blob: 7b1393c71ddb57e1a1ae1ebdbff06f4ca675b182 [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);
John Kessenich140f3df2015-06-26 16:58:36 -0600213
John Kessenich121853f2017-05-31 17:11:16 -0600214 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600215 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600216 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700217 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600218 int sequenceDepth;
219
Lei Zhang17535f72016-05-04 15:55:59 -0400220 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400221
John Kessenich140f3df2015-06-26 16:58:36 -0600222 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
223 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700224 bool inEntryPoint;
225 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700226 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 -0700227 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600228 const glslang::TIntermediate* glslangIntermediate;
John Kessenich605afc72019-06-17 23:33:09 -0600229 bool nanMinMaxClamp; // true if use NMin/NMax/NClamp instead of FMin/FMax/FClamp
John Kessenich140f3df2015-06-26 16:58:36 -0600230 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800231 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600232
John Kessenich2f273362015-07-18 22:34:27 -0600233 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600234 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600235 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700236 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700237 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
238 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600239 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700240 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600241 // Map pointee types for EbtReference to their forward pointers
242 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich9c14f772019-06-17 08:38:35 -0600243 // Type forcing, for when SPIR-V wants a different type than the AST,
244 // requiring local translation to and from SPIR-V type on every access.
245 // Maps <builtin-variable-id -> AST-required-type-id>
246 std::unordered_map<spv::Id, spv::Id> forceType;
John Kessenich140f3df2015-06-26 16:58:36 -0600247};
248
249//
250// Helper functions for translating glslang representations to SPIR-V enumerants.
251//
252
253// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700254spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600255{
John Kessenich66e2faf2016-03-12 18:34:36 -0700256 switch (source) {
257 case glslang::EShSourceGlsl:
258 switch (profile) {
259 case ENoProfile:
260 case ECoreProfile:
261 case ECompatibilityProfile:
262 return spv::SourceLanguageGLSL;
263 case EEsProfile:
264 return spv::SourceLanguageESSL;
265 default:
266 return spv::SourceLanguageUnknown;
267 }
268 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600269 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600270 default:
271 return spv::SourceLanguageUnknown;
272 }
273}
274
275// Translate glslang language (stage) to SPIR-V execution model.
276spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
277{
278 switch (stage) {
279 case EShLangVertex: return spv::ExecutionModelVertex;
280 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
281 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
282 case EShLangGeometry: return spv::ExecutionModelGeometry;
283 case EShLangFragment: return spv::ExecutionModelFragment;
284 case EShLangCompute: return spv::ExecutionModelGLCompute;
Chao Chen3c366992018-09-19 11:41:59 -0700285#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -0700286 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
287 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
288 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
289 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
290 case EShLangMissNV: return spv::ExecutionModelMissNV;
291 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700292 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
293 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
294#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600295 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700296 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600297 return spv::ExecutionModelFragment;
298 }
299}
300
John Kessenich140f3df2015-06-26 16:58:36 -0600301// Translate glslang sampler type to SPIR-V dimensionality.
302spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
303{
304 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700305 case glslang::Esd1D: return spv::Dim1D;
306 case glslang::Esd2D: return spv::Dim2D;
307 case glslang::Esd3D: return spv::Dim3D;
308 case glslang::EsdCube: return spv::DimCube;
309 case glslang::EsdRect: return spv::DimRect;
310 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700311 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600312 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700313 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600314 return spv::Dim2D;
315 }
316}
317
John Kessenichf6640762016-08-01 19:44:00 -0600318// Translate glslang precision to SPIR-V precision decorations.
319spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600320{
John Kessenichf6640762016-08-01 19:44:00 -0600321 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700322 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600323 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600324 default:
325 return spv::NoPrecision;
326 }
327}
328
John Kessenichf6640762016-08-01 19:44:00 -0600329// Translate glslang type to SPIR-V precision decorations.
330spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
331{
332 return TranslatePrecisionDecoration(type.getQualifier().precision);
333}
334
John Kessenich140f3df2015-06-26 16:58:36 -0600335// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600336spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600337{
338 if (type.getBasicType() == glslang::EbtBlock) {
339 switch (type.getQualifier().storage) {
340 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600341 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 case glslang::EvqVaryingIn: return spv::DecorationBlock;
343 case glslang::EvqVaryingOut: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700344#ifdef NV_EXTENSIONS
345 case glslang::EvqPayloadNV: return spv::DecorationBlock;
346 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
347 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700348 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
349 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700350#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600351 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700352 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600353 break;
354 }
355 }
356
John Kessenich4016e382016-07-15 11:53:56 -0600357 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600358}
359
Rex Xu1da878f2016-02-21 20:59:01 +0800360// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500361void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800362{
Jeff Bolz36831c92018-09-05 10:11:41 -0500363 if (!useVulkanMemoryModel) {
364 if (qualifier.coherent)
365 memory.push_back(spv::DecorationCoherent);
366 if (qualifier.volatil) {
367 memory.push_back(spv::DecorationVolatile);
368 memory.push_back(spv::DecorationCoherent);
369 }
John Kessenich14b85d32018-06-04 15:36:03 -0600370 }
Rex Xu1da878f2016-02-21 20:59:01 +0800371 if (qualifier.restrict)
372 memory.push_back(spv::DecorationRestrict);
373 if (qualifier.readonly)
374 memory.push_back(spv::DecorationNonWritable);
375 if (qualifier.writeonly)
376 memory.push_back(spv::DecorationNonReadable);
377}
378
John Kessenich140f3df2015-06-26 16:58:36 -0600379// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700380spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600381{
382 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700383 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600384 case glslang::ElmRowMajor:
385 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700386 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600387 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700388 default:
389 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600390 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600391 }
392 } else {
393 switch (type.getBasicType()) {
394 default:
John Kessenich4016e382016-07-15 11:53:56 -0600395 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600396 break;
397 case glslang::EbtBlock:
398 switch (type.getQualifier().storage) {
399 case glslang::EvqUniform:
400 case glslang::EvqBuffer:
401 switch (type.getQualifier().layoutPacking) {
402 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600403 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
404 default:
John Kessenich4016e382016-07-15 11:53:56 -0600405 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600406 }
407 case glslang::EvqVaryingIn:
408 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700409 if (type.getQualifier().isTaskMemory()) {
410 switch (type.getQualifier().layoutPacking) {
411 case glslang::ElpShared: return spv::DecorationGLSLShared;
412 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
413 default: break;
414 }
415 } else {
416 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
417 }
John Kessenich4016e382016-07-15 11:53:56 -0600418 return spv::DecorationMax;
Chao Chenb50c02e2018-09-19 11:42:24 -0700419#ifdef NV_EXTENSIONS
420 case glslang::EvqPayloadNV:
421 case glslang::EvqPayloadInNV:
422 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700423 case glslang::EvqCallableDataNV:
424 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700425 return spv::DecorationMax;
426#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600427 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700428 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600429 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600430 }
431 }
432 }
433}
434
435// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600436// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700437// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800438spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600439{
Rex Xubbceed72016-05-21 09:40:44 +0800440 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700441 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600442 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800443 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700444 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700445 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600446 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800447#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800448 else if (qualifier.explicitInterp) {
449 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800450 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800451 }
Rex Xu9d93a232016-05-05 12:30:44 +0800452#endif
Rex Xubbceed72016-05-21 09:40:44 +0800453 else
John Kessenich4016e382016-07-15 11:53:56 -0600454 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800455}
456
457// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600458// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800459// should be applied.
460spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
461{
462 if (qualifier.patch)
463 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700464 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600465 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700466 else if (qualifier.sample) {
467 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600468 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700469 } else
John Kessenich4016e382016-07-15 11:53:56 -0600470 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600471}
472
John Kessenich92187592016-02-01 13:45:25 -0700473// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700474spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600475{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700476 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600477 return spv::DecorationInvariant;
478 else
John Kessenich4016e382016-07-15 11:53:56 -0600479 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600480}
481
qining9220dbb2016-05-04 17:34:38 -0400482// If glslang type is noContraction, return SPIR-V NoContraction decoration.
483spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
484{
485 if (qualifier.noContraction)
486 return spv::DecorationNoContraction;
487 else
John Kessenich4016e382016-07-15 11:53:56 -0600488 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400489}
490
John Kessenich5611c6d2018-04-05 11:25:02 -0600491// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
492spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
493{
494 if (qualifier.isNonUniform()) {
495 builder.addExtension("SPV_EXT_descriptor_indexing");
496 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
497 return spv::DecorationNonUniformEXT;
498 } else
499 return spv::DecorationMax;
500}
501
Jeff Bolz36831c92018-09-05 10:11:41 -0500502spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
503{
504 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
505 return spv::MemoryAccessMaskNone;
506 }
507 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
508 if (coherentFlags.volatil ||
509 coherentFlags.coherent ||
510 coherentFlags.devicecoherent ||
511 coherentFlags.queuefamilycoherent ||
512 coherentFlags.workgroupcoherent ||
513 coherentFlags.subgroupcoherent) {
514 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
515 spv::MemoryAccessMakePointerVisibleKHRMask;
516 }
517 if (coherentFlags.nonprivate) {
518 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
519 }
520 if (coherentFlags.volatil) {
521 mask = mask | spv::MemoryAccessVolatileMask;
522 }
523 if (mask != spv::MemoryAccessMaskNone) {
524 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
525 }
526 return mask;
527}
528
529spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
530{
531 if (!glslangIntermediate->usingVulkanMemoryModel()) {
532 return spv::ImageOperandsMaskNone;
533 }
534 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
535 if (coherentFlags.volatil ||
536 coherentFlags.coherent ||
537 coherentFlags.devicecoherent ||
538 coherentFlags.queuefamilycoherent ||
539 coherentFlags.workgroupcoherent ||
540 coherentFlags.subgroupcoherent) {
541 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
542 spv::ImageOperandsMakeTexelVisibleKHRMask;
543 }
544 if (coherentFlags.nonprivate) {
545 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
546 }
547 if (coherentFlags.volatil) {
548 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
549 }
550 if (mask != spv::ImageOperandsMaskNone) {
551 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
552 }
553 return mask;
554}
555
556spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
557{
558 spv::Builder::AccessChain::CoherentFlags flags;
559 flags.coherent = type.getQualifier().coherent;
560 flags.devicecoherent = type.getQualifier().devicecoherent;
561 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
562 // shared variables are implicitly workgroupcoherent in GLSL.
563 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
564 type.getQualifier().storage == glslang::EvqShared;
565 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600566 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500567 // *coherent variables are implicitly nonprivate in GLSL
568 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500569 flags.subgroupcoherent ||
570 flags.workgroupcoherent ||
571 flags.queuefamilycoherent ||
572 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600573 flags.coherent ||
574 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500575 flags.isImage = type.getBasicType() == glslang::EbtSampler;
576 return flags;
577}
578
579spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
580{
581 spv::Scope scope;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600582 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500583 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
584 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
585 } else if (coherentFlags.devicecoherent) {
586 scope = spv::ScopeDevice;
587 } else if (coherentFlags.queuefamilycoherent) {
588 scope = spv::ScopeQueueFamilyKHR;
589 } else if (coherentFlags.workgroupcoherent) {
590 scope = spv::ScopeWorkgroup;
591 } else if (coherentFlags.subgroupcoherent) {
592 scope = spv::ScopeSubgroup;
593 } else {
594 scope = spv::ScopeMax;
595 }
596 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
597 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
598 }
599 return scope;
600}
601
David Netoa901ffe2016-06-08 14:11:40 +0100602// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
603// associated capabilities when required. For some built-in variables, a capability
604// is generated only when using the variable in an executable instruction, but not when
605// just declaring a struct member variable with it. This is true for PointSize,
606// ClipDistance, and CullDistance.
607spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600608{
609 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700610 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600611 // Defer adding the capability until the built-in is actually used.
612 if (! memberDeclaration) {
613 switch (glslangIntermediate->getStage()) {
614 case EShLangGeometry:
615 builder.addCapability(spv::CapabilityGeometryPointSize);
616 break;
617 case EShLangTessControl:
618 case EShLangTessEvaluation:
619 builder.addCapability(spv::CapabilityTessellationPointSize);
620 break;
621 default:
622 break;
623 }
John Kessenich92187592016-02-01 13:45:25 -0700624 }
625 return spv::BuiltInPointSize;
626
John Kessenichebb50532016-05-16 19:22:05 -0600627 // These *Distance capabilities logically belong here, but if the member is declared and
628 // then never used, consumers of SPIR-V prefer the capability not be declared.
629 // They are now generated when used, rather than here when declared.
630 // Potentially, the specification should be more clear what the minimum
631 // use needed is to trigger the capability.
632 //
John Kessenich92187592016-02-01 13:45:25 -0700633 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100634 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800635 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700636 return spv::BuiltInClipDistance;
637
638 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100639 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800640 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700641 return spv::BuiltInCullDistance;
642
643 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600644 builder.addCapability(spv::CapabilityMultiViewport);
645 if (glslangIntermediate->getStage() == EShLangVertex ||
646 glslangIntermediate->getStage() == EShLangTessControl ||
647 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800648
John Kessenichba6a3c22017-09-13 13:22:50 -0600649 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
650 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800651 }
John Kessenich92187592016-02-01 13:45:25 -0700652 return spv::BuiltInViewportIndex;
653
John Kessenich5e801132016-02-15 11:09:46 -0700654 case glslang::EbvSampleId:
655 builder.addCapability(spv::CapabilitySampleRateShading);
656 return spv::BuiltInSampleId;
657
658 case glslang::EbvSamplePosition:
659 builder.addCapability(spv::CapabilitySampleRateShading);
660 return spv::BuiltInSamplePosition;
661
662 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700663 return spv::BuiltInSampleMask;
664
John Kessenich78a45572016-07-08 14:05:15 -0600665 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700666#ifdef NV_EXTENSIONS
667 if (glslangIntermediate->getStage() == EShLangMeshNV) {
668 return spv::BuiltInLayer;
669 }
670#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600671 builder.addCapability(spv::CapabilityGeometry);
672 if (glslangIntermediate->getStage() == EShLangVertex ||
673 glslangIntermediate->getStage() == EShLangTessControl ||
674 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800675
John Kessenichba6a3c22017-09-13 13:22:50 -0600676 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
677 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800678 }
John Kessenich78a45572016-07-08 14:05:15 -0600679 return spv::BuiltInLayer;
680
John Kessenich140f3df2015-06-26 16:58:36 -0600681 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600682 case glslang::EbvVertexId: return spv::BuiltInVertexId;
683 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700684 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
685 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800686
John Kessenichda581a22015-10-14 14:10:30 -0600687 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700688 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800689 builder.addCapability(spv::CapabilityDrawParameters);
690 return spv::BuiltInBaseVertex;
691
John Kessenichda581a22015-10-14 14:10:30 -0600692 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700693 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800694 builder.addCapability(spv::CapabilityDrawParameters);
695 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200696
John Kessenichda581a22015-10-14 14:10:30 -0600697 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700698 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800699 builder.addCapability(spv::CapabilityDrawParameters);
700 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200701
702 case glslang::EbvPrimitiveId:
703 if (glslangIntermediate->getStage() == EShLangFragment)
704 builder.addCapability(spv::CapabilityGeometry);
705 return spv::BuiltInPrimitiveId;
706
Rex Xu37cdcee2017-06-29 17:46:34 +0800707 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800708 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
709 builder.addCapability(spv::CapabilityStencilExportEXT);
710 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800711
John Kessenich140f3df2015-06-26 16:58:36 -0600712 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600713 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
714 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
715 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
716 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
717 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
718 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
719 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600720 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
721 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
722 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
723 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
724 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
725 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
726 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
727 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800728
Rex Xu574ab042016-04-14 16:53:07 +0800729 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800730 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800731 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
732 return spv::BuiltInSubgroupSize;
733
Rex Xu574ab042016-04-14 16:53:07 +0800734 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800735 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800736 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
737 return spv::BuiltInSubgroupLocalInvocationId;
738
Rex Xu574ab042016-04-14 16:53:07 +0800739 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800740 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
741 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600742 return spv::BuiltInSubgroupEqMask;
Rex Xu51596642016-09-21 18:56:12 +0800743
Rex Xu574ab042016-04-14 16:53:07 +0800744 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800745 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
746 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600747 return spv::BuiltInSubgroupGeMask;
Rex Xu51596642016-09-21 18:56:12 +0800748
Rex Xu574ab042016-04-14 16:53:07 +0800749 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800750 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
751 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600752 return spv::BuiltInSubgroupGtMask;
Rex Xu51596642016-09-21 18:56:12 +0800753
Rex Xu574ab042016-04-14 16:53:07 +0800754 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800755 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
756 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600757 return spv::BuiltInSubgroupLeMask;
Rex Xu51596642016-09-21 18:56:12 +0800758
Rex Xu574ab042016-04-14 16:53:07 +0800759 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800760 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
761 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
John Kessenich9c14f772019-06-17 08:38:35 -0600762 return spv::BuiltInSubgroupLtMask;
Rex Xu51596642016-09-21 18:56:12 +0800763
John Kessenich66011cb2018-03-06 16:12:04 -0700764 case glslang::EbvNumSubgroups:
765 builder.addCapability(spv::CapabilityGroupNonUniform);
766 return spv::BuiltInNumSubgroups;
767
768 case glslang::EbvSubgroupID:
769 builder.addCapability(spv::CapabilityGroupNonUniform);
770 return spv::BuiltInSubgroupId;
771
772 case glslang::EbvSubgroupSize2:
773 builder.addCapability(spv::CapabilityGroupNonUniform);
774 return spv::BuiltInSubgroupSize;
775
776 case glslang::EbvSubgroupInvocation2:
777 builder.addCapability(spv::CapabilityGroupNonUniform);
778 return spv::BuiltInSubgroupLocalInvocationId;
779
780 case glslang::EbvSubgroupEqMask2:
781 builder.addCapability(spv::CapabilityGroupNonUniform);
782 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
783 return spv::BuiltInSubgroupEqMask;
784
785 case glslang::EbvSubgroupGeMask2:
786 builder.addCapability(spv::CapabilityGroupNonUniform);
787 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
788 return spv::BuiltInSubgroupGeMask;
789
790 case glslang::EbvSubgroupGtMask2:
791 builder.addCapability(spv::CapabilityGroupNonUniform);
792 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
793 return spv::BuiltInSubgroupGtMask;
794
795 case glslang::EbvSubgroupLeMask2:
796 builder.addCapability(spv::CapabilityGroupNonUniform);
797 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
798 return spv::BuiltInSubgroupLeMask;
799
800 case glslang::EbvSubgroupLtMask2:
801 builder.addCapability(spv::CapabilityGroupNonUniform);
802 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
803 return spv::BuiltInSubgroupLtMask;
John Kessenich9c14f772019-06-17 08:38:35 -0600804
Rex Xu9d93a232016-05-05 12:30:44 +0800805#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800806 case glslang::EbvBaryCoordNoPersp:
807 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
808 return spv::BuiltInBaryCoordNoPerspAMD;
809
810 case glslang::EbvBaryCoordNoPerspCentroid:
811 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
812 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
813
814 case glslang::EbvBaryCoordNoPerspSample:
815 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
816 return spv::BuiltInBaryCoordNoPerspSampleAMD;
817
818 case glslang::EbvBaryCoordSmooth:
819 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
820 return spv::BuiltInBaryCoordSmoothAMD;
821
822 case glslang::EbvBaryCoordSmoothCentroid:
823 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
824 return spv::BuiltInBaryCoordSmoothCentroidAMD;
825
826 case glslang::EbvBaryCoordSmoothSample:
827 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
828 return spv::BuiltInBaryCoordSmoothSampleAMD;
829
830 case glslang::EbvBaryCoordPullModel:
831 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
832 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800833#endif
chaoc771d89f2017-01-13 01:10:53 -0800834
John Kessenich6c8aaac2017-02-27 01:20:51 -0700835 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700836 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700837 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700838 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700839
840 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700841 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700842 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700843 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700844
Daniel Koch5154db52018-11-26 10:01:58 -0500845 case glslang::EbvFragSizeEXT:
846 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
847 builder.addCapability(spv::CapabilityFragmentDensityEXT);
848 return spv::BuiltInFragSizeEXT;
849
850 case glslang::EbvFragInvocationCountEXT:
851 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
852 builder.addCapability(spv::CapabilityFragmentDensityEXT);
853 return spv::BuiltInFragInvocationCountEXT;
854
chaoc771d89f2017-01-13 01:10:53 -0800855#ifdef NV_EXTENSIONS
856 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800857 if (!memberDeclaration) {
858 builder.addExtension(spv::E_SPV_NV_viewport_array2);
859 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
860 }
chaoc771d89f2017-01-13 01:10:53 -0800861 return spv::BuiltInViewportMaskNV;
862 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800863 if (!memberDeclaration) {
864 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
865 builder.addCapability(spv::CapabilityShaderStereoViewNV);
866 }
chaoc771d89f2017-01-13 01:10:53 -0800867 return spv::BuiltInSecondaryPositionNV;
868 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800869 if (!memberDeclaration) {
870 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
871 builder.addCapability(spv::CapabilityShaderStereoViewNV);
872 }
chaoc771d89f2017-01-13 01:10:53 -0800873 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800874 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800875 if (!memberDeclaration) {
876 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
877 builder.addCapability(spv::CapabilityPerViewAttributesNV);
878 }
chaocdf3956c2017-02-14 14:52:34 -0800879 return spv::BuiltInPositionPerViewNV;
880 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800881 if (!memberDeclaration) {
882 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
883 builder.addCapability(spv::CapabilityPerViewAttributesNV);
884 }
chaocdf3956c2017-02-14 14:52:34 -0800885 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700886 case glslang::EbvFragFullyCoveredNV:
887 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
888 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
889 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700890 case glslang::EbvFragmentSizeNV:
891 builder.addExtension(spv::E_SPV_NV_shading_rate);
892 builder.addCapability(spv::CapabilityShadingRateNV);
893 return spv::BuiltInFragmentSizeNV;
894 case glslang::EbvInvocationsPerPixelNV:
895 builder.addExtension(spv::E_SPV_NV_shading_rate);
896 builder.addCapability(spv::CapabilityShadingRateNV);
897 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700898
Daniel Koch593a4e02019-05-27 16:46:31 -0400899 // ray tracing
Chao Chenb50c02e2018-09-19 11:42:24 -0700900 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700901 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700902 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700903 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700904 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700905 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700906 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700907 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700908 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700909 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700910 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700911 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700912 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700913 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700914 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700915 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700916 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700917 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700918 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700919 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700920 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700921 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700922 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700923 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700924 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700925 return spv::BuiltInWorldToObjectNV;
926 case glslang::EbvIncomingRayFlagsNV:
927 return spv::BuiltInIncomingRayFlagsNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400928
929 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700930 case glslang::EbvBaryCoordNV:
931 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
932 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
933 return spv::BuiltInBaryCoordNV;
934 case glslang::EbvBaryCoordNoPerspNV:
935 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
936 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
937 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400938
939 // mesh shaders
940 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700941 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400942 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700943 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400944 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700945 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400946 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700947 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400948 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700949 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400950 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700951 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400952 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700953 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400954 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700955 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400956#endif
Daniel Koch2cb2f192019-06-04 08:43:32 -0400957
958 // sm builtins
959 case glslang::EbvWarpsPerSM:
960 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
961 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
962 return spv::BuiltInWarpsPerSMNV;
963 case glslang::EbvSMCount:
964 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
965 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
966 return spv::BuiltInSMCountNV;
967 case glslang::EbvWarpID:
968 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
969 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
970 return spv::BuiltInWarpIDNV;
971 case glslang::EbvSMID:
972 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
973 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
974 return spv::BuiltInSMIDNV;
Rex Xu3e783f92017-02-22 16:44:48 +0800975 default:
976 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600977 }
978}
979
Rex Xufc618912015-09-09 16:42:49 +0800980// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700981spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800982{
983 assert(type.getBasicType() == glslang::EbtSampler);
984
John Kessenich5d0fa972016-02-15 11:57:00 -0700985 // Check for capabilities
986 switch (type.getQualifier().layoutFormat) {
987 case glslang::ElfRg32f:
988 case glslang::ElfRg16f:
989 case glslang::ElfR11fG11fB10f:
990 case glslang::ElfR16f:
991 case glslang::ElfRgba16:
992 case glslang::ElfRgb10A2:
993 case glslang::ElfRg16:
994 case glslang::ElfRg8:
995 case glslang::ElfR16:
996 case glslang::ElfR8:
997 case glslang::ElfRgba16Snorm:
998 case glslang::ElfRg16Snorm:
999 case glslang::ElfRg8Snorm:
1000 case glslang::ElfR16Snorm:
1001 case glslang::ElfR8Snorm:
1002
1003 case glslang::ElfRg32i:
1004 case glslang::ElfRg16i:
1005 case glslang::ElfRg8i:
1006 case glslang::ElfR16i:
1007 case glslang::ElfR8i:
1008
1009 case glslang::ElfRgb10a2ui:
1010 case glslang::ElfRg32ui:
1011 case glslang::ElfRg16ui:
1012 case glslang::ElfRg8ui:
1013 case glslang::ElfR16ui:
1014 case glslang::ElfR8ui:
1015 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1016 break;
1017
1018 default:
1019 break;
1020 }
1021
1022 // do the translation
Rex Xufc618912015-09-09 16:42:49 +08001023 switch (type.getQualifier().layoutFormat) {
1024 case glslang::ElfNone: return spv::ImageFormatUnknown;
1025 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1026 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1027 case glslang::ElfR32f: return spv::ImageFormatR32f;
1028 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1029 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1030 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1031 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1032 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1033 case glslang::ElfR16f: return spv::ImageFormatR16f;
1034 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1035 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1036 case glslang::ElfRg16: return spv::ImageFormatRg16;
1037 case glslang::ElfRg8: return spv::ImageFormatRg8;
1038 case glslang::ElfR16: return spv::ImageFormatR16;
1039 case glslang::ElfR8: return spv::ImageFormatR8;
1040 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1041 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1042 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1043 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1044 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1045 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1046 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1047 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1048 case glslang::ElfR32i: return spv::ImageFormatR32i;
1049 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1050 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1051 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1052 case glslang::ElfR16i: return spv::ImageFormatR16i;
1053 case glslang::ElfR8i: return spv::ImageFormatR8i;
1054 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1055 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1056 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1057 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1058 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1059 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1060 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1061 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1062 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1063 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001064 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001065 }
1066}
1067
John Kesseniche18fd202018-01-30 11:01:39 -07001068spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001069{
John Kesseniche18fd202018-01-30 11:01:39 -07001070 if (selectionNode.getFlatten())
1071 return spv::SelectionControlFlattenMask;
1072 if (selectionNode.getDontFlatten())
1073 return spv::SelectionControlDontFlattenMask;
1074 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001075}
1076
John Kesseniche18fd202018-01-30 11:01:39 -07001077spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001078{
John Kesseniche18fd202018-01-30 11:01:39 -07001079 if (switchNode.getFlatten())
1080 return spv::SelectionControlFlattenMask;
1081 if (switchNode.getDontFlatten())
1082 return spv::SelectionControlDontFlattenMask;
1083 return spv::SelectionControlMaskNone;
1084}
1085
John Kessenicha2858d92018-01-31 08:11:18 -07001086// return a non-0 dependency if the dependency argument must be set
1087spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001088 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001089{
1090 spv::LoopControlMask control = spv::LoopControlMaskNone;
1091
1092 if (loopNode.getDontUnroll())
1093 control = control | spv::LoopControlDontUnrollMask;
1094 if (loopNode.getUnroll())
1095 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001096 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001097 control = control | spv::LoopControlDependencyInfiniteMask;
1098 else if (loopNode.getLoopDependency() > 0) {
1099 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001100 operands.push_back((unsigned int)loopNode.getLoopDependency());
1101 }
1102 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1103 if (loopNode.getMinIterations() > 0) {
1104 control = control | spv::LoopControlMinIterationsMask;
1105 operands.push_back(loopNode.getMinIterations());
1106 }
1107 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1108 control = control | spv::LoopControlMaxIterationsMask;
1109 operands.push_back(loopNode.getMaxIterations());
1110 }
1111 if (loopNode.getIterationMultiple() > 1) {
1112 control = control | spv::LoopControlIterationMultipleMask;
1113 operands.push_back(loopNode.getIterationMultiple());
1114 }
1115 if (loopNode.getPeelCount() > 0) {
1116 control = control | spv::LoopControlPeelCountMask;
1117 operands.push_back(loopNode.getPeelCount());
1118 }
1119 if (loopNode.getPartialCount() > 0) {
1120 control = control | spv::LoopControlPartialCountMask;
1121 operands.push_back(loopNode.getPartialCount());
1122 }
John Kessenicha2858d92018-01-31 08:11:18 -07001123 }
John Kesseniche18fd202018-01-30 11:01:39 -07001124
1125 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001126}
1127
John Kessenicha5c5fb62017-05-05 05:09:58 -06001128// Translate glslang type to SPIR-V storage class.
1129spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1130{
1131 if (type.getQualifier().isPipeInput())
1132 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001133 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001134 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001135
1136 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1137 type.getQualifier().storage == glslang::EvqUniform) {
1138 if (type.getBasicType() == glslang::EbtAtomicUint)
1139 return spv::StorageClassAtomicCounter;
1140 if (type.containsOpaque())
1141 return spv::StorageClassUniformConstant;
1142 }
1143
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001144#ifdef NV_EXTENSIONS
1145 if (type.getQualifier().isUniformOrBuffer() &&
1146 type.getQualifier().layoutShaderRecordNV) {
1147 return spv::StorageClassShaderRecordBufferNV;
1148 }
1149#endif
1150
John Kessenichbed4e4f2017-09-08 02:38:07 -06001151 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001152 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001153 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001154 }
1155
1156 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001157 if (type.getQualifier().layoutPushConstant)
1158 return spv::StorageClassPushConstant;
1159 if (type.getBasicType() == glslang::EbtBlock)
1160 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001161 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001162 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001163
1164 switch (type.getQualifier().storage) {
1165 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1166 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1167 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1168 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001169#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001170 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1171 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1172 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1173 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1174 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001175#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001176 default:
1177 assert(0);
1178 break;
1179 }
1180
1181 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001182}
1183
John Kessenich5611c6d2018-04-05 11:25:02 -06001184// Add capabilities pertaining to how an array is indexed.
1185void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1186 const glslang::TType& indexType)
1187{
1188 if (indexType.getQualifier().isNonUniform()) {
1189 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001190 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001191 if (baseType.getBasicType() == glslang::EbtSampler) {
1192 if (baseType.getQualifier().hasAttachment())
1193 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1194 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1195 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1196 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1197 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1198 else if (baseType.isImage())
1199 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1200 else if (baseType.isTexture())
1201 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1202 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1203 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1204 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1205 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1206 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1207 }
1208 } else {
1209 // assume a dynamically uniform index
1210 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001211 if (baseType.getQualifier().hasAttachment()) {
1212 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001213 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001214 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1215 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001216 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001217 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1218 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001219 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001220 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001221 }
1222 }
1223}
1224
qining25262b32016-05-06 17:25:16 -04001225// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001226// descriptor set.
1227bool IsDescriptorResource(const glslang::TType& type)
1228{
John Kessenichf7497e22016-03-08 21:36:22 -07001229 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001230 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001231 return type.getQualifier().isUniformOrBuffer() &&
1232#ifdef NV_EXTENSIONS
1233 ! type.getQualifier().layoutShaderRecordNV &&
1234#endif
1235 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001236
1237 // non block...
1238 // basically samplerXXX/subpass/sampler/texture are all included
1239 // if they are the global-scope-class, not the function parameter
1240 // (or local, if they ever exist) class.
1241 if (type.getBasicType() == glslang::EbtSampler)
1242 return type.getQualifier().isUniformOrBuffer();
1243
1244 // None of the above.
1245 return false;
1246}
1247
John Kesseniche0b6cad2015-12-24 10:30:13 -07001248void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1249{
1250 if (child.layoutMatrix == glslang::ElmNone)
1251 child.layoutMatrix = parent.layoutMatrix;
1252
1253 if (parent.invariant)
1254 child.invariant = true;
1255 if (parent.nopersp)
1256 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001257#ifdef AMD_EXTENSIONS
1258 if (parent.explicitInterp)
1259 child.explicitInterp = true;
1260#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001261 if (parent.flat)
1262 child.flat = true;
1263 if (parent.centroid)
1264 child.centroid = true;
1265 if (parent.patch)
1266 child.patch = true;
1267 if (parent.sample)
1268 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001269 if (parent.coherent)
1270 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001271 if (parent.devicecoherent)
1272 child.devicecoherent = true;
1273 if (parent.queuefamilycoherent)
1274 child.queuefamilycoherent = true;
1275 if (parent.workgroupcoherent)
1276 child.workgroupcoherent = true;
1277 if (parent.subgroupcoherent)
1278 child.subgroupcoherent = true;
1279 if (parent.nonprivate)
1280 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001281 if (parent.volatil)
1282 child.volatil = true;
1283 if (parent.restrict)
1284 child.restrict = true;
1285 if (parent.readonly)
1286 child.readonly = true;
1287 if (parent.writeonly)
1288 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001289#ifdef NV_EXTENSIONS
1290 if (parent.perPrimitiveNV)
1291 child.perPrimitiveNV = true;
1292 if (parent.perViewNV)
1293 child.perViewNV = true;
1294 if (parent.perTaskNV)
1295 child.perTaskNV = true;
1296#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001297}
1298
John Kessenichf2b7f332016-09-01 17:05:23 -06001299bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001300{
John Kessenich7b9fa252016-01-21 18:56:57 -07001301 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001302 // - struct members might inherit from a struct declaration
1303 // (note that non-block structs don't explicitly inherit,
1304 // only implicitly, meaning no decoration involved)
1305 // - affect decorations on the struct members
1306 // (note smooth does not, and expecting something like volatile
1307 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001308 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001309 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001310}
1311
John Kessenich140f3df2015-06-26 16:58:36 -06001312//
1313// Implement the TGlslangToSpvTraverser class.
1314//
1315
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001316TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001317 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1318 : TIntermTraverser(true, false, true),
1319 options(options),
1320 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001321 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001322 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001323 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich605afc72019-06-17 23:33:09 -06001324 glslangIntermediate(glslangIntermediate),
1325 nanMinMaxClamp(glslangIntermediate->getNanMinMaxClamp())
John Kessenich140f3df2015-06-26 16:58:36 -06001326{
1327 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1328
1329 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001330 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1331 glslangIntermediate->getVersion());
1332
John Kessenich121853f2017-05-31 17:11:16 -06001333 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001334 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001335 builder.setSourceFile(glslangIntermediate->getSourceFile());
1336
1337 // Set the source shader's text. If for SPV version 1.0, include
1338 // a preamble in comments stating the OpModuleProcessed instructions.
1339 // Otherwise, emit those as actual instructions.
1340 std::string text;
1341 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1342 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001343 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001344 text.append("// OpModuleProcessed ");
1345 text.append(processes[p]);
1346 text.append("\n");
1347 } else
1348 builder.addModuleProcessed(processes[p]);
1349 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001350 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001351 text.append("#line 1\n");
1352 text.append(glslangIntermediate->getSourceText());
1353 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001354 // Pass name and text for all included files
1355 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1356 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1357 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001358 }
John Kessenich140f3df2015-06-26 16:58:36 -06001359 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001360
1361 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1362 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1363
1364 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1365 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1366 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1367 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1368 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001369 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001370 memoryModel = spv::MemoryModelVulkanKHR;
1371 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001372 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001373 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001374 builder.setMemoryModel(addressingModel, memoryModel);
1375
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001376 if (glslangIntermediate->usingVariablePointers()) {
1377 builder.addCapability(spv::CapabilityVariablePointers);
1378 }
1379
John Kessenicheee9d532016-09-19 18:09:30 -06001380 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1381 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001382
1383 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001384 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1385 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001386 builder.addSourceExtension(it->c_str());
1387
1388 // Add the top-level modes for this shader.
1389
John Kessenich92187592016-02-01 13:45:25 -07001390 if (glslangIntermediate->getXfbMode()) {
1391 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001392 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001393 }
John Kessenich140f3df2015-06-26 16:58:36 -06001394
1395 unsigned int mode;
1396 switch (glslangIntermediate->getStage()) {
1397 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001398 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001399 break;
1400
steve-lunarge7412492017-03-23 11:56:07 -06001401 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001402 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001403 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001404
steve-lunarge7412492017-03-23 11:56:07 -06001405 glslang::TLayoutGeometry primitive;
1406
1407 if (glslangIntermediate->getStage() == EShLangTessControl) {
1408 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1409 primitive = glslangIntermediate->getOutputPrimitive();
1410 } else {
1411 primitive = glslangIntermediate->getInputPrimitive();
1412 }
1413
1414 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001415 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1416 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1417 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001418 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001419 }
John Kessenich4016e382016-07-15 11:53:56 -06001420 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001421 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1422
John Kesseniche6903322015-10-13 16:29:02 -06001423 switch (glslangIntermediate->getVertexSpacing()) {
1424 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1425 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1426 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001427 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001428 }
John Kessenich4016e382016-07-15 11:53:56 -06001429 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001430 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1431
1432 switch (glslangIntermediate->getVertexOrder()) {
1433 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1434 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001435 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001436 }
John Kessenich4016e382016-07-15 11:53:56 -06001437 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001438 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1439
1440 if (glslangIntermediate->getPointMode())
1441 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001442 break;
1443
1444 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001445 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001446 switch (glslangIntermediate->getInputPrimitive()) {
1447 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1448 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1449 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001450 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001451 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001452 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001453 }
John Kessenich4016e382016-07-15 11:53:56 -06001454 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001455 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001456
John Kessenich140f3df2015-06-26 16:58:36 -06001457 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1458
1459 switch (glslangIntermediate->getOutputPrimitive()) {
1460 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1461 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1462 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001463 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001464 }
John Kessenich4016e382016-07-15 11:53:56 -06001465 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001466 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1467 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1468 break;
1469
1470 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001471 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001472 if (glslangIntermediate->getPixelCenterInteger())
1473 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001474
John Kessenich140f3df2015-06-26 16:58:36 -06001475 if (glslangIntermediate->getOriginUpperLeft())
1476 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001477 else
1478 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001479
1480 if (glslangIntermediate->getEarlyFragmentTests())
1481 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1482
chaocc1204522017-06-30 17:14:30 -07001483 if (glslangIntermediate->getPostDepthCoverage()) {
1484 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1485 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1486 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1487 }
1488
John Kesseniche6903322015-10-13 16:29:02 -06001489 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001490 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1491 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001492 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001493 }
John Kessenich4016e382016-07-15 11:53:56 -06001494 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001495 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1496
1497 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1498 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05001499
1500 switch (glslangIntermediate->getInterlockOrdering()) {
1501 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT; break;
1502 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT; break;
1503 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT; break;
1504 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT; break;
1505 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT; break;
1506 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT; break;
1507 default: mode = spv::ExecutionModeMax; break;
1508 }
1509 if (mode != spv::ExecutionModeMax) {
1510 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1511 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1512 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1513 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1514 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1515 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1516 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1517 } else {
1518 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1519 }
1520 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1521 }
1522
John Kessenich140f3df2015-06-26 16:58:36 -06001523 break;
1524
1525 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001526 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001527 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1528 glslangIntermediate->getLocalSize(1),
1529 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001530#ifdef NV_EXTENSIONS
1531 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1532 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1533 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1534 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1535 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1536 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1537 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1538 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1539 }
1540#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001541 break;
1542
Chao Chen3c366992018-09-19 11:41:59 -07001543#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001544 case EShLangRayGenNV:
1545 case EShLangIntersectNV:
1546 case EShLangAnyHitNV:
1547 case EShLangClosestHitNV:
1548 case EShLangMissNV:
1549 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001550 builder.addCapability(spv::CapabilityRayTracingNV);
1551 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001552 break;
Chao Chen3c366992018-09-19 11:41:59 -07001553 case EShLangTaskNV:
1554 case EShLangMeshNV:
1555 builder.addCapability(spv::CapabilityMeshShadingNV);
1556 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1557 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1558 glslangIntermediate->getLocalSize(1),
1559 glslangIntermediate->getLocalSize(2));
1560 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1561 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1562 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1563
1564 switch (glslangIntermediate->getOutputPrimitive()) {
1565 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1566 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1567 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1568 default: mode = spv::ExecutionModeMax; break;
1569 }
1570 if (mode != spv::ExecutionModeMax)
1571 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1572 }
1573 break;
1574#endif
1575
John Kessenich140f3df2015-06-26 16:58:36 -06001576 default:
1577 break;
1578 }
John Kessenich140f3df2015-06-26 16:58:36 -06001579}
1580
John Kessenichfca82622016-11-26 13:23:20 -07001581// Finish creating SPV, after the traversal is complete.
1582void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001583{
John Kessenichf04c51b2018-08-03 15:56:12 -06001584 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001585 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001586 builder.setBuildPoint(shaderEntry->getLastBlock());
1587 builder.leaveFunction();
1588 }
1589
John Kessenich7ba63412015-12-20 17:37:07 -07001590 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001591 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1592 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001593
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 Kessenich7ba63412015-12-20 17:37:07 -07001597}
1598
John Kessenichfca82622016-11-26 13:23:20 -07001599// Write the SPV into 'out'.
1600void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001601{
John Kessenichfca82622016-11-26 13:23:20 -07001602 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001603}
1604
1605//
1606// Implement the traversal functions.
1607//
1608// Return true from interior nodes to have the external traversal
1609// continue on to children. Return false if children were
1610// already processed.
1611//
1612
1613//
qining25262b32016-05-06 17:25:16 -04001614// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001615// - uniform/input reads
1616// - output writes
1617// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1618// - something simple that degenerates into the last bullet
1619//
1620void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1621{
qining75d1d802016-04-06 14:42:01 -04001622 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1623 if (symbol->getType().getQualifier().isSpecConstant())
1624 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1625
John Kessenich140f3df2015-06-26 16:58:36 -06001626 // getSymbolId() will set up all the IO decorations on the first call.
1627 // Formal function parameters were mapped during makeFunctions().
1628 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001629
John Kessenich7ba63412015-12-20 17:37:07 -07001630 if (builder.isPointer(id)) {
John Kessenich9c14f772019-06-17 08:38:35 -06001631 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
John Kessenich7c7731e2019-01-04 16:47:06 +07001632 // Consider adding to the OpEntryPoint interface list.
1633 // Only looking at structures if they have at least one member.
1634 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1635 spv::StorageClass sc = builder.getStorageClass(id);
1636 // Before SPIR-V 1.4, we only want to include Input and Output.
1637 // Starting with SPIR-V 1.4, we want all globals.
1638 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1639 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001640 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001641 }
John Kessenich5f77d862017-09-19 11:09:59 -06001642 }
John Kessenich9c14f772019-06-17 08:38:35 -06001643
1644 // If the SPIR-V type is required to be different than the AST type,
1645 // translate now from the SPIR-V type to the AST type, for the consuming
1646 // operation.
1647 // Note this turns it from an l-value to an r-value.
1648 // Currently, all symbols needing this are inputs; avoid the map lookup when non-input.
1649 if (symbol->getType().getQualifier().storage == glslang::EvqVaryingIn)
1650 id = translateForcedType(id);
John Kessenich7ba63412015-12-20 17:37:07 -07001651 }
1652
1653 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001654 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001655 // Prepare to generate code for the access
1656
1657 // L-value chains will be computed left to right. We're on the symbol now,
1658 // which is the left-most part of the access chain, so now is "clear" time,
1659 // followed by setting the base.
1660 builder.clearAccessChain();
1661
1662 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001663 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001664 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001665 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001666 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001667 // These are also pure R-values.
John Kessenich9c14f772019-06-17 08:38:35 -06001668 // C) R-Values from type translation, see above call to translateForcedType()
John Kessenich6c292d32016-02-15 20:58:50 -07001669 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich9c14f772019-06-17 08:38:35 -06001670 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end() ||
1671 !builder.isPointerType(builder.getTypeId(id)))
John Kessenich140f3df2015-06-26 16:58:36 -06001672 builder.setAccessChainRValue(id);
1673 else
1674 builder.setAccessChainLValue(id);
1675 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001676
1677 // Process linkage-only nodes for any special additional interface work.
1678 if (linkageOnly) {
1679 if (glslangIntermediate->getHlslFunctionality1()) {
1680 // Map implicit counter buffers to their originating buffers, which should have been
1681 // seen by now, given earlier pruning of unused counters, and preservation of order
1682 // of declaration.
1683 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1684 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1685 // Save possible originating buffers for counter buffers, keyed by
1686 // making the potential counter-buffer name.
1687 std::string keyName = symbol->getName().c_str();
1688 keyName = glslangIntermediate->addCounterBufferName(keyName);
1689 counterOriginator[keyName] = symbol;
1690 } else {
1691 // Handle a counter buffer, by finding the saved originating buffer.
1692 std::string keyName = symbol->getName().c_str();
1693 auto it = counterOriginator.find(keyName);
1694 if (it != counterOriginator.end()) {
1695 id = getSymbolId(it->second);
1696 if (id != spv::NoResult) {
1697 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001698 if (counterId != spv::NoResult) {
1699 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001700 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001701 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001702 }
1703 }
1704 }
1705 }
1706 }
1707 }
John Kessenich140f3df2015-06-26 16:58:36 -06001708}
1709
1710bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1711{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001712 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001713
qining40887662016-04-03 22:20:42 -04001714 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1715 if (node->getType().getQualifier().isSpecConstant())
1716 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1717
John Kessenich140f3df2015-06-26 16:58:36 -06001718 // First, handle special cases
1719 switch (node->getOp()) {
1720 case glslang::EOpAssign:
1721 case glslang::EOpAddAssign:
1722 case glslang::EOpSubAssign:
1723 case glslang::EOpMulAssign:
1724 case glslang::EOpVectorTimesMatrixAssign:
1725 case glslang::EOpVectorTimesScalarAssign:
1726 case glslang::EOpMatrixTimesScalarAssign:
1727 case glslang::EOpMatrixTimesMatrixAssign:
1728 case glslang::EOpDivAssign:
1729 case glslang::EOpModAssign:
1730 case glslang::EOpAndAssign:
1731 case glslang::EOpInclusiveOrAssign:
1732 case glslang::EOpExclusiveOrAssign:
1733 case glslang::EOpLeftShiftAssign:
1734 case glslang::EOpRightShiftAssign:
1735 // A bin-op assign "a += b" means the same thing as "a = a + b"
1736 // where a is evaluated before b. For a simple assignment, GLSL
1737 // says to evaluate the left before the right. So, always, left
1738 // node then right node.
1739 {
1740 // get the left l-value, save it away
1741 builder.clearAccessChain();
1742 node->getLeft()->traverse(this);
1743 spv::Builder::AccessChain lValue = builder.getAccessChain();
1744
1745 // evaluate the right
1746 builder.clearAccessChain();
1747 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001748 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001749
1750 if (node->getOp() != glslang::EOpAssign) {
1751 // the left is also an r-value
1752 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001753 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001754
1755 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001756 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001757 TranslateNoContractionDecoration(node->getType().getQualifier()),
1758 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001759 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001760 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1761 node->getType().getBasicType());
1762
1763 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001764 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001765 }
1766
1767 // store the result
1768 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001769 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001770
1771 // assignments are expressions having an rValue after they are evaluated...
1772 builder.clearAccessChain();
1773 builder.setAccessChainRValue(rValue);
1774 }
1775 return false;
1776 case glslang::EOpIndexDirect:
1777 case glslang::EOpIndexDirectStruct:
1778 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001779 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001780 // Get the left part of the access chain.
1781 node->getLeft()->traverse(this);
1782
1783 // Add the next element in the chain
1784
David Netoa901ffe2016-06-08 14:11:40 +01001785 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001786 if (! node->getLeft()->getType().isArray() &&
1787 node->getLeft()->getType().isVector() &&
1788 node->getOp() == glslang::EOpIndexDirect) {
1789 // This is essentially a hard-coded vector swizzle of size 1,
1790 // so short circuit the access-chain stuff with a swizzle.
1791 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001792 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001793 int dummySize;
1794 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1795 TranslateCoherent(node->getLeft()->getType()),
1796 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001797 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001798
1799 // Load through a block reference is performed with a dot operator that
1800 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1801 // do a load and reset the access chain.
1802 if (node->getLeft()->getBasicType() == glslang::EbtReference &&
1803 !node->getLeft()->getType().isArray() &&
1804 node->getOp() == glslang::EOpIndexDirectStruct)
1805 {
1806 spv::Id left = accessChainLoad(node->getLeft()->getType());
1807 builder.clearAccessChain();
1808 builder.setAccessChainLValue(left);
1809 }
1810
David Netoa901ffe2016-06-08 14:11:40 +01001811 int spvIndex = glslangIndex;
1812 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1813 node->getOp() == glslang::EOpIndexDirectStruct)
1814 {
1815 // This may be, e.g., an anonymous block-member selection, which generally need
1816 // index remapping due to hidden members in anonymous blocks.
1817 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1818 assert(remapper.size() > 0);
1819 spvIndex = remapper[glslangIndex];
1820 }
John Kessenichebb50532016-05-16 19:22:05 -06001821
David Netoa901ffe2016-06-08 14:11:40 +01001822 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001823 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001824
1825 // Add capabilities here for accessing PointSize and clip/cull distance.
1826 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001827 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001828 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001829 }
1830 }
1831 return false;
1832 case glslang::EOpIndexIndirect:
1833 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001834 // Array, matrix, or vector indirection with variable index.
1835 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001836 // matrices are arrays of vectors, so will also work for a matrix.
1837 // Will use the access chain's 'component' for variable index into a vector.
1838
1839 // This adapter is building access chains left to right.
1840 // Set up the access chain to the left.
1841 node->getLeft()->traverse(this);
1842
1843 // save it so that computing the right side doesn't trash it
1844 spv::Builder::AccessChain partial = builder.getAccessChain();
1845
1846 // compute the next index in the chain
1847 builder.clearAccessChain();
1848 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001849 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001850
John Kessenich5611c6d2018-04-05 11:25:02 -06001851 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1852
John Kessenich140f3df2015-06-26 16:58:36 -06001853 // restore the saved access chain
1854 builder.setAccessChain(partial);
1855
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001856 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1857 int dummySize;
1858 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1859 TranslateCoherent(node->getLeft()->getType()),
1860 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1861 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001862 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001863 }
1864 return false;
1865 case glslang::EOpVectorSwizzle:
1866 {
1867 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001868 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001869 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001870 int dummySize;
1871 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1872 TranslateCoherent(node->getLeft()->getType()),
1873 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001874 }
1875 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001876 case glslang::EOpMatrixSwizzle:
1877 logger->missingFunctionality("matrix swizzle");
1878 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001879 case glslang::EOpLogicalOr:
1880 case glslang::EOpLogicalAnd:
1881 {
1882
1883 // These may require short circuiting, but can sometimes be done as straight
1884 // binary operations. The right operand must be short circuited if it has
1885 // side effects, and should probably be if it is complex.
1886 if (isTrivial(node->getRight()->getAsTyped()))
1887 break; // handle below as a normal binary operation
1888 // otherwise, we need to do dynamic short circuiting on the right operand
1889 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1890 builder.clearAccessChain();
1891 builder.setAccessChainRValue(result);
1892 }
1893 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001894 default:
1895 break;
1896 }
1897
1898 // Assume generic binary op...
1899
John Kessenich32cfd492016-02-02 12:37:46 -07001900 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001901 builder.clearAccessChain();
1902 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001903 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001904
John Kessenich32cfd492016-02-02 12:37:46 -07001905 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001906 builder.clearAccessChain();
1907 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001908 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001909
John Kessenich32cfd492016-02-02 12:37:46 -07001910 // get result
John Kessenichead86222018-03-28 18:01:20 -06001911 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001912 TranslateNoContractionDecoration(node->getType().getQualifier()),
1913 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001914 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001915 convertGlslangToSpvType(node->getType()), left, right,
1916 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001917
John Kessenich50e57562015-12-21 21:21:11 -07001918 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001919 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001920 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001921 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001922 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001923 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001924 return false;
1925 }
John Kessenich140f3df2015-06-26 16:58:36 -06001926}
1927
John Kessenich9c14f772019-06-17 08:38:35 -06001928// Figure out what, if any, type changes are needed when accessing a specific built-in.
1929// Returns <the type SPIR-V requires for declarion, the type to translate to on use>.
1930// Also see comment for 'forceType', regarding tracking SPIR-V-required types.
1931std::pair<spv::Id, spv::Id> TGlslangToSpvTraverser::getForcedType(spv::BuiltIn builtIn,
1932 const glslang::TType& glslangType)
1933{
1934 switch(builtIn)
1935 {
1936 case spv::BuiltInSubgroupEqMask:
1937 case spv::BuiltInSubgroupGeMask:
1938 case spv::BuiltInSubgroupGtMask:
1939 case spv::BuiltInSubgroupLeMask:
1940 case spv::BuiltInSubgroupLtMask: {
1941 // these require changing a 64-bit scaler -> a vector of 32-bit components
1942 if (glslangType.isVector())
1943 break;
1944 std::pair<spv::Id, spv::Id> ret(builder.makeVectorType(builder.makeUintType(32), 4),
1945 builder.makeUintType(64));
1946 return ret;
1947 }
1948 default:
1949 break;
1950 }
1951
1952 std::pair<spv::Id, spv::Id> ret(spv::NoType, spv::NoType);
1953 return ret;
1954}
1955
1956// For an object previously identified (see getForcedType() and forceType)
1957// as needing type translations, do the translation needed for a load, turning
1958// an L-value into in R-value.
1959spv::Id TGlslangToSpvTraverser::translateForcedType(spv::Id object)
1960{
1961 const auto forceIt = forceType.find(object);
1962 if (forceIt == forceType.end())
1963 return object;
1964
1965 spv::Id desiredTypeId = forceIt->second;
1966 spv::Id objectTypeId = builder.getTypeId(object);
1967 assert(builder.isPointerType(objectTypeId));
1968 objectTypeId = builder.getContainedTypeId(objectTypeId);
1969 if (builder.isVectorType(objectTypeId) &&
1970 builder.getScalarTypeWidth(builder.getContainedTypeId(objectTypeId)) == 32) {
1971 if (builder.getScalarTypeWidth(desiredTypeId) == 64) {
1972 // handle 32-bit v.xy* -> 64-bit
1973 builder.clearAccessChain();
1974 builder.setAccessChainLValue(object);
1975 object = builder.accessChainLoad(spv::NoPrecision, spv::DecorationMax, objectTypeId);
1976 std::vector<spv::Id> components;
1977 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 0));
1978 components.push_back(builder.createCompositeExtract(object, builder.getContainedTypeId(objectTypeId), 1));
1979
1980 spv::Id vecType = builder.makeVectorType(builder.getContainedTypeId(objectTypeId), 2);
1981 return builder.createUnaryOp(spv::OpBitcast, desiredTypeId,
1982 builder.createCompositeConstruct(vecType, components));
1983 } else {
1984 logger->missingFunctionality("forcing 32-bit vector type to non 64-bit scalar");
1985 }
1986 } else {
1987 logger->missingFunctionality("forcing non 32-bit vector type");
1988 }
1989
1990 return object;
1991}
1992
John Kessenich140f3df2015-06-26 16:58:36 -06001993bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1994{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001995 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001996
qining40887662016-04-03 22:20:42 -04001997 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1998 if (node->getType().getQualifier().isSpecConstant())
1999 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2000
John Kessenichfc51d282015-08-19 13:34:18 -06002001 spv::Id result = spv::NoResult;
2002
2003 // try texturing first
2004 result = createImageTextureFunctionCall(node);
2005 if (result != spv::NoResult) {
2006 builder.clearAccessChain();
2007 builder.setAccessChainRValue(result);
2008
2009 return false; // done with this node
2010 }
2011
2012 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06002013
2014 if (node->getOp() == glslang::EOpArrayLength) {
2015 // Quite special; won't want to evaluate the operand.
2016
John Kessenich5611c6d2018-04-05 11:25:02 -06002017 // Currently, the front-end does not allow .length() on an array until it is sized,
2018 // except for the last block membeor of an SSBO.
2019 // TODO: If this changes, link-time sized arrays might show up here, and need their
2020 // size extracted.
2021
John Kessenichc9a80832015-09-12 12:17:44 -06002022 // Normal .length() would have been constant folded by the front-end.
2023 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06002024 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06002025
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002026 spv::Id length;
2027 if (node->getOperand()->getType().isCoopMat()) {
2028 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2029
2030 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
2031 assert(builder.isCooperativeMatrixType(typeId));
2032
2033 length = builder.createCooperativeMatrixLength(typeId);
2034 } else {
2035 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
2036 block->traverse(this);
2037 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
2038 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
2039 }
John Kessenichc9a80832015-09-12 12:17:44 -06002040
John Kessenich8c869672018-11-28 07:01:37 -07002041 // GLSL semantics say the result of .length() is an int, while SPIR-V says
2042 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
2043 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002044 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
2045 if (builder.isInSpecConstCodeGenMode()) {
2046 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
2047 } else {
2048 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
2049 }
2050 }
John Kessenich8c869672018-11-28 07:01:37 -07002051
John Kessenichc9a80832015-09-12 12:17:44 -06002052 builder.clearAccessChain();
2053 builder.setAccessChainRValue(length);
2054
2055 return false;
2056 }
2057
John Kessenichfc51d282015-08-19 13:34:18 -06002058 // Start by evaluating the operand
2059
John Kessenich8c8505c2016-07-26 12:50:38 -06002060 // Does it need a swizzle inversion? If so, evaluation is inverted;
2061 // operate first on the swizzle base, then apply the swizzle.
2062 spv::Id invertedType = spv::NoType;
2063 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
2064 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
2065 invertedType = getInvertedSwizzleType(*node->getOperand());
2066
John Kessenich140f3df2015-06-26 16:58:36 -06002067 builder.clearAccessChain();
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002068 TIntermNode *operandNode;
John Kessenich8c8505c2016-07-26 12:50:38 -06002069 if (invertedType != spv::NoType)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002070 operandNode = node->getOperand()->getAsBinaryNode()->getLeft();
John Kessenich8c8505c2016-07-26 12:50:38 -06002071 else
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002072 operandNode = node->getOperand();
2073
2074 operandNode->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08002075
Rex Xufc618912015-09-09 16:42:49 +08002076 spv::Id operand = spv::NoResult;
2077
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002078 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2079
Rex Xufc618912015-09-09 16:42:49 +08002080 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
2081 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08002082 node->getOp() == glslang::EOpAtomicCounter ||
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002083 node->getOp() == glslang::EOpInterpolateAtCentroid) {
Rex Xufc618912015-09-09 16:42:49 +08002084 operand = builder.accessChainGetLValue(); // Special case l-value operands
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002085 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2086 lvalueCoherentFlags |= TranslateCoherent(operandNode->getAsTyped()->getType());
2087 } else
John Kessenich32cfd492016-02-02 12:37:46 -07002088 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002089
John Kessenichead86222018-03-28 18:01:20 -06002090 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002091 TranslateNoContractionDecoration(node->getType().getQualifier()),
2092 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002093
2094 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002095 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06002096 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002097
2098 // if not, then possibly an operation
2099 if (! result)
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002100 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType(), lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002101
2102 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002103 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002104 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002105 builder.addDecoration(result, decorations.nonUniform);
2106 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002107
John Kessenich140f3df2015-06-26 16:58:36 -06002108 builder.clearAccessChain();
2109 builder.setAccessChainRValue(result);
2110
2111 return false; // done with this node
2112 }
2113
2114 // it must be a special case, check...
2115 switch (node->getOp()) {
2116 case glslang::EOpPostIncrement:
2117 case glslang::EOpPostDecrement:
2118 case glslang::EOpPreIncrement:
2119 case glslang::EOpPreDecrement:
2120 {
2121 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002122 spv::Id one = 0;
2123 if (node->getBasicType() == glslang::EbtFloat)
2124 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08002125 else if (node->getBasicType() == glslang::EbtDouble)
2126 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002127 else if (node->getBasicType() == glslang::EbtFloat16)
2128 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002129 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2130 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002131 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2132 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002133 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2134 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08002135 else
2136 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002137 glslang::TOperator op;
2138 if (node->getOp() == glslang::EOpPreIncrement ||
2139 node->getOp() == glslang::EOpPostIncrement)
2140 op = glslang::EOpAdd;
2141 else
2142 op = glslang::EOpSub;
2143
John Kessenichead86222018-03-28 18:01:20 -06002144 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002145 convertGlslangToSpvType(node->getType()), operand, one,
2146 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002147 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002148
2149 // The result of operation is always stored, but conditionally the
2150 // consumed result. The consumed result is always an r-value.
2151 builder.accessChainStore(result);
2152 builder.clearAccessChain();
2153 if (node->getOp() == glslang::EOpPreIncrement ||
2154 node->getOp() == glslang::EOpPreDecrement)
2155 builder.setAccessChainRValue(result);
2156 else
2157 builder.setAccessChainRValue(operand);
2158 }
2159
2160 return false;
2161
2162 case glslang::EOpEmitStreamVertex:
2163 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2164 return false;
2165 case glslang::EOpEndStreamPrimitive:
2166 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2167 return false;
2168
2169 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002170 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002171 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002172 }
John Kessenich140f3df2015-06-26 16:58:36 -06002173}
2174
2175bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2176{
qining27e04a02016-04-14 16:40:20 -04002177 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2178 if (node->getType().getQualifier().isSpecConstant())
2179 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2180
John Kessenichfc51d282015-08-19 13:34:18 -06002181 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002182 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2183 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002184
2185 // try texturing
2186 result = createImageTextureFunctionCall(node);
2187 if (result != spv::NoResult) {
2188 builder.clearAccessChain();
2189 builder.setAccessChainRValue(result);
2190
2191 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05002192 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08002193#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05002194 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08002195#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05002196 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002197 // "imageStore" is a special case, which has no result
2198 return false;
2199 }
John Kessenichfc51d282015-08-19 13:34:18 -06002200
John Kessenich140f3df2015-06-26 16:58:36 -06002201 glslang::TOperator binOp = glslang::EOpNull;
2202 bool reduceComparison = true;
2203 bool isMatrix = false;
2204 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002205 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002206
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002207 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
2208
John Kessenich140f3df2015-06-26 16:58:36 -06002209 assert(node->getOp());
2210
John Kessenichf6640762016-08-01 19:44:00 -06002211 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002212
2213 switch (node->getOp()) {
2214 case glslang::EOpSequence:
2215 {
2216 if (preVisit)
2217 ++sequenceDepth;
2218 else
2219 --sequenceDepth;
2220
2221 if (sequenceDepth == 1) {
2222 // If this is the parent node of all the functions, we want to see them
2223 // early, so all call points have actual SPIR-V functions to reference.
2224 // In all cases, still let the traverser visit the children for us.
2225 makeFunctions(node->getAsAggregate()->getSequence());
2226
John Kessenich6fccb3c2016-09-19 16:01:41 -06002227 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002228 // anything else gets there, so visit out of order, doing them all now.
2229 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2230
John Kessenich6a60c2f2016-12-08 21:01:59 -07002231 // 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 -06002232 // so do them manually.
2233 visitFunctions(node->getAsAggregate()->getSequence());
2234
2235 return false;
2236 }
2237
2238 return true;
2239 }
2240 case glslang::EOpLinkerObjects:
2241 {
2242 if (visit == glslang::EvPreVisit)
2243 linkageOnly = true;
2244 else
2245 linkageOnly = false;
2246
2247 return true;
2248 }
2249 case glslang::EOpComma:
2250 {
2251 // processing from left to right naturally leaves the right-most
2252 // lying around in the access chain
2253 glslang::TIntermSequence& glslangOperands = node->getSequence();
2254 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2255 glslangOperands[i]->traverse(this);
2256
2257 return false;
2258 }
2259 case glslang::EOpFunction:
2260 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002261 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002262 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002263 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002264 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002265 } else {
2266 handleFunctionEntry(node);
2267 }
2268 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002269 if (inEntryPoint)
2270 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002271 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002272 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002273 }
2274
2275 return true;
2276 case glslang::EOpParameters:
2277 // Parameters will have been consumed by EOpFunction processing, but not
2278 // the body, so we still visited the function node's children, making this
2279 // child redundant.
2280 return false;
2281 case glslang::EOpFunctionCall:
2282 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002283 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002284 if (node->isUserDefined())
2285 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002286 // 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 -07002287 if (result) {
2288 builder.clearAccessChain();
2289 builder.setAccessChainRValue(result);
2290 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002291 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002292
2293 return false;
2294 }
2295 case glslang::EOpConstructMat2x2:
2296 case glslang::EOpConstructMat2x3:
2297 case glslang::EOpConstructMat2x4:
2298 case glslang::EOpConstructMat3x2:
2299 case glslang::EOpConstructMat3x3:
2300 case glslang::EOpConstructMat3x4:
2301 case glslang::EOpConstructMat4x2:
2302 case glslang::EOpConstructMat4x3:
2303 case glslang::EOpConstructMat4x4:
2304 case glslang::EOpConstructDMat2x2:
2305 case glslang::EOpConstructDMat2x3:
2306 case glslang::EOpConstructDMat2x4:
2307 case glslang::EOpConstructDMat3x2:
2308 case glslang::EOpConstructDMat3x3:
2309 case glslang::EOpConstructDMat3x4:
2310 case glslang::EOpConstructDMat4x2:
2311 case glslang::EOpConstructDMat4x3:
2312 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002313 case glslang::EOpConstructIMat2x2:
2314 case glslang::EOpConstructIMat2x3:
2315 case glslang::EOpConstructIMat2x4:
2316 case glslang::EOpConstructIMat3x2:
2317 case glslang::EOpConstructIMat3x3:
2318 case glslang::EOpConstructIMat3x4:
2319 case glslang::EOpConstructIMat4x2:
2320 case glslang::EOpConstructIMat4x3:
2321 case glslang::EOpConstructIMat4x4:
2322 case glslang::EOpConstructUMat2x2:
2323 case glslang::EOpConstructUMat2x3:
2324 case glslang::EOpConstructUMat2x4:
2325 case glslang::EOpConstructUMat3x2:
2326 case glslang::EOpConstructUMat3x3:
2327 case glslang::EOpConstructUMat3x4:
2328 case glslang::EOpConstructUMat4x2:
2329 case glslang::EOpConstructUMat4x3:
2330 case glslang::EOpConstructUMat4x4:
2331 case glslang::EOpConstructBMat2x2:
2332 case glslang::EOpConstructBMat2x3:
2333 case glslang::EOpConstructBMat2x4:
2334 case glslang::EOpConstructBMat3x2:
2335 case glslang::EOpConstructBMat3x3:
2336 case glslang::EOpConstructBMat3x4:
2337 case glslang::EOpConstructBMat4x2:
2338 case glslang::EOpConstructBMat4x3:
2339 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002340 case glslang::EOpConstructF16Mat2x2:
2341 case glslang::EOpConstructF16Mat2x3:
2342 case glslang::EOpConstructF16Mat2x4:
2343 case glslang::EOpConstructF16Mat3x2:
2344 case glslang::EOpConstructF16Mat3x3:
2345 case glslang::EOpConstructF16Mat3x4:
2346 case glslang::EOpConstructF16Mat4x2:
2347 case glslang::EOpConstructF16Mat4x3:
2348 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002349 isMatrix = true;
2350 // fall through
2351 case glslang::EOpConstructFloat:
2352 case glslang::EOpConstructVec2:
2353 case glslang::EOpConstructVec3:
2354 case glslang::EOpConstructVec4:
2355 case glslang::EOpConstructDouble:
2356 case glslang::EOpConstructDVec2:
2357 case glslang::EOpConstructDVec3:
2358 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002359 case glslang::EOpConstructFloat16:
2360 case glslang::EOpConstructF16Vec2:
2361 case glslang::EOpConstructF16Vec3:
2362 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002363 case glslang::EOpConstructBool:
2364 case glslang::EOpConstructBVec2:
2365 case glslang::EOpConstructBVec3:
2366 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002367 case glslang::EOpConstructInt8:
2368 case glslang::EOpConstructI8Vec2:
2369 case glslang::EOpConstructI8Vec3:
2370 case glslang::EOpConstructI8Vec4:
2371 case glslang::EOpConstructUint8:
2372 case glslang::EOpConstructU8Vec2:
2373 case glslang::EOpConstructU8Vec3:
2374 case glslang::EOpConstructU8Vec4:
2375 case glslang::EOpConstructInt16:
2376 case glslang::EOpConstructI16Vec2:
2377 case glslang::EOpConstructI16Vec3:
2378 case glslang::EOpConstructI16Vec4:
2379 case glslang::EOpConstructUint16:
2380 case glslang::EOpConstructU16Vec2:
2381 case glslang::EOpConstructU16Vec3:
2382 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002383 case glslang::EOpConstructInt:
2384 case glslang::EOpConstructIVec2:
2385 case glslang::EOpConstructIVec3:
2386 case glslang::EOpConstructIVec4:
2387 case glslang::EOpConstructUint:
2388 case glslang::EOpConstructUVec2:
2389 case glslang::EOpConstructUVec3:
2390 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002391 case glslang::EOpConstructInt64:
2392 case glslang::EOpConstructI64Vec2:
2393 case glslang::EOpConstructI64Vec3:
2394 case glslang::EOpConstructI64Vec4:
2395 case glslang::EOpConstructUint64:
2396 case glslang::EOpConstructU64Vec2:
2397 case glslang::EOpConstructU64Vec3:
2398 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002399 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002400 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002401 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002402 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002403 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002404 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002405 std::vector<spv::Id> arguments;
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002406 translateArguments(*node, arguments, lvalueCoherentFlags);
John Kessenich140f3df2015-06-26 16:58:36 -06002407 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002408 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002409 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002410 else if (node->getOp() == glslang::EOpConstructStruct ||
2411 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2412 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002413 std::vector<spv::Id> constituents;
2414 for (int c = 0; c < (int)arguments.size(); ++c)
2415 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002416 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002417 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002418 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002419 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002420 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002421
2422 builder.clearAccessChain();
2423 builder.setAccessChainRValue(constructed);
2424
2425 return false;
2426 }
2427
2428 // These six are component-wise compares with component-wise results.
2429 // Forward on to createBinaryOperation(), requesting a vector result.
2430 case glslang::EOpLessThan:
2431 case glslang::EOpGreaterThan:
2432 case glslang::EOpLessThanEqual:
2433 case glslang::EOpGreaterThanEqual:
2434 case glslang::EOpVectorEqual:
2435 case glslang::EOpVectorNotEqual:
2436 {
2437 // Map the operation to a binary
2438 binOp = node->getOp();
2439 reduceComparison = false;
2440 switch (node->getOp()) {
2441 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2442 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2443 default: binOp = node->getOp(); break;
2444 }
2445
2446 break;
2447 }
2448 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002449 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002450 binOp = glslang::EOpMul;
2451 break;
2452 case glslang::EOpOuterProduct:
2453 // two vectors multiplied to make a matrix
2454 binOp = glslang::EOpOuterProduct;
2455 break;
2456 case glslang::EOpDot:
2457 {
qining25262b32016-05-06 17:25:16 -04002458 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002459 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002460 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002461 binOp = glslang::EOpMul;
2462 break;
2463 }
2464 case glslang::EOpMod:
2465 // when an aggregate, this is the floating-point mod built-in function,
2466 // which can be emitted by the one in createBinaryOperation()
2467 binOp = glslang::EOpMod;
2468 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002469 case glslang::EOpEmitVertex:
2470 case glslang::EOpEndPrimitive:
2471 case glslang::EOpBarrier:
2472 case glslang::EOpMemoryBarrier:
2473 case glslang::EOpMemoryBarrierAtomicCounter:
2474 case glslang::EOpMemoryBarrierBuffer:
2475 case glslang::EOpMemoryBarrierImage:
2476 case glslang::EOpMemoryBarrierShared:
2477 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002478 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002479 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002480 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002481 case glslang::EOpWorkgroupMemoryBarrier:
2482 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002483 case glslang::EOpSubgroupBarrier:
2484 case glslang::EOpSubgroupMemoryBarrier:
2485 case glslang::EOpSubgroupMemoryBarrierBuffer:
2486 case glslang::EOpSubgroupMemoryBarrierImage:
2487 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002488 noReturnValue = true;
2489 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2490 break;
2491
Jeff Bolz36831c92018-09-05 10:11:41 -05002492 case glslang::EOpAtomicStore:
2493 noReturnValue = true;
2494 // fallthrough
2495 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002496 case glslang::EOpAtomicAdd:
2497 case glslang::EOpAtomicMin:
2498 case glslang::EOpAtomicMax:
2499 case glslang::EOpAtomicAnd:
2500 case glslang::EOpAtomicOr:
2501 case glslang::EOpAtomicXor:
2502 case glslang::EOpAtomicExchange:
2503 case glslang::EOpAtomicCompSwap:
2504 atomic = true;
2505 break;
2506
John Kessenich0d0c6d32017-07-23 16:08:26 -06002507 case glslang::EOpAtomicCounterAdd:
2508 case glslang::EOpAtomicCounterSubtract:
2509 case glslang::EOpAtomicCounterMin:
2510 case glslang::EOpAtomicCounterMax:
2511 case glslang::EOpAtomicCounterAnd:
2512 case glslang::EOpAtomicCounterOr:
2513 case glslang::EOpAtomicCounterXor:
2514 case glslang::EOpAtomicCounterExchange:
2515 case glslang::EOpAtomicCounterCompSwap:
2516 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2517 builder.addCapability(spv::CapabilityAtomicStorageOps);
2518 atomic = true;
2519 break;
2520
Chao Chen3c366992018-09-19 11:41:59 -07002521#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002522 case glslang::EOpIgnoreIntersectionNV:
2523 case glslang::EOpTerminateRayNV:
2524 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002525 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002526 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2527 noReturnValue = true;
2528 break;
2529#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002530 case glslang::EOpCooperativeMatrixLoad:
2531 case glslang::EOpCooperativeMatrixStore:
2532 noReturnValue = true;
2533 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002534 case glslang::EOpBeginInvocationInterlock:
2535 case glslang::EOpEndInvocationInterlock:
2536 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2537 noReturnValue = true;
2538 break;
Chao Chen3c366992018-09-19 11:41:59 -07002539
John Kessenich140f3df2015-06-26 16:58:36 -06002540 default:
2541 break;
2542 }
2543
2544 //
2545 // See if it maps to a regular operation.
2546 //
John Kessenich140f3df2015-06-26 16:58:36 -06002547 if (binOp != glslang::EOpNull) {
2548 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2549 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2550 assert(left && right);
2551
2552 builder.clearAccessChain();
2553 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002554 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002555
2556 builder.clearAccessChain();
2557 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002558 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002559
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002560 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002561 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002562 TranslateNoContractionDecoration(node->getType().getQualifier()),
2563 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002564 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002565 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002566 left->getType().getBasicType(), reduceComparison);
2567
2568 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002569 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002570 builder.clearAccessChain();
2571 builder.setAccessChainRValue(result);
2572
2573 return false;
2574 }
2575
John Kessenich426394d2015-07-23 10:22:48 -06002576 //
2577 // Create the list of operands.
2578 //
John Kessenich140f3df2015-06-26 16:58:36 -06002579 glslang::TIntermSequence& glslangOperands = node->getSequence();
2580 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002581 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002582 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002583 // special case l-value operands; there are just a few
2584 bool lvalue = false;
2585 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002586 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002587 case glslang::EOpModf:
2588 if (arg == 1)
2589 lvalue = true;
2590 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002591 case glslang::EOpInterpolateAtSample:
2592 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002593#ifdef AMD_EXTENSIONS
2594 case glslang::EOpInterpolateAtVertex:
2595#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002596 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002597 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002598
2599 // Does it need a swizzle inversion? If so, evaluation is inverted;
2600 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002601 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002602 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2603 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2604 }
Rex Xu7a26c172015-12-08 17:12:09 +08002605 break;
Rex Xud4782c12015-09-06 16:30:11 +08002606 case glslang::EOpAtomicAdd:
2607 case glslang::EOpAtomicMin:
2608 case glslang::EOpAtomicMax:
2609 case glslang::EOpAtomicAnd:
2610 case glslang::EOpAtomicOr:
2611 case glslang::EOpAtomicXor:
2612 case glslang::EOpAtomicExchange:
2613 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002614 case glslang::EOpAtomicLoad:
2615 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002616 case glslang::EOpAtomicCounterAdd:
2617 case glslang::EOpAtomicCounterSubtract:
2618 case glslang::EOpAtomicCounterMin:
2619 case glslang::EOpAtomicCounterMax:
2620 case glslang::EOpAtomicCounterAnd:
2621 case glslang::EOpAtomicCounterOr:
2622 case glslang::EOpAtomicCounterXor:
2623 case glslang::EOpAtomicCounterExchange:
2624 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002625 if (arg == 0)
2626 lvalue = true;
2627 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002628 case glslang::EOpAddCarry:
2629 case glslang::EOpSubBorrow:
2630 if (arg == 2)
2631 lvalue = true;
2632 break;
2633 case glslang::EOpUMulExtended:
2634 case glslang::EOpIMulExtended:
2635 if (arg >= 2)
2636 lvalue = true;
2637 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002638 case glslang::EOpCooperativeMatrixLoad:
2639 if (arg == 0 || arg == 1)
2640 lvalue = true;
2641 break;
2642 case glslang::EOpCooperativeMatrixStore:
2643 if (arg == 1)
2644 lvalue = true;
2645 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002646 default:
2647 break;
2648 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002649 builder.clearAccessChain();
2650 if (invertedType != spv::NoType && arg == 0)
2651 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2652 else
2653 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002654
2655 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2656 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2657
2658 if (arg == 1) {
2659 // fold "element" parameter into the access chain
2660 spv::Builder::AccessChain save = builder.getAccessChain();
2661 builder.clearAccessChain();
2662 glslangOperands[2]->traverse(this);
2663
2664 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2665
2666 builder.setAccessChain(save);
2667
2668 // Point to the first element of the array.
2669 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002670 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002671
2672 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2673 unsigned int alignment = builder.getAccessChain().alignment;
2674
2675 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2676 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2677 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2678 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2679 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2680 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2681 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2682 }
2683
2684 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2685
2686 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2687 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2688 }
2689
2690 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2691 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2692 }
2693 } else if (arg == 2) {
2694 continue;
2695 }
2696 }
2697
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002698 if (lvalue) {
John Kessenich140f3df2015-06-26 16:58:36 -06002699 operands.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002700 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
2701 lvalueCoherentFlags |= TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType());
2702 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002703 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002704 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002705 }
John Kessenich140f3df2015-06-26 16:58:36 -06002706 }
John Kessenich426394d2015-07-23 10:22:48 -06002707
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002708 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002709 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2710 std::vector<spv::IdImmediate> idImmOps;
2711
2712 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2713 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2714 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2715 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2716 // get the pointee type
2717 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2718 assert(builder.isCooperativeMatrixType(typeId));
2719 // do the op
2720 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2721 // store the result to the pointer (out param 'm')
2722 builder.createStore(result, operands[0]);
2723 result = 0;
2724 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2725 std::vector<spv::IdImmediate> idImmOps;
2726
2727 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2728 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2729 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2730 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2731 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2732
2733 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2734 result = 0;
2735 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002736 // Handle all atomics
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002737 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
John Kessenich426394d2015-07-23 10:22:48 -06002738 } else {
2739 // Pass through to generic operations.
2740 switch (glslangOperands.size()) {
2741 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002742 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002743 break;
2744 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002745 {
2746 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002747 TranslateNoContractionDecoration(node->getType().getQualifier()),
2748 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002749 result = createUnaryOperation(
2750 node->getOp(), decorations,
2751 resultType(), operands.front(),
Jeff Bolz38a52fc2019-06-14 09:56:28 -05002752 glslangOperands[0]->getAsTyped()->getBasicType(), lvalueCoherentFlags);
John Kessenichead86222018-03-28 18:01:20 -06002753 }
John Kessenich426394d2015-07-23 10:22:48 -06002754 break;
2755 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002756 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002757 break;
2758 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002759 if (invertedType)
2760 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002761 }
2762
2763 if (noReturnValue)
2764 return false;
2765
2766 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002767 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002768 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002769 } else {
2770 builder.clearAccessChain();
2771 builder.setAccessChainRValue(result);
2772 return false;
2773 }
2774}
2775
John Kessenich433e9ff2017-01-26 20:31:11 -07002776// This path handles both if-then-else and ?:
2777// The if-then-else has a node type of void, while
2778// ?: has either a void or a non-void node type
2779//
2780// Leaving the result, when not void:
2781// GLSL only has r-values as the result of a :?, but
2782// if we have an l-value, that can be more efficient if it will
2783// become the base of a complex r-value expression, because the
2784// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002785bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2786{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002787 // see if OpSelect can handle it
2788 const auto isOpSelectable = [&]() {
2789 if (node->getBasicType() == glslang::EbtVoid)
2790 return false;
2791 // OpSelect can do all other types starting with SPV 1.4
2792 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2793 // pre-1.4, only scalars and vectors can be handled
2794 if ((!node->getType().isScalar() && !node->getType().isVector()))
2795 return false;
2796 }
2797 return true;
2798 };
2799
John Kessenich4bee5312018-02-20 21:29:05 -07002800 // See if it simple and safe, or required, to execute both sides.
2801 // Crucially, side effects must be either semantically required or avoided,
2802 // and there are performance trade-offs.
2803 // Return true if required or a good idea (and safe) to execute both sides,
2804 // false otherwise.
2805 const auto bothSidesPolicy = [&]() -> bool {
2806 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002807 if (node->getTrueBlock() == nullptr ||
2808 node->getFalseBlock() == nullptr)
2809 return false;
2810
John Kessenich4bee5312018-02-20 21:29:05 -07002811 // required? (unless we write additional code to look for side effects
2812 // and make performance trade-offs if none are present)
2813 if (!node->getShortCircuit())
2814 return true;
2815
2816 // if not required to execute both, decide based on performance/practicality...
2817
John Kessenich0c1e71a2019-01-10 18:23:06 +07002818 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002819 return false;
2820
John Kessenich433e9ff2017-01-26 20:31:11 -07002821 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2822 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2823
2824 // return true if a single operand to ? : is okay for OpSelect
2825 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002826 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002827 };
2828
2829 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2830 operandOkay(node->getFalseBlock()->getAsTyped());
2831 };
2832
John Kessenich4bee5312018-02-20 21:29:05 -07002833 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2834 // emit the condition before doing anything with selection
2835 node->getCondition()->traverse(this);
2836 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2837
2838 // Find a way of executing both sides and selecting the right result.
2839 const auto executeBothSides = [&]() -> void {
2840 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002841 node->getTrueBlock()->traverse(this);
2842 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2843 node->getFalseBlock()->traverse(this);
2844 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2845
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002846 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002847
John Kessenich4bee5312018-02-20 21:29:05 -07002848 // done if void
2849 if (node->getBasicType() == glslang::EbtVoid)
2850 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002851
John Kessenich4bee5312018-02-20 21:29:05 -07002852 // emit code to select between trueValue and falseValue
2853
2854 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002855 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002856 // Emit OpSelect for this selection.
2857
2858 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002859 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2860 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002861 condition = builder.smearScalar(spv::NoPrecision, condition,
2862 builder.makeVectorType(builder.makeBoolType(),
2863 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002864 }
John Kessenich4bee5312018-02-20 21:29:05 -07002865
2866 // OpSelect
2867 result = builder.createTriOp(spv::OpSelect,
2868 convertGlslangToSpvType(node->getType()), condition,
2869 trueValue, falseValue);
2870
2871 builder.clearAccessChain();
2872 builder.setAccessChainRValue(result);
2873 } else {
2874 // We need control flow to select the result.
2875 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2876 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2877
2878 // Selection control:
2879 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2880
2881 // make an "if" based on the value created by the condition
2882 spv::Builder::If ifBuilder(condition, control, builder);
2883
2884 // emit the "then" statement
2885 builder.createStore(trueValue, result);
2886 ifBuilder.makeBeginElse();
2887 // emit the "else" statement
2888 builder.createStore(falseValue, result);
2889
2890 // finish off the control flow
2891 ifBuilder.makeEndIf();
2892
2893 builder.clearAccessChain();
2894 builder.setAccessChainLValue(result);
2895 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002896 };
2897
John Kessenich4bee5312018-02-20 21:29:05 -07002898 // Execute the one side needed, as per the condition
2899 const auto executeOneSide = [&]() {
2900 // Always emit control flow.
2901 if (node->getBasicType() != glslang::EbtVoid)
2902 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002903
John Kessenich4bee5312018-02-20 21:29:05 -07002904 // Selection control:
2905 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2906
2907 // make an "if" based on the value created by the condition
2908 spv::Builder::If ifBuilder(condition, control, builder);
2909
2910 // emit the "then" statement
2911 if (node->getTrueBlock() != nullptr) {
2912 node->getTrueBlock()->traverse(this);
2913 if (result != spv::NoResult)
2914 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2915 }
2916
2917 if (node->getFalseBlock() != nullptr) {
2918 ifBuilder.makeBeginElse();
2919 // emit the "else" statement
2920 node->getFalseBlock()->traverse(this);
2921 if (result != spv::NoResult)
2922 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2923 }
2924
2925 // finish off the control flow
2926 ifBuilder.makeEndIf();
2927
2928 if (result != spv::NoResult) {
2929 builder.clearAccessChain();
2930 builder.setAccessChainLValue(result);
2931 }
2932 };
2933
2934 // Try for OpSelect (or a requirement to execute both sides)
2935 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002936 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2937 if (node->getType().getQualifier().isSpecConstant())
2938 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002939 executeBothSides();
2940 } else
2941 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002942
2943 return false;
2944}
2945
2946bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2947{
2948 // emit and get the condition before doing anything with switch
2949 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002950 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002951
Rex Xu57e65922017-07-04 23:23:40 +08002952 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002953 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002954
John Kessenich140f3df2015-06-26 16:58:36 -06002955 // browse the children to sort out code segments
2956 int defaultSegment = -1;
2957 std::vector<TIntermNode*> codeSegments;
2958 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2959 std::vector<int> caseValues;
2960 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2961 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2962 TIntermNode* child = *c;
2963 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002964 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002965 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002966 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002967 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2968 } else
2969 codeSegments.push_back(child);
2970 }
2971
qining25262b32016-05-06 17:25:16 -04002972 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002973 // statements between the last case and the end of the switch statement
2974 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2975 (int)codeSegments.size() == defaultSegment)
2976 codeSegments.push_back(nullptr);
2977
2978 // make the switch statement
2979 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002980 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002981
2982 // emit all the code in the segments
2983 breakForLoop.push(false);
2984 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2985 builder.nextSwitchSegment(segmentBlocks, s);
2986 if (codeSegments[s])
2987 codeSegments[s]->traverse(this);
2988 else
2989 builder.addSwitchBreak();
2990 }
2991 breakForLoop.pop();
2992
2993 builder.endSwitch(segmentBlocks);
2994
2995 return false;
2996}
2997
2998void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2999{
3000 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003001 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06003002
3003 builder.clearAccessChain();
3004 builder.setAccessChainRValue(constant);
3005}
3006
3007bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
3008{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003009 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003010 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06003011
3012 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07003013 std::vector<unsigned int> operands;
3014 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06003015
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003016 // Spec requires back edges to target header blocks, and every header block
3017 // must dominate its merge block. Make a header block first to ensure these
3018 // conditions are met. By definition, it will contain OpLoopMerge, followed
3019 // by a block-ending branch. But we don't want to put any other body/test
3020 // instructions in it, since the body/test may have arbitrary instructions,
3021 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003022 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003023 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07003024 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003025 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05003026 spv::Block& test = builder.makeNewBlock();
3027 builder.createBranch(&test);
3028
3029 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06003030 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06003031 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003032 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
3033
3034 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003035 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003036 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003037 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003038 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003039 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003040
3041 builder.setBuildPoint(&blocks.continue_target);
3042 if (node->getTerminal())
3043 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003044 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04003045 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003046 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003047 builder.createBranch(&blocks.body);
3048
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003049 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003050 builder.setBuildPoint(&blocks.body);
3051 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05003052 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003053 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003054 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003055
3056 builder.setBuildPoint(&blocks.continue_target);
3057 if (node->getTerminal())
3058 node->getTerminal()->traverse(this);
3059 if (node->getTest()) {
3060 node->getTest()->traverse(this);
3061 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07003062 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003063 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003064 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05003065 // TODO: unless there was a break/return/discard instruction
3066 // somewhere in the body, this is an infinite loop, so we should
3067 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05003068 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003069 }
John Kessenich140f3df2015-06-26 16:58:36 -06003070 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05003071 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05003072 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06003073 return false;
3074}
3075
3076bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
3077{
3078 if (node->getExpression())
3079 node->getExpression()->traverse(this);
3080
greg-lunarg5d43c4a2018-12-07 17:36:33 -07003081 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06003082
John Kessenich140f3df2015-06-26 16:58:36 -06003083 switch (node->getFlowOp()) {
3084 case glslang::EOpKill:
3085 builder.makeDiscard();
3086 break;
3087 case glslang::EOpBreak:
3088 if (breakForLoop.top())
3089 builder.createLoopExit();
3090 else
3091 builder.addSwitchBreak();
3092 break;
3093 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06003094 builder.createLoopContinue();
3095 break;
3096 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003097 if (node->getExpression()) {
3098 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3099 spv::Id returnId = accessChainLoad(glslangReturnType);
3100 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3101 builder.clearAccessChain();
3102 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3103 builder.setAccessChainLValue(copyId);
3104 multiTypeStore(glslangReturnType, returnId);
3105 returnId = builder.createLoad(copyId);
3106 }
3107 builder.makeReturn(false, returnId);
3108 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003109 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003110
3111 builder.clearAccessChain();
3112 break;
3113
Jeff Bolzba6170b2019-07-01 09:23:23 -05003114 case glslang::EOpDemote:
3115 builder.createNoResultOp(spv::OpDemoteToHelperInvocationEXT);
3116 builder.addExtension(spv::E_SPV_EXT_demote_to_helper_invocation);
3117 builder.addCapability(spv::CapabilityDemoteToHelperInvocationEXT);
3118 break;
3119
John Kessenich140f3df2015-06-26 16:58:36 -06003120 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003121 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003122 break;
3123 }
3124
3125 return false;
3126}
3127
John Kessenich9c14f772019-06-17 08:38:35 -06003128spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003129{
qining25262b32016-05-06 17:25:16 -04003130 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003131 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003132 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003133 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003134 spv::Id result = createSpvConstant(*node);
3135 if (result != spv::NoResult)
3136 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003137 }
3138
3139 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003140 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003141 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3142 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003143
Rex Xucabbb782017-03-24 13:41:14 +08003144 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
3145 node->getType().containsBasicType(glslang::EbtInt16) ||
3146 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08003147 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003148 switch (storageClass) {
3149 case spv::StorageClassInput:
3150 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07003151 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003152 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003153 break;
3154 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07003155 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003156 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06003157 break;
3158 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003159 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003160 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3161 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003162 else
3163 builder.addCapability(spv::CapabilityStorageUniform16);
3164 break;
3165 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003166 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003167 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3168 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3169 break;
3170 default:
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003171 if (node->getType().containsBasicType(glslang::EbtFloat16))
3172 builder.addCapability(spv::CapabilityFloat16);
3173 if (node->getType().containsBasicType(glslang::EbtInt16) ||
3174 node->getType().containsBasicType(glslang::EbtUint16))
3175 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003176 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003177 }
3178 }
Rex Xuf89ad982017-04-07 23:22:33 +08003179
John Kessenich312dcfb2018-07-03 13:19:51 -06003180 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3181 node->getType().containsBasicType(glslang::EbtUint8);
3182 if (contains8BitType) {
3183 if (storageClass == spv::StorageClassPushConstant) {
3184 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3185 builder.addCapability(spv::CapabilityStoragePushConstant8);
3186 } else if (storageClass == spv::StorageClassUniform) {
3187 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3188 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003189 } else if (storageClass == spv::StorageClassStorageBuffer) {
3190 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3191 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003192 } else {
3193 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003194 }
3195 }
3196
John Kessenich140f3df2015-06-26 16:58:36 -06003197 const char* name = node->getName().c_str();
3198 if (glslang::IsAnonymous(name))
3199 name = "";
3200
3201 return builder.createVariable(storageClass, spvType, name);
3202}
3203
3204// Return type Id of the sampled type.
3205spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3206{
3207 switch (sampler.type) {
3208 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003209#ifdef AMD_EXTENSIONS
3210 case glslang::EbtFloat16:
3211 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3212 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3213 return builder.makeFloatType(16);
3214#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003215 case glslang::EbtInt: return builder.makeIntType(32);
3216 case glslang::EbtUint: return builder.makeUintType(32);
3217 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003218 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003219 return builder.makeFloatType(32);
3220 }
3221}
3222
John Kessenich8c8505c2016-07-26 12:50:38 -06003223// If node is a swizzle operation, return the type that should be used if
3224// the swizzle base is first consumed by another operation, before the swizzle
3225// is applied.
3226spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3227{
John Kessenichecba76f2017-01-06 00:34:48 -07003228 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003229 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3230 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3231 else
3232 return spv::NoType;
3233}
3234
3235// When inverting a swizzle with a parent op, this function
3236// will apply the swizzle operation to a completed parent operation.
3237spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3238{
3239 std::vector<unsigned> swizzle;
3240 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3241 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3242}
3243
John Kessenich8c8505c2016-07-26 12:50:38 -06003244// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3245void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3246{
3247 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3248 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3249 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3250}
3251
John Kessenich3ac051e2015-12-20 11:29:16 -07003252// Convert from a glslang type to an SPV type, by calling into a
3253// recursive version of this function. This establishes the inherited
3254// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003255spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003256{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003257 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003258}
3259
3260// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003261// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003262// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003263spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003264 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3265 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003266{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003267 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003268
3269 switch (type.getBasicType()) {
3270 case glslang::EbtVoid:
3271 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003272 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003273 break;
3274 case glslang::EbtFloat:
3275 spvType = builder.makeFloatType(32);
3276 break;
3277 case glslang::EbtDouble:
3278 spvType = builder.makeFloatType(64);
3279 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003280 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003281 spvType = builder.makeFloatType(16);
3282 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003283 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003284 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3285 // a 32-bit int where non-0 means true.
3286 if (explicitLayout != glslang::ElpNone)
3287 spvType = builder.makeUintType(32);
3288 else
3289 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003290 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003291 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003292 spvType = builder.makeIntType(8);
3293 break;
3294 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003295 spvType = builder.makeUintType(8);
3296 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003297 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003298 spvType = builder.makeIntType(16);
3299 break;
3300 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003301 spvType = builder.makeUintType(16);
3302 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003303 case glslang::EbtInt:
3304 spvType = builder.makeIntType(32);
3305 break;
3306 case glslang::EbtUint:
3307 spvType = builder.makeUintType(32);
3308 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003309 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003310 spvType = builder.makeIntType(64);
3311 break;
3312 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003313 spvType = builder.makeUintType(64);
3314 break;
John Kessenich426394d2015-07-23 10:22:48 -06003315 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003316 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003317 spvType = builder.makeUintType(32);
3318 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003319#ifdef NV_EXTENSIONS
3320 case glslang::EbtAccStructNV:
3321 spvType = builder.makeAccelerationStructureNVType();
3322 break;
3323#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003324 case glslang::EbtSampler:
3325 {
3326 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003327 if (sampler.sampler) {
3328 // pure sampler
3329 spvType = builder.makeSamplerType();
3330 } else {
3331 // an image is present, make its type
3332 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3333 sampler.image ? 2 : 1, TranslateImageFormat(type));
3334 if (sampler.combined) {
3335 // already has both image and sampler, make the combined type
3336 spvType = builder.makeSampledImageType(spvType);
3337 }
John Kessenich55e7d112015-11-15 21:33:39 -07003338 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003339 }
John Kessenich140f3df2015-06-26 16:58:36 -06003340 break;
3341 case glslang::EbtStruct:
3342 case glslang::EbtBlock:
3343 {
3344 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003345 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003346
3347 // Try to share structs for different layouts, but not yet for other
3348 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003349 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003350 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003351 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003352 break;
3353
3354 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003355 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003356 memberRemapper[glslangMembers].resize(glslangMembers->size());
3357 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003358 }
3359 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003360 case glslang::EbtReference:
3361 {
3362 // Make the forward pointer, then recurse to convert the structure type, then
3363 // patch up the forward pointer with a real pointer type.
3364 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3365 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3366 forwardPointers[type.getReferentType()] = forwardId;
3367 }
3368 spvType = forwardPointers[type.getReferentType()];
3369 if (!forwardReferenceOnly) {
3370 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3371 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3372 forwardPointers[type.getReferentType()],
3373 referentType);
3374 }
3375 }
3376 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003377 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003378 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003379 break;
3380 }
3381
3382 if (type.isMatrix())
3383 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3384 else {
3385 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3386 if (type.getVectorSize() > 1)
3387 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3388 }
3389
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003390 if (type.isCoopMat()) {
3391 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3392 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3393 if (type.getBasicType() == glslang::EbtFloat16)
3394 builder.addCapability(spv::CapabilityFloat16);
3395
3396 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3397 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3398 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3399
3400 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3401 }
3402
John Kessenich140f3df2015-06-26 16:58:36 -06003403 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003404 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3405
John Kessenichc9a80832015-09-12 12:17:44 -06003406 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003407 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003408 // We need to decorate array strides for types needing explicit layout, except blocks.
3409 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003410 // Use a dummy glslang type for querying internal strides of
3411 // arrays of arrays, but using just a one-dimensional array.
3412 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003413 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3414 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003415
3416 // Will compute the higher-order strides here, rather than making a whole
3417 // pile of types and doing repetitive recursion on their contents.
3418 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3419 }
John Kessenichf8842e52016-01-04 19:22:56 -07003420
3421 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003422 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003423 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003424 if (stride > 0)
3425 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003426 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003427 }
3428 } else {
3429 // single-dimensional array, and don't yet have stride
3430
John Kessenichf8842e52016-01-04 19:22:56 -07003431 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003432 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3433 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003434 }
John Kessenich31ed4832015-09-09 17:51:38 -06003435
John Kessenichead86222018-03-28 18:01:20 -06003436 // Do the outer dimension, which might not be known for a runtime-sized array.
3437 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3438 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003439 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003440 else {
3441 if (!lastBufferBlockMember) {
3442 builder.addExtension("SPV_EXT_descriptor_indexing");
3443 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3444 }
John Kessenichead86222018-03-28 18:01:20 -06003445 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003446 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003447 if (stride > 0)
3448 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003449 }
3450
3451 return spvType;
3452}
3453
John Kessenich0e737842017-03-24 18:38:16 -06003454// TODO: this functionality should exist at a higher level, in creating the AST
3455//
3456// Identify interface members that don't have their required extension turned on.
3457//
3458bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3459{
Chao Chen3c366992018-09-19 11:41:59 -07003460#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003461 auto& extensions = glslangIntermediate->getRequestedExtensions();
3462
Rex Xubcf291a2017-03-29 23:01:36 +08003463 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3464 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3465 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003466 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3467 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3468 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003469
3470 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3471 if (member.getFieldName() == "gl_ViewportMask" &&
3472 extensions.find("GL_NV_viewport_array2") == extensions.end())
3473 return true;
3474 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3475 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3476 return true;
3477 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3478 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3479 return true;
3480 }
3481#endif
John Kessenich0e737842017-03-24 18:38:16 -06003482
3483 return false;
3484};
3485
John Kessenich6090df02016-06-30 21:18:02 -06003486// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3487// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3488// Mutually recursive with convertGlslangToSpvType().
3489spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3490 const glslang::TTypeList* glslangMembers,
3491 glslang::TLayoutPacking explicitLayout,
3492 const glslang::TQualifier& qualifier)
3493{
3494 // Create a vector of struct types for SPIR-V to consume
3495 std::vector<spv::Id> spvMembers;
3496 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 -06003497 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003498 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3499 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3500 if (glslangMember.hiddenMember()) {
3501 ++memberDelta;
3502 if (type.getBasicType() == glslang::EbtBlock)
3503 memberRemapper[glslangMembers][i] = -1;
3504 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003505 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003506 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003507 if (filterMember(glslangMember))
3508 continue;
3509 }
John Kessenich6090df02016-06-30 21:18:02 -06003510 // modify just this child's view of the qualifier
3511 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3512 InheritQualifiers(memberQualifier, qualifier);
3513
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003514 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003515 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003516 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003517
3518 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003519 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3520 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003521
3522 // Make forward pointers for any pointer members, and create a list of members to
3523 // convert to spirv types after creating the struct.
3524 if (glslangMember.getBasicType() == glslang::EbtReference) {
3525 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3526 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3527 }
3528 spvMembers.push_back(
3529 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3530 } else {
3531 spvMembers.push_back(
3532 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3533 }
John Kessenich6090df02016-06-30 21:18:02 -06003534 }
3535 }
3536
3537 // Make the SPIR-V type
3538 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003539 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003540 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3541
3542 // Decorate it
3543 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3544
John Kessenichd72f4882019-01-16 14:55:37 +07003545 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003546 auto it = deferredForwardPointers[i];
3547 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3548 }
3549
John Kessenich6090df02016-06-30 21:18:02 -06003550 return spvType;
3551}
3552
3553void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3554 const glslang::TTypeList* glslangMembers,
3555 glslang::TLayoutPacking explicitLayout,
3556 const glslang::TQualifier& qualifier,
3557 spv::Id spvType)
3558{
3559 // Name and decorate the non-hidden members
3560 int offset = -1;
3561 int locationOffset = 0; // for use within the members of this struct
3562 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3563 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3564 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003565 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003566 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003567 if (filterMember(glslangMember))
3568 continue;
3569 }
John Kessenich6090df02016-06-30 21:18:02 -06003570
3571 // modify just this child's view of the qualifier
3572 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3573 InheritQualifiers(memberQualifier, qualifier);
3574
3575 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003576 if (member < 0)
3577 continue;
3578
3579 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3580 builder.addMemberDecoration(spvType, member,
3581 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3582 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3583 // Add interpolation and auxiliary storage decorations only to
3584 // top-level members of Input and Output storage classes
3585 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3586 type.getQualifier().storage == glslang::EvqVaryingOut) {
3587 if (type.getBasicType() == glslang::EbtBlock ||
3588 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3589 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3590 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003591#ifdef NV_EXTENSIONS
3592 addMeshNVDecoration(spvType, member, memberQualifier);
3593#endif
John Kessenich6090df02016-06-30 21:18:02 -06003594 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003595 }
3596 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003597
John Kessenich5d610ee2018-03-07 18:05:55 -07003598 if (type.getBasicType() == glslang::EbtBlock &&
3599 qualifier.storage == glslang::EvqBuffer) {
3600 // Add memory decorations only to top-level members of shader storage block
3601 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003602 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003603 for (unsigned int i = 0; i < memory.size(); ++i)
3604 builder.addMemberDecoration(spvType, member, memory[i]);
3605 }
John Kessenich6090df02016-06-30 21:18:02 -06003606
John Kessenich5d610ee2018-03-07 18:05:55 -07003607 // Location assignment was already completed correctly by the front end,
3608 // just track whether a member needs to be decorated.
3609 // Ignore member locations if the container is an array, as that's
3610 // ill-specified and decisions have been made to not allow this.
3611 if (! type.isArray() && memberQualifier.hasLocation())
3612 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003613
John Kessenich5d610ee2018-03-07 18:05:55 -07003614 if (qualifier.hasLocation()) // track for upcoming inheritance
3615 locationOffset += glslangIntermediate->computeTypeLocationSize(
3616 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003617
John Kessenich5d610ee2018-03-07 18:05:55 -07003618 // component, XFB, others
3619 if (glslangMember.getQualifier().hasComponent())
3620 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3621 glslangMember.getQualifier().layoutComponent);
3622 if (glslangMember.getQualifier().hasXfbOffset())
3623 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3624 glslangMember.getQualifier().layoutXfbOffset);
3625 else if (explicitLayout != glslang::ElpNone) {
3626 // figure out what to do with offset, which is accumulating
3627 int nextOffset;
3628 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3629 if (offset >= 0)
3630 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3631 offset = nextOffset;
3632 }
John Kessenich6090df02016-06-30 21:18:02 -06003633
John Kessenich5d610ee2018-03-07 18:05:55 -07003634 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3635 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3636 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003637
John Kessenich5d610ee2018-03-07 18:05:55 -07003638 // built-in variable decorations
3639 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3640 if (builtIn != spv::BuiltInMax)
3641 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003642
John Kessenich5611c6d2018-04-05 11:25:02 -06003643 // nonuniform
3644 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3645
John Kessenichead86222018-03-28 18:01:20 -06003646 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3647 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3648 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3649 memberQualifier.semanticName);
3650 }
3651
chaoc771d89f2017-01-13 01:10:53 -08003652#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003653 if (builtIn == spv::BuiltInLayer) {
3654 // SPV_NV_viewport_array2 extension
3655 if (glslangMember.getQualifier().layoutViewportRelative){
3656 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3657 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3658 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003659 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003660 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3661 builder.addMemberDecoration(spvType, member,
3662 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3663 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3664 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3665 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003666 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003667 }
3668 if (glslangMember.getQualifier().layoutPassthrough) {
3669 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3670 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3671 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3672 }
chaoc771d89f2017-01-13 01:10:53 -08003673#endif
John Kessenich6090df02016-06-30 21:18:02 -06003674 }
3675
3676 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003677 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3678 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003679}
3680
John Kessenich6c292d32016-02-15 20:58:50 -07003681// Turn the expression forming the array size into an id.
3682// This is not quite trivial, because of specialization constants.
3683// Sometimes, a raw constant is turned into an Id, and sometimes
3684// a specialization constant expression is.
3685spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3686{
3687 // First, see if this is sized with a node, meaning a specialization constant:
3688 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3689 if (specNode != nullptr) {
3690 builder.clearAccessChain();
3691 specNode->traverse(this);
3692 return accessChainLoad(specNode->getAsTyped()->getType());
3693 }
qining25262b32016-05-06 17:25:16 -04003694
John Kessenich6c292d32016-02-15 20:58:50 -07003695 // Otherwise, need a compile-time (front end) size, get it:
3696 int size = arraySizes.getDimSize(dim);
3697 assert(size > 0);
3698 return builder.makeUintConstant(size);
3699}
3700
John Kessenich103bef92016-02-08 21:38:15 -07003701// Wrap the builder's accessChainLoad to:
3702// - localize handling of RelaxedPrecision
3703// - use the SPIR-V inferred type instead of another conversion of the glslang type
3704// (avoids unnecessary work and possible type punning for structures)
3705// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003706spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3707{
John Kessenich103bef92016-02-08 21:38:15 -07003708 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003709
3710 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3711 coherentFlags |= TranslateCoherent(type);
3712
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003713 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003714 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003715
John Kessenich5611c6d2018-04-05 11:25:02 -06003716 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003717 TranslateNonUniformDecoration(type.getQualifier()),
3718 nominalTypeId,
3719 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003720 TranslateMemoryScope(coherentFlags),
3721 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003722
3723 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003724 if (type.getBasicType() == glslang::EbtBool) {
3725 if (builder.isScalarType(nominalTypeId)) {
3726 // Conversion for bool
3727 spv::Id boolType = builder.makeBoolType();
3728 if (nominalTypeId != boolType)
3729 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3730 } else if (builder.isVectorType(nominalTypeId)) {
3731 // Conversion for bvec
3732 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3733 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3734 if (nominalTypeId != bvecType)
3735 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3736 }
3737 }
John Kessenich103bef92016-02-08 21:38:15 -07003738
3739 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003740}
3741
Rex Xu27253232016-02-23 17:51:09 +08003742// Wrap the builder's accessChainStore to:
3743// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003744//
3745// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003746void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3747{
3748 // Need to convert to abstract types when necessary
3749 if (type.getBasicType() == glslang::EbtBool) {
3750 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3751
3752 if (builder.isScalarType(nominalTypeId)) {
3753 // Conversion for bool
3754 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003755 if (nominalTypeId != boolType) {
3756 // keep these outside arguments, for determinant order-of-evaluation
3757 spv::Id one = builder.makeUintConstant(1);
3758 spv::Id zero = builder.makeUintConstant(0);
3759 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3760 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003761 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003762 } else if (builder.isVectorType(nominalTypeId)) {
3763 // Conversion for bvec
3764 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3765 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003766 if (nominalTypeId != bvecType) {
3767 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003768 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3769 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3770 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003771 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003772 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3773 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003774 }
3775 }
3776
Jeff Bolz36831c92018-09-05 10:11:41 -05003777 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3778 coherentFlags |= TranslateCoherent(type);
3779
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003780 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003781 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003782
Jeff Bolz36831c92018-09-05 10:11:41 -05003783 builder.accessChainStore(rvalue,
3784 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003785 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003786}
3787
John Kessenich4bf71552016-09-02 11:20:21 -06003788// For storing when types match at the glslang level, but not might match at the
3789// SPIR-V level.
3790//
3791// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003792// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003793// as in a member-decorated way.
3794//
3795// NOTE: This function can handle any store request; if it's not special it
3796// simplifies to a simple OpStore.
3797//
3798// Implicitly uses the existing builder.accessChain as the storage target.
3799void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3800{
John Kessenichb3e24e42016-09-11 12:33:43 -06003801 // we only do the complex path here if it's an aggregate
3802 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003803 accessChainStore(type, rValue);
3804 return;
3805 }
3806
John Kessenichb3e24e42016-09-11 12:33:43 -06003807 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003808 spv::Id rType = builder.getTypeId(rValue);
3809 spv::Id lValue = builder.accessChainGetLValue();
3810 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3811 if (lType == rType) {
3812 accessChainStore(type, rValue);
3813 return;
3814 }
3815
John Kessenichb3e24e42016-09-11 12:33:43 -06003816 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003817 // where the two types were the same type in GLSL. This requires member
3818 // by member copy, recursively.
3819
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003820 // SPIR-V 1.4 added an instruction to do help do this.
3821 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3822 // However, bool in uniform space is changed to int, so
3823 // OpCopyLogical does not work for that.
3824 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3825 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3826 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3827 if (lBool == rBool) {
3828 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3829 accessChainStore(type, logicalCopy);
3830 return;
3831 }
3832 }
3833
John Kessenichb3e24e42016-09-11 12:33:43 -06003834 // If an array, copy element by element.
3835 if (type.isArray()) {
3836 glslang::TType glslangElementType(type, 0);
3837 spv::Id elementRType = builder.getContainedTypeId(rType);
3838 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3839 // get the source member
3840 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003841
John Kessenichb3e24e42016-09-11 12:33:43 -06003842 // set up the target storage
3843 builder.clearAccessChain();
3844 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003845 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003846
John Kessenichb3e24e42016-09-11 12:33:43 -06003847 // store the member
3848 multiTypeStore(glslangElementType, elementRValue);
3849 }
3850 } else {
3851 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003852
John Kessenichb3e24e42016-09-11 12:33:43 -06003853 // loop over structure members
3854 const glslang::TTypeList& members = *type.getStruct();
3855 for (int m = 0; m < (int)members.size(); ++m) {
3856 const glslang::TType& glslangMemberType = *members[m].type;
3857
3858 // get the source member
3859 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3860 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3861
3862 // set up the target storage
3863 builder.clearAccessChain();
3864 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003865 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003866
3867 // store the member
3868 multiTypeStore(glslangMemberType, memberRValue);
3869 }
John Kessenich4bf71552016-09-02 11:20:21 -06003870 }
3871}
3872
John Kessenichf85e8062015-12-19 13:57:10 -07003873// Decide whether or not this type should be
3874// decorated with offsets and strides, and if so
3875// whether std140 or std430 rules should be applied.
3876glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003877{
John Kessenichf85e8062015-12-19 13:57:10 -07003878 // has to be a block
3879 if (type.getBasicType() != glslang::EbtBlock)
3880 return glslang::ElpNone;
3881
Chao Chen3c366992018-09-19 11:41:59 -07003882 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003883 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003884 type.getQualifier().storage != glslang::EvqBuffer &&
3885 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003886 return glslang::ElpNone;
3887
3888 // return the layout to use
3889 switch (type.getQualifier().layoutPacking) {
3890 case glslang::ElpStd140:
3891 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003892 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003893 return type.getQualifier().layoutPacking;
3894 default:
3895 return glslang::ElpNone;
3896 }
John Kessenich31ed4832015-09-09 17:51:38 -06003897}
3898
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003899// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003900int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003901{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003902 int size;
John Kessenich49987892015-12-29 17:11:44 -07003903 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003904 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003905
3906 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003907}
3908
John Kessenich49987892015-12-29 17:11:44 -07003909// 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 -07003910// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003911int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003912{
John Kessenich49987892015-12-29 17:11:44 -07003913 glslang::TType elementType;
3914 elementType.shallowCopy(matrixType);
3915 elementType.clearArraySizes();
3916
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003917 int size;
John Kessenich49987892015-12-29 17:11:44 -07003918 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003919 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003920
3921 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003922}
3923
John Kessenich5e4b1242015-08-06 22:53:06 -06003924// Given a member type of a struct, realign the current offset for it, and compute
3925// the next (not yet aligned) offset for the next member, which will get aligned
3926// on the next call.
3927// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3928// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3929// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003930void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003931 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003932{
3933 // this will get a positive value when deemed necessary
3934 nextOffset = -1;
3935
John Kessenich5e4b1242015-08-06 22:53:06 -06003936 // override anything in currentOffset with user-set offset
3937 if (memberType.getQualifier().hasOffset())
3938 currentOffset = memberType.getQualifier().layoutOffset;
3939
3940 // It could be that current linker usage in glslang updated all the layoutOffset,
3941 // in which case the following code does not matter. But, that's not quite right
3942 // once cross-compilation unit GLSL validation is done, as the original user
3943 // settings are needed in layoutOffset, and then the following will come into play.
3944
John Kessenichf85e8062015-12-19 13:57:10 -07003945 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003946 if (! memberType.getQualifier().hasOffset())
3947 currentOffset = -1;
3948
3949 return;
3950 }
3951
John Kessenichf85e8062015-12-19 13:57:10 -07003952 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003953 if (currentOffset < 0)
3954 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003955
John Kessenich5e4b1242015-08-06 22:53:06 -06003956 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3957 // but possibly not yet correctly aligned.
3958
3959 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003960 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003961 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003962
3963 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003964 // TODO: make this consistent in early phases of code:
3965 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3966 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3967 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003968 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003969 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003970 int dummySize;
3971 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3972 if (componentAlignment <= 4)
3973 memberAlignment = componentAlignment;
3974 }
3975
3976 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003977 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003978
3979 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003980 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003981 glslang::RoundToPow2(currentOffset, 16);
3982
John Kessenich5e4b1242015-08-06 22:53:06 -06003983 nextOffset = currentOffset + memberSize;
3984}
3985
David Netoa901ffe2016-06-08 14:11:40 +01003986void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003987{
David Netoa901ffe2016-06-08 14:11:40 +01003988 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3989 switch (glslangBuiltIn)
3990 {
3991 case glslang::EbvClipDistance:
3992 case glslang::EbvCullDistance:
3993 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003994#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003995 case glslang::EbvViewportMaskNV:
3996 case glslang::EbvSecondaryPositionNV:
3997 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003998 case glslang::EbvPositionPerViewNV:
3999 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07004000 case glslang::EbvTaskCountNV:
4001 case glslang::EbvPrimitiveCountNV:
4002 case glslang::EbvPrimitiveIndicesNV:
4003 case glslang::EbvClipDistancePerViewNV:
4004 case glslang::EbvCullDistancePerViewNV:
4005 case glslang::EbvLayerPerViewNV:
4006 case glslang::EbvMeshViewCountNV:
4007 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004008#endif
David Netoa901ffe2016-06-08 14:11:40 +01004009 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4010 // Alternately, we could just call this for any glslang built-in, since the
4011 // capability already guards against duplicates.
4012 TranslateBuiltInDecoration(glslangBuiltIn, false);
4013 break;
4014 default:
4015 // Capabilities were already generated when the struct was declared.
4016 break;
4017 }
John Kessenichebb50532016-05-16 19:22:05 -06004018}
4019
John Kessenich6fccb3c2016-09-19 16:01:41 -06004020bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004021{
John Kessenicheee9d532016-09-19 18:09:30 -06004022 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004023}
4024
John Kessenichd41993d2017-09-10 15:21:05 -06004025// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004026// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4027// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004028bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004029{
John Kessenich6a14f782017-12-04 02:48:10 -07004030 assert(qualifier == glslang::EvqIn ||
4031 qualifier == glslang::EvqOut ||
4032 qualifier == glslang::EvqInOut ||
4033 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004034 return qualifier != glslang::EvqConstReadOnly;
4035}
4036
4037// Is parameter pass-by-original?
4038bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4039 bool implicitThisParam)
4040{
4041 if (implicitThisParam) // implicit this
4042 return true;
4043 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004044 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004045 return paramType.containsOpaque() || // sampler, etc.
4046 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4047}
4048
John Kessenich140f3df2015-06-26 16:58:36 -06004049// Make all the functions, skeletally, without actually visiting their bodies.
4050void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4051{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004052 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004053 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4054 if (paramPrecision != spv::NoPrecision)
4055 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004056 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004057 if (type.getBasicType() == glslang::EbtReference) {
4058 // Original and non-writable params pass the pointer directly and
4059 // use restrict/aliased, others are stored to a pointer in Function
4060 // memory and use RestrictPointer/AliasedPointer.
4061 if (originalParam(type.getQualifier().storage, type, false) ||
4062 !writableParam(type.getQualifier().storage)) {
4063 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
4064 } else {
4065 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
4066 }
4067 }
John Kessenichfad62972017-07-18 02:35:46 -06004068 };
4069
John Kessenich140f3df2015-06-26 16:58:36 -06004070 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4071 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004072 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004073 continue;
4074
4075 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004076 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004077 //
qining25262b32016-05-06 17:25:16 -04004078 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004079 // function. What it is an address of varies:
4080 //
John Kessenich4bf71552016-09-02 11:20:21 -06004081 // - "in" parameters not marked as "const" can be written to without modifying the calling
4082 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004083 //
4084 // - "const in" parameters can just be the r-value, as no writes need occur.
4085 //
John Kessenich4bf71552016-09-02 11:20:21 -06004086 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4087 // 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 -06004088
4089 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004090 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004091 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4092
John Kessenichfad62972017-07-18 02:35:46 -06004093 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4094 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06004095
John Kessenichfad62972017-07-18 02:35:46 -06004096 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004097 for (int p = 0; p < (int)parameters.size(); ++p) {
4098 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4099 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004100 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004101 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004102 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004103 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4104 else
John Kessenich4bf71552016-09-02 11:20:21 -06004105 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004106 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004107 paramTypes.push_back(typeId);
4108 }
4109
4110 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004111 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4112 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004113 glslFunction->getName().c_str(), paramTypes,
4114 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004115 if (implicitThis)
4116 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004117
4118 // Track function to emit/call later
4119 functionMap[glslFunction->getName().c_str()] = function;
4120
4121 // Set the parameter id's
4122 for (int p = 0; p < (int)parameters.size(); ++p) {
4123 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4124 // give a name too
4125 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004126
4127 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4128 if (paramType.containsBasicType(glslang::EbtInt8) ||
4129 paramType.containsBasicType(glslang::EbtUint8))
4130 builder.addCapability(spv::CapabilityInt8);
4131 if (paramType.containsBasicType(glslang::EbtInt16) ||
4132 paramType.containsBasicType(glslang::EbtUint16))
4133 builder.addCapability(spv::CapabilityInt16);
4134 if (paramType.containsBasicType(glslang::EbtFloat16))
4135 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004136 }
4137 }
4138}
4139
4140// Process all the initializers, while skipping the functions and link objects
4141void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4142{
4143 builder.setBuildPoint(shaderEntry->getLastBlock());
4144 for (int i = 0; i < (int)initializers.size(); ++i) {
4145 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4146 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4147
4148 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004149 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004150 initializer->traverse(this);
4151 }
4152 }
4153}
4154
4155// Process all the functions, while skipping initializers.
4156void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4157{
4158 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4159 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004160 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004161 node->traverse(this);
4162 }
4163}
4164
4165void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4166{
qining25262b32016-05-06 17:25:16 -04004167 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004168 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004169 currentFunction = functionMap[node->getName().c_str()];
4170 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004171 builder.setBuildPoint(functionBlock);
4172}
4173
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004174void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004175{
Rex Xufc618912015-09-09 16:42:49 +08004176 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004177
4178 glslang::TSampler sampler = {};
4179 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004180#ifdef AMD_EXTENSIONS
4181 bool f16ShadowCompare = false;
4182#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004183 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004184 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4185 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004186#ifdef AMD_EXTENSIONS
4187 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4188#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004189 }
4190
John Kessenich140f3df2015-06-26 16:58:36 -06004191 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4192 builder.clearAccessChain();
4193 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004194
4195 // Special case l-value operands
4196 bool lvalue = false;
4197 switch (node.getOp()) {
4198 case glslang::EOpImageAtomicAdd:
4199 case glslang::EOpImageAtomicMin:
4200 case glslang::EOpImageAtomicMax:
4201 case glslang::EOpImageAtomicAnd:
4202 case glslang::EOpImageAtomicOr:
4203 case glslang::EOpImageAtomicXor:
4204 case glslang::EOpImageAtomicExchange:
4205 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004206 case glslang::EOpImageAtomicLoad:
4207 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004208 if (i == 0)
4209 lvalue = true;
4210 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004211 case glslang::EOpSparseImageLoad:
4212 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4213 lvalue = true;
4214 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004215#ifdef AMD_EXTENSIONS
4216 case glslang::EOpSparseTexture:
4217 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4218 lvalue = true;
4219 break;
4220 case glslang::EOpSparseTextureClamp:
4221 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4222 lvalue = true;
4223 break;
4224 case glslang::EOpSparseTextureLod:
4225 case glslang::EOpSparseTextureOffset:
4226 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4227 lvalue = true;
4228 break;
4229#else
Rex Xu48edadf2015-12-31 16:11:41 +08004230 case glslang::EOpSparseTexture:
4231 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4232 lvalue = true;
4233 break;
4234 case glslang::EOpSparseTextureClamp:
4235 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4236 lvalue = true;
4237 break;
4238 case glslang::EOpSparseTextureLod:
4239 case glslang::EOpSparseTextureOffset:
4240 if (i == 3)
4241 lvalue = true;
4242 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004243#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004244 case glslang::EOpSparseTextureFetch:
4245 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4246 lvalue = true;
4247 break;
4248 case glslang::EOpSparseTextureFetchOffset:
4249 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4250 lvalue = true;
4251 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004252#ifdef AMD_EXTENSIONS
4253 case glslang::EOpSparseTextureLodOffset:
4254 case glslang::EOpSparseTextureGrad:
4255 case glslang::EOpSparseTextureOffsetClamp:
4256 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4257 lvalue = true;
4258 break;
4259 case glslang::EOpSparseTextureGradOffset:
4260 case glslang::EOpSparseTextureGradClamp:
4261 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4262 lvalue = true;
4263 break;
4264 case glslang::EOpSparseTextureGradOffsetClamp:
4265 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4266 lvalue = true;
4267 break;
4268#else
Rex Xu48edadf2015-12-31 16:11:41 +08004269 case glslang::EOpSparseTextureLodOffset:
4270 case glslang::EOpSparseTextureGrad:
4271 case glslang::EOpSparseTextureOffsetClamp:
4272 if (i == 4)
4273 lvalue = true;
4274 break;
4275 case glslang::EOpSparseTextureGradOffset:
4276 case glslang::EOpSparseTextureGradClamp:
4277 if (i == 5)
4278 lvalue = true;
4279 break;
4280 case glslang::EOpSparseTextureGradOffsetClamp:
4281 if (i == 6)
4282 lvalue = true;
4283 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004284#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004285 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004286 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4287 lvalue = true;
4288 break;
4289 case glslang::EOpSparseTextureGatherOffset:
4290 case glslang::EOpSparseTextureGatherOffsets:
4291 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4292 lvalue = true;
4293 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004294#ifdef AMD_EXTENSIONS
4295 case glslang::EOpSparseTextureGatherLod:
4296 if (i == 3)
4297 lvalue = true;
4298 break;
4299 case glslang::EOpSparseTextureGatherLodOffset:
4300 case glslang::EOpSparseTextureGatherLodOffsets:
4301 if (i == 4)
4302 lvalue = true;
4303 break;
Rex Xu129799a2017-07-05 17:23:28 +08004304 case glslang::EOpSparseImageLoadLod:
4305 if (i == 3)
4306 lvalue = true;
4307 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004308#endif
Chao Chen3a137962018-09-19 11:41:27 -07004309#ifdef NV_EXTENSIONS
4310 case glslang::EOpImageSampleFootprintNV:
4311 if (i == 4)
4312 lvalue = true;
4313 break;
4314 case glslang::EOpImageSampleFootprintClampNV:
4315 case glslang::EOpImageSampleFootprintLodNV:
4316 if (i == 5)
4317 lvalue = true;
4318 break;
4319 case glslang::EOpImageSampleFootprintGradNV:
4320 if (i == 6)
4321 lvalue = true;
4322 break;
4323 case glslang::EOpImageSampleFootprintGradClampNV:
4324 if (i == 7)
4325 lvalue = true;
4326 break;
4327#endif
Rex Xufc618912015-09-09 16:42:49 +08004328 default:
4329 break;
4330 }
4331
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004332 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004333 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004334 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4335 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4336 } else
John Kessenich32cfd492016-02-02 12:37:46 -07004337 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004338 }
4339}
4340
John Kessenichfc51d282015-08-19 13:34:18 -06004341void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004342{
John Kessenichfc51d282015-08-19 13:34:18 -06004343 builder.clearAccessChain();
4344 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004345 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004346}
John Kessenich140f3df2015-06-26 16:58:36 -06004347
John Kessenichfc51d282015-08-19 13:34:18 -06004348spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4349{
John Kesseniche485c7a2017-05-31 18:50:53 -06004350 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004351 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004352
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004353 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004354
John Kessenichfc51d282015-08-19 13:34:18 -06004355 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004356
John Kessenichf43c7392019-03-31 10:51:57 -06004357 const glslang::TType &imageType = node->getAsAggregate()
4358 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4359 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004360 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004361#ifdef AMD_EXTENSIONS
4362 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004363 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4364 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004365#endif
4366
John Kessenichf43c7392019-03-31 10:51:57 -06004367 const auto signExtensionMask = [&]() {
4368 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4369 if (sampler.type == glslang::EbtUint)
4370 return spv::ImageOperandsZeroExtendMask;
4371 else if (sampler.type == glslang::EbtInt)
4372 return spv::ImageOperandsSignExtendMask;
4373 }
4374 return spv::ImageOperandsMaskNone;
4375 };
4376
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004377 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4378
John Kessenichfc51d282015-08-19 13:34:18 -06004379 std::vector<spv::Id> arguments;
4380 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004381 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004382 else
4383 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004384 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004385
4386 spv::Builder::TextureParameters params = { };
4387 params.sampler = arguments[0];
4388
Rex Xu04db3f52015-09-16 11:44:02 +08004389 glslang::TCrackedTextureOp cracked;
4390 node->crackTexture(sampler, cracked);
4391
amhagan05506bb2017-06-13 16:53:02 -04004392 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004393
John Kessenichfc51d282015-08-19 13:34:18 -06004394 // Check for queries
4395 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004396 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4397 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004398 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004399
John Kessenichfc51d282015-08-19 13:34:18 -06004400 switch (node->getOp()) {
4401 case glslang::EOpImageQuerySize:
4402 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004403 if (arguments.size() > 1) {
4404 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004405 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004406 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004407 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004408 case glslang::EOpImageQuerySamples:
4409 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004410 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004411 case glslang::EOpTextureQueryLod:
4412 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004413 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004414 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004415 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004416 case glslang::EOpSparseTexelsResident:
4417 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004418 default:
4419 assert(0);
4420 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004421 }
John Kessenich140f3df2015-06-26 16:58:36 -06004422 }
4423
LoopDawg4425f242018-02-18 11:40:01 -07004424 int components = node->getType().getVectorSize();
4425
4426 if (node->getOp() == glslang::EOpTextureFetch) {
4427 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4428 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4429 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4430 // here around e.g. which ones return scalars or other types.
4431 components = 4;
4432 }
4433
4434 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4435
4436 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4437
Rex Xufc618912015-09-09 16:42:49 +08004438 // Check for image functions other than queries
4439 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004440 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004441 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004442 spv::IdImmediate image = { true, *(opIt++) };
4443 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004444
4445 // Handle subpass operations
4446 // TODO: GLSL should change to have the "MS" only on the type rather than the
4447 // built-in function.
4448 if (cracked.subpass) {
4449 // add on the (0,0) coordinate
4450 spv::Id zero = builder.makeIntConstant(0);
4451 std::vector<spv::Id> comps;
4452 comps.push_back(zero);
4453 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004454 spv::IdImmediate coord = { true,
4455 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4456 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004457 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4458 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich6c292d32016-02-15 20:58:50 -07004459 if (sampler.ms) {
John Kessenichf43c7392019-03-31 10:51:57 -06004460 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4461 }
4462 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004463 operands.push_back(imageOperands);
John Kessenichf43c7392019-03-31 10:51:57 -06004464 if (sampler.ms) {
4465 spv::IdImmediate imageOperand = { true, *(opIt++) };
4466 operands.push_back(imageOperand);
4467 }
John Kessenich6c292d32016-02-15 20:58:50 -07004468 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004469 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4470 builder.setPrecision(result, precision);
4471 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004472 }
4473
John Kessenich149afc32018-08-14 13:31:43 -06004474 spv::IdImmediate coord = { true, *(opIt++) };
4475 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004476#ifdef AMD_EXTENSIONS
4477 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4478#else
John Kessenich56bab042015-09-16 10:54:31 -06004479 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004480#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004481 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004482 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004483 mask = mask | spv::ImageOperandsSampleMask;
4484 }
Rex Xu129799a2017-07-05 17:23:28 +08004485#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004486 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004487 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4488 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004489 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004490 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004491#endif
4492 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4493 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004494 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004495 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004496 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4497 operands.push_back(imageOperands);
4498 }
4499 if (mask & spv::ImageOperandsSampleMask) {
4500 spv::IdImmediate imageOperand = { true, *opIt++ };
4501 operands.push_back(imageOperand);
4502 }
4503#ifdef AMD_EXTENSIONS
4504 if (mask & spv::ImageOperandsLodMask) {
4505 spv::IdImmediate imageOperand = { true, *opIt++ };
4506 operands.push_back(imageOperand);
4507 }
4508#endif
4509 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004510 spv::IdImmediate imageOperand = { true,
4511 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004512 operands.push_back(imageOperand);
4513 }
4514
John Kessenich149afc32018-08-14 13:31:43 -06004515 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004516 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004517
John Kessenich149afc32018-08-14 13:31:43 -06004518 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004519 builder.setPrecision(result[0], precision);
4520
4521 // If needed, add a conversion constructor to the proper size.
4522 if (components != node->getType().getVectorSize())
4523 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4524
4525 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004526#ifdef AMD_EXTENSIONS
4527 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4528#else
John Kessenich56bab042015-09-16 10:54:31 -06004529 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004530#endif
Rex Xu129799a2017-07-05 17:23:28 +08004531
Jeff Bolz36831c92018-09-05 10:11:41 -05004532 // Push the texel value before the operands
4533#ifdef AMD_EXTENSIONS
4534 if (sampler.ms || cracked.lod) {
4535#else
4536 if (sampler.ms) {
4537#endif
John Kessenich149afc32018-08-14 13:31:43 -06004538 spv::IdImmediate texel = { true, *(opIt + 1) };
4539 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004540 } else {
4541 spv::IdImmediate texel = { true, *opIt };
4542 operands.push_back(texel);
4543 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004544
4545 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4546 if (sampler.ms) {
4547 mask = mask | spv::ImageOperandsSampleMask;
4548 }
4549#ifdef AMD_EXTENSIONS
4550 if (cracked.lod) {
4551 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4552 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4553 mask = mask | spv::ImageOperandsLodMask;
4554 }
4555#endif
4556 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4557 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004558 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004559 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004560 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4561 operands.push_back(imageOperands);
4562 }
4563 if (mask & spv::ImageOperandsSampleMask) {
4564 spv::IdImmediate imageOperand = { true, *opIt++ };
4565 operands.push_back(imageOperand);
4566 }
4567#ifdef AMD_EXTENSIONS
4568 if (mask & spv::ImageOperandsLodMask) {
4569 spv::IdImmediate imageOperand = { true, *opIt++ };
4570 operands.push_back(imageOperand);
4571 }
4572#endif
4573 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004574 spv::IdImmediate imageOperand = { true,
4575 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004576 operands.push_back(imageOperand);
4577 }
4578
John Kessenich56bab042015-09-16 10:54:31 -06004579 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004580 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004581 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004582 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004583#ifdef AMD_EXTENSIONS
John Kessenichf43c7392019-03-31 10:51:57 -06004584 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4585 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004586#else
Rex Xu5eafa472016-02-19 22:24:03 +08004587 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004588#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004589 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004590 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004591 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4592
Jeff Bolz36831c92018-09-05 10:11:41 -05004593 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004594 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004595 mask = mask | spv::ImageOperandsSampleMask;
4596 }
Rex Xu129799a2017-07-05 17:23:28 +08004597#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004598 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004599 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4600 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4601
Jeff Bolz36831c92018-09-05 10:11:41 -05004602 mask = mask | spv::ImageOperandsLodMask;
4603 }
4604#endif
4605 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4606 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004607 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004608 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004609 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004610 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004611 }
4612 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004613 spv::IdImmediate imageOperand = { true, *opIt++ };
4614 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004615 }
4616#ifdef AMD_EXTENSIONS
4617 if (mask & spv::ImageOperandsLodMask) {
4618 spv::IdImmediate imageOperand = { true, *opIt++ };
4619 operands.push_back(imageOperand);
4620 }
Rex Xu129799a2017-07-05 17:23:28 +08004621#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004622 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4623 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4624 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004625 }
4626
4627 // Create the return type that was a special structure
4628 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004629 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004630 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4631 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4632
4633 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4634
4635 // Decode the return type
4636 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4637 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004638 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004639 // Process image atomic operations
4640
4641 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4642 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004643 // For non-MS, the sample value should be 0
4644 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4645 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004646
Jeff Bolz36831c92018-09-05 10:11:41 -05004647 spv::Id resultTypeId;
4648 // imageAtomicStore has a void return type so base the pointer type on
4649 // the type of the value operand.
4650 if (node->getOp() == glslang::EOpImageAtomicStore) {
4651 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4652 } else {
4653 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4654 }
John Kessenich56bab042015-09-16 10:54:31 -06004655 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004656
4657 std::vector<spv::Id> operands;
4658 operands.push_back(pointer);
4659 for (; opIt != arguments.end(); ++opIt)
4660 operands.push_back(*opIt);
4661
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004662 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004663 }
4664 }
4665
amhagan05506bb2017-06-13 16:53:02 -04004666#ifdef AMD_EXTENSIONS
4667 // Check for fragment mask functions other than queries
4668 if (cracked.fragMask) {
4669 assert(sampler.ms);
4670
4671 auto opIt = arguments.begin();
4672 std::vector<spv::Id> operands;
4673
4674 // Extract the image if necessary
4675 if (builder.isSampledImage(params.sampler))
4676 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4677
4678 operands.push_back(params.sampler);
4679 ++opIt;
4680
4681 if (sampler.isSubpass()) {
4682 // add on the (0,0) coordinate
4683 spv::Id zero = builder.makeIntConstant(0);
4684 std::vector<spv::Id> comps;
4685 comps.push_back(zero);
4686 comps.push_back(zero);
4687 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4688 }
4689
4690 for (; opIt != arguments.end(); ++opIt)
4691 operands.push_back(*opIt);
4692
4693 spv::Op fragMaskOp = spv::OpNop;
4694 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4695 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4696 else if (node->getOp() == glslang::EOpFragmentFetch)
4697 fragMaskOp = spv::OpFragmentFetchAMD;
4698
4699 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4700 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4701 return builder.createOp(fragMaskOp, resultType(), operands);
4702 }
4703#endif
4704
Rex Xufc618912015-09-09 16:42:49 +08004705 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004706 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004707#ifdef NV_EXTENSIONS
4708 bool imageFootprint = node->isImageFootprint();
4709#endif
4710
Rex Xu71519fe2015-11-11 15:35:47 +08004711 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4712
John Kessenichfc51d282015-08-19 13:34:18 -06004713 // check for bias argument
4714 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004715#ifdef AMD_EXTENSIONS
4716 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4717#else
Rex Xu71519fe2015-11-11 15:35:47 +08004718 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004719#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004720 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004721#ifdef AMD_EXTENSIONS
4722 if (cracked.gather)
4723 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004724
4725 if (f16ShadowCompare)
4726 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004727#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004728 if (cracked.offset)
4729 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004730#ifdef AMD_EXTENSIONS
4731 else if (cracked.offsets)
4732 ++nonBiasArgCount;
4733#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004734 if (cracked.grad)
4735 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004736 if (cracked.lodClamp)
4737 ++nonBiasArgCount;
4738 if (sparse)
4739 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004740#ifdef NV_EXTENSIONS
4741 if (imageFootprint)
4742 //Following three extra arguments
4743 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4744 nonBiasArgCount += 3;
4745#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004746 if ((int)arguments.size() > nonBiasArgCount)
4747 bias = true;
4748 }
4749
John Kessenicha5c33d62016-06-02 23:45:21 -06004750 // See if the sampler param should really be just the SPV image part
4751 if (cracked.fetch) {
4752 // a fetch needs to have the image extracted first
4753 if (builder.isSampledImage(params.sampler))
4754 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4755 }
4756
Rex Xu225e0fc2016-11-17 17:47:59 +08004757#ifdef AMD_EXTENSIONS
4758 if (cracked.gather) {
4759 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4760 if (bias || cracked.lod ||
4761 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4762 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004763 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004764 }
4765 }
4766#endif
4767
John Kessenichfc51d282015-08-19 13:34:18 -06004768 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004769
John Kessenichfc51d282015-08-19 13:34:18 -06004770 params.coords = arguments[1];
4771 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004772 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004773
4774 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004775#ifdef AMD_EXTENSIONS
4776 if (cubeCompare || f16ShadowCompare) {
4777#else
Rex Xu48edadf2015-12-31 16:11:41 +08004778 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004779#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004780 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004781 ++extraArgs;
4782 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004783 params.Dref = arguments[2];
4784 ++extraArgs;
4785 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004786 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004787 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004788 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004789 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004790 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004791 dRefComp = builder.getNumComponents(params.coords) - 1;
4792 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004793 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4794 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004795
4796 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004797 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004798 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004799 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004800 } else if (glslangIntermediate->getStage() != EShLangFragment
4801#ifdef NV_EXTENSIONS
4802 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4803 && !(glslangIntermediate->getStage() == EShLangCompute &&
4804 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4805#endif
4806 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004807 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4808 noImplicitLod = true;
4809 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004810
4811 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004812 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004813 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004814 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004815 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004816
4817 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004818 if (cracked.grad) {
4819 params.gradX = arguments[2 + extraArgs];
4820 params.gradY = arguments[3 + extraArgs];
4821 extraArgs += 2;
4822 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004823
4824 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004825 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004826 params.offset = arguments[2 + extraArgs];
4827 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004828 } else if (cracked.offsets) {
4829 params.offsets = arguments[2 + extraArgs];
4830 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004831 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004832
4833 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004834 if (cracked.lodClamp) {
4835 params.lodClamp = arguments[2 + extraArgs];
4836 ++extraArgs;
4837 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004838 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004839 if (sparse) {
4840 params.texelOut = arguments[2 + extraArgs];
4841 ++extraArgs;
4842 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004843
John Kessenich76d4dfc2016-06-16 12:43:23 -06004844 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004845 if (cracked.gather && ! sampler.shadow) {
4846 // default component is 0, if missing, otherwise an argument
4847 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004848 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004849 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004850 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004851 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004852 }
Chao Chen3a137962018-09-19 11:41:27 -07004853#ifdef NV_EXTENSIONS
4854 spv::Id resultStruct = spv::NoResult;
4855 if (imageFootprint) {
4856 //Following three extra arguments
4857 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4858 params.granularity = arguments[2 + extraArgs];
4859 params.coarse = arguments[3 + extraArgs];
4860 resultStruct = arguments[4 + extraArgs];
4861 extraArgs += 3;
4862 }
4863#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004864 // bias
4865 if (bias) {
4866 params.bias = arguments[2 + extraArgs];
4867 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004868 }
John Kessenichfc51d282015-08-19 13:34:18 -06004869
Chao Chen3a137962018-09-19 11:41:27 -07004870#ifdef NV_EXTENSIONS
4871 if (imageFootprint) {
4872 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4873 builder.addCapability(spv::CapabilityImageFootprintNV);
4874
4875
4876 //resultStructType(OpenGL type) contains 5 elements:
4877 //struct gl_TextureFootprint2DNV {
4878 // uvec2 anchor;
4879 // uvec2 offset;
4880 // uvec2 mask;
4881 // uint lod;
4882 // uint granularity;
4883 //};
4884 //or
4885 //struct gl_TextureFootprint3DNV {
4886 // uvec3 anchor;
4887 // uvec3 offset;
4888 // uvec2 mask;
4889 // uint lod;
4890 // uint granularity;
4891 //};
4892 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4893 assert(builder.isStructType(resultStructType));
4894
4895 //resType (SPIR-V type) contains 6 elements:
4896 //Member 0 must be a Boolean type scalar(LOD),
4897 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4898 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4899 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4900 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4901 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4902 std::vector<spv::Id> members;
4903 members.push_back(resultType());
4904 for (int i = 0; i < 5; i++) {
4905 members.push_back(builder.getContainedTypeId(resultStructType, i));
4906 }
4907 spv::Id resType = builder.makeStructType(members, "ResType");
4908
4909 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004910 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4911 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004912
4913 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4914 for (int i = 0; i < 5; i++) {
4915 builder.clearAccessChain();
4916 builder.setAccessChainLValue(resultStruct);
4917
4918 //Accessing to a struct we created, no coherent flag is set
4919 spv::Builder::AccessChain::CoherentFlags flags;
4920 flags.clear();
4921
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004922 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004923 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4924 }
4925 return builder.createCompositeExtract(res, resultType(), 0);
4926 }
4927#endif
4928
John Kessenich65336482016-06-16 14:06:26 -06004929 // projective component (might not to move)
4930 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4931 // are divided by the last component of P."
4932 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4933 // unused components will appear after all used components."
4934 if (cracked.proj) {
4935 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4936 int projTargetComp;
4937 switch (sampler.dim) {
4938 case glslang::Esd1D: projTargetComp = 1; break;
4939 case glslang::Esd2D: projTargetComp = 2; break;
4940 case glslang::EsdRect: projTargetComp = 2; break;
4941 default: projTargetComp = projSourceComp; break;
4942 }
4943 // copy the projective coordinate if we have to
4944 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004945 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004946 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4947 projSourceComp);
4948 params.coords = builder.createCompositeInsert(projComp, params.coords,
4949 builder.getTypeId(params.coords), projTargetComp);
4950 }
4951 }
4952
Jeff Bolz36831c92018-09-05 10:11:41 -05004953 // nonprivate
4954 if (imageType.getQualifier().nonprivate) {
4955 params.nonprivate = true;
4956 }
4957
4958 // volatile
4959 if (imageType.getQualifier().volatil) {
4960 params.volatil = true;
4961 }
4962
St0fFa1184dd2018-04-09 21:08:14 +02004963 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004964 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4965 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004966 );
LoopDawg4425f242018-02-18 11:40:01 -07004967
4968 if (components != node->getType().getVectorSize())
4969 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4970
4971 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004972}
4973
4974spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4975{
4976 // Grab the function's pointer from the previously created function
4977 spv::Function* function = functionMap[node->getName().c_str()];
4978 if (! function)
4979 return 0;
4980
4981 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4982 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4983
4984 // See comments in makeFunctions() for details about the semantics for parameter passing.
4985 //
4986 // These imply we need a four step process:
4987 // 1. Evaluate the arguments
4988 // 2. Allocate and make copies of in, out, and inout arguments
4989 // 3. Make the call
4990 // 4. Copy back the results
4991
John Kessenichd3ed90b2018-05-04 11:43:03 -06004992 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004993 std::vector<spv::Builder::AccessChain> lValues;
4994 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004995 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004996 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004997 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004998 // build l-value
4999 builder.clearAccessChain();
5000 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06005001 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06005002 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07005003 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005004 // save l-value
5005 lValues.push_back(builder.getAccessChain());
5006 } else {
5007 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005008 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005009 }
5010 }
5011
5012 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5013 // copy the original into that space.
5014 //
5015 // Also, build up the list of actual arguments to pass in for the call
5016 int lValueCount = 0;
5017 int rValueCount = 0;
5018 std::vector<spv::Id> spvArgs;
5019 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5020 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005021 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005022 builder.setAccessChain(lValues[lValueCount]);
5023 arg = builder.accessChainGetLValue();
5024 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005025 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005026 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06005027 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005028 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5029 // need to copy the input into output space
5030 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005031 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005032 builder.clearAccessChain();
5033 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005034 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005035 }
5036 ++lValueCount;
5037 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005038 // process r-value, which involves a copy for a type mismatch
5039 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5040 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5041 builder.clearAccessChain();
5042 builder.setAccessChainLValue(argCopy);
5043 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5044 arg = builder.createLoad(argCopy);
5045 } else
5046 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005047 ++rValueCount;
5048 }
5049 spvArgs.push_back(arg);
5050 }
5051
5052 // 3. Make the call.
5053 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005054 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005055
5056 // 4. Copy back out an "out" arguments.
5057 lValueCount = 0;
5058 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005059 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005060 ++lValueCount;
5061 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005062 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5063 spv::Id copy = builder.createLoad(spvArgs[a]);
5064 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005065 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005066 }
5067 ++lValueCount;
5068 }
5069 }
5070
5071 return result;
5072}
5073
5074// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005075spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005076 spv::Id typeId, spv::Id left, spv::Id right,
5077 glslang::TBasicType typeProxy, bool reduceComparison)
5078{
John Kessenich66011cb2018-03-06 16:12:04 -07005079 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5080 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005081 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005082
5083 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005084 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005085 bool comparison = false;
5086
5087 switch (op) {
5088 case glslang::EOpAdd:
5089 case glslang::EOpAddAssign:
5090 if (isFloat)
5091 binOp = spv::OpFAdd;
5092 else
5093 binOp = spv::OpIAdd;
5094 break;
5095 case glslang::EOpSub:
5096 case glslang::EOpSubAssign:
5097 if (isFloat)
5098 binOp = spv::OpFSub;
5099 else
5100 binOp = spv::OpISub;
5101 break;
5102 case glslang::EOpMul:
5103 case glslang::EOpMulAssign:
5104 if (isFloat)
5105 binOp = spv::OpFMul;
5106 else
5107 binOp = spv::OpIMul;
5108 break;
5109 case glslang::EOpVectorTimesScalar:
5110 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005111 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005112 if (builder.isVector(right))
5113 std::swap(left, right);
5114 assert(builder.isScalar(right));
5115 needMatchingVectors = false;
5116 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005117 } else if (isFloat)
5118 binOp = spv::OpFMul;
5119 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005120 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005121 break;
5122 case glslang::EOpVectorTimesMatrix:
5123 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005124 binOp = spv::OpVectorTimesMatrix;
5125 break;
5126 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005127 binOp = spv::OpMatrixTimesVector;
5128 break;
5129 case glslang::EOpMatrixTimesScalar:
5130 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005131 binOp = spv::OpMatrixTimesScalar;
5132 break;
5133 case glslang::EOpMatrixTimesMatrix:
5134 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005135 binOp = spv::OpMatrixTimesMatrix;
5136 break;
5137 case glslang::EOpOuterProduct:
5138 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005139 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005140 break;
5141
5142 case glslang::EOpDiv:
5143 case glslang::EOpDivAssign:
5144 if (isFloat)
5145 binOp = spv::OpFDiv;
5146 else if (isUnsigned)
5147 binOp = spv::OpUDiv;
5148 else
5149 binOp = spv::OpSDiv;
5150 break;
5151 case glslang::EOpMod:
5152 case glslang::EOpModAssign:
5153 if (isFloat)
5154 binOp = spv::OpFMod;
5155 else if (isUnsigned)
5156 binOp = spv::OpUMod;
5157 else
5158 binOp = spv::OpSMod;
5159 break;
5160 case glslang::EOpRightShift:
5161 case glslang::EOpRightShiftAssign:
5162 if (isUnsigned)
5163 binOp = spv::OpShiftRightLogical;
5164 else
5165 binOp = spv::OpShiftRightArithmetic;
5166 break;
5167 case glslang::EOpLeftShift:
5168 case glslang::EOpLeftShiftAssign:
5169 binOp = spv::OpShiftLeftLogical;
5170 break;
5171 case glslang::EOpAnd:
5172 case glslang::EOpAndAssign:
5173 binOp = spv::OpBitwiseAnd;
5174 break;
5175 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005176 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005177 binOp = spv::OpLogicalAnd;
5178 break;
5179 case glslang::EOpInclusiveOr:
5180 case glslang::EOpInclusiveOrAssign:
5181 binOp = spv::OpBitwiseOr;
5182 break;
5183 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005184 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005185 binOp = spv::OpLogicalOr;
5186 break;
5187 case glslang::EOpExclusiveOr:
5188 case glslang::EOpExclusiveOrAssign:
5189 binOp = spv::OpBitwiseXor;
5190 break;
5191 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005192 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005193 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005194 break;
5195
5196 case glslang::EOpLessThan:
5197 case glslang::EOpGreaterThan:
5198 case glslang::EOpLessThanEqual:
5199 case glslang::EOpGreaterThanEqual:
5200 case glslang::EOpEqual:
5201 case glslang::EOpNotEqual:
5202 case glslang::EOpVectorEqual:
5203 case glslang::EOpVectorNotEqual:
5204 comparison = true;
5205 break;
5206 default:
5207 break;
5208 }
5209
John Kessenich7c1aa102015-10-15 13:29:11 -06005210 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005211 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005212 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005213 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5214 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005215 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005216
5217 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005218 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005219 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005220
qining25262b32016-05-06 17:25:16 -04005221 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005222 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005223 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005224 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005225 }
5226
5227 if (! comparison)
5228 return 0;
5229
John Kessenich7c1aa102015-10-15 13:29:11 -06005230 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005231
John Kessenich4583b612016-08-07 19:14:22 -06005232 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005233 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5234 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06005235 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005236 return result;
5237 }
John Kessenich140f3df2015-06-26 16:58:36 -06005238
5239 switch (op) {
5240 case glslang::EOpLessThan:
5241 if (isFloat)
5242 binOp = spv::OpFOrdLessThan;
5243 else if (isUnsigned)
5244 binOp = spv::OpULessThan;
5245 else
5246 binOp = spv::OpSLessThan;
5247 break;
5248 case glslang::EOpGreaterThan:
5249 if (isFloat)
5250 binOp = spv::OpFOrdGreaterThan;
5251 else if (isUnsigned)
5252 binOp = spv::OpUGreaterThan;
5253 else
5254 binOp = spv::OpSGreaterThan;
5255 break;
5256 case glslang::EOpLessThanEqual:
5257 if (isFloat)
5258 binOp = spv::OpFOrdLessThanEqual;
5259 else if (isUnsigned)
5260 binOp = spv::OpULessThanEqual;
5261 else
5262 binOp = spv::OpSLessThanEqual;
5263 break;
5264 case glslang::EOpGreaterThanEqual:
5265 if (isFloat)
5266 binOp = spv::OpFOrdGreaterThanEqual;
5267 else if (isUnsigned)
5268 binOp = spv::OpUGreaterThanEqual;
5269 else
5270 binOp = spv::OpSGreaterThanEqual;
5271 break;
5272 case glslang::EOpEqual:
5273 case glslang::EOpVectorEqual:
5274 if (isFloat)
5275 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005276 else if (isBool)
5277 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005278 else
5279 binOp = spv::OpIEqual;
5280 break;
5281 case glslang::EOpNotEqual:
5282 case glslang::EOpVectorNotEqual:
5283 if (isFloat)
5284 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005285 else if (isBool)
5286 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005287 else
5288 binOp = spv::OpINotEqual;
5289 break;
5290 default:
5291 break;
5292 }
5293
qining25262b32016-05-06 17:25:16 -04005294 if (binOp != spv::OpNop) {
5295 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005296 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005297 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005298 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005299 }
John Kessenich140f3df2015-06-26 16:58:36 -06005300
5301 return 0;
5302}
5303
John Kessenich04bb8a02015-12-12 12:28:14 -07005304//
5305// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5306// These can be any of:
5307//
5308// matrix * scalar
5309// scalar * matrix
5310// matrix * matrix linear algebraic
5311// matrix * vector
5312// vector * matrix
5313// matrix * matrix componentwise
5314// matrix op matrix op in {+, -, /}
5315// matrix op scalar op in {+, -, /}
5316// scalar op matrix op in {+, -, /}
5317//
John Kessenichead86222018-03-28 18:01:20 -06005318spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5319 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005320{
5321 bool firstClass = true;
5322
5323 // First, handle first-class matrix operations (* and matrix/scalar)
5324 switch (op) {
5325 case spv::OpFDiv:
5326 if (builder.isMatrix(left) && builder.isScalar(right)) {
5327 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005328 spv::Id resultType = builder.getTypeId(right);
5329 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005330 op = spv::OpMatrixTimesScalar;
5331 } else
5332 firstClass = false;
5333 break;
5334 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005335 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005336 std::swap(left, right);
5337 assert(builder.isScalar(right));
5338 break;
5339 case spv::OpVectorTimesMatrix:
5340 assert(builder.isVector(left));
5341 assert(builder.isMatrix(right));
5342 break;
5343 case spv::OpMatrixTimesVector:
5344 assert(builder.isMatrix(left));
5345 assert(builder.isVector(right));
5346 break;
5347 case spv::OpMatrixTimesMatrix:
5348 assert(builder.isMatrix(left));
5349 assert(builder.isMatrix(right));
5350 break;
5351 default:
5352 firstClass = false;
5353 break;
5354 }
5355
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005356 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5357 firstClass = true;
5358
qining25262b32016-05-06 17:25:16 -04005359 if (firstClass) {
5360 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005361 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005362 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005363 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005364 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005365
LoopDawg592860c2016-06-09 08:57:35 -06005366 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005367 // The result type of all of them is the same type as the (a) matrix operand.
5368 // The algorithm is to:
5369 // - break the matrix(es) into vectors
5370 // - smear any scalar to a vector
5371 // - do vector operations
5372 // - make a matrix out the vector results
5373 switch (op) {
5374 case spv::OpFAdd:
5375 case spv::OpFSub:
5376 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005377 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005378 case spv::OpFMul:
5379 {
5380 // one time set up...
5381 bool leftMat = builder.isMatrix(left);
5382 bool rightMat = builder.isMatrix(right);
5383 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5384 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5385 spv::Id scalarType = builder.getScalarTypeId(typeId);
5386 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5387 std::vector<spv::Id> results;
5388 spv::Id smearVec = spv::NoResult;
5389 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005390 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005391 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005392 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005393
5394 // do each vector op
5395 for (unsigned int c = 0; c < numCols; ++c) {
5396 std::vector<unsigned int> indexes;
5397 indexes.push_back(c);
5398 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5399 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005400 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005401 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005402 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005403 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005404 }
5405
5406 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005407 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005408 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005409 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005410 }
5411 default:
5412 assert(0);
5413 return spv::NoResult;
5414 }
5415}
5416
John Kessenichead86222018-03-28 18:01:20 -06005417spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005418 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005419{
5420 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005421 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005422 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005423 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5424 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005425
5426 switch (op) {
5427 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005428 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005429 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005430 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005431 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005432 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005433 unaryOp = spv::OpSNegate;
5434 break;
5435
5436 case glslang::EOpLogicalNot:
5437 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005438 unaryOp = spv::OpLogicalNot;
5439 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005440 case glslang::EOpBitwiseNot:
5441 unaryOp = spv::OpNot;
5442 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005443
John Kessenich140f3df2015-06-26 16:58:36 -06005444 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005445 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005446 break;
5447 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005448 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005449 break;
5450 case glslang::EOpTranspose:
5451 unaryOp = spv::OpTranspose;
5452 break;
5453
5454 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005455 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005456 break;
5457 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005458 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005459 break;
5460 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005461 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005462 break;
5463 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005464 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005465 break;
5466 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005467 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005468 break;
5469 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005470 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005471 break;
5472 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005473 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005474 break;
5475 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005476 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005477 break;
5478
5479 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005480 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005481 break;
5482 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005483 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005484 break;
5485 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005486 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005487 break;
5488 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005489 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005490 break;
5491 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005492 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005493 break;
5494 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005495 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005496 break;
5497
5498 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005499 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005500 break;
5501 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005502 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005503 break;
5504
5505 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005506 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005507 break;
5508 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005509 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005510 break;
5511 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005512 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005513 break;
5514 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005515 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005516 break;
5517 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005518 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005519 break;
5520 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005521 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005522 break;
5523
5524 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005525 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005526 break;
5527 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005528 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005529 break;
5530 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005531 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005532 break;
5533 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005534 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005535 break;
5536 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005537 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005538 break;
5539 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005540 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005541 break;
5542
5543 case glslang::EOpIsNan:
5544 unaryOp = spv::OpIsNan;
5545 break;
5546 case glslang::EOpIsInf:
5547 unaryOp = spv::OpIsInf;
5548 break;
LoopDawg592860c2016-06-09 08:57:35 -06005549 case glslang::EOpIsFinite:
5550 unaryOp = spv::OpIsFinite;
5551 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005552
Rex Xucbc426e2015-12-15 16:03:10 +08005553 case glslang::EOpFloatBitsToInt:
5554 case glslang::EOpFloatBitsToUint:
5555 case glslang::EOpIntBitsToFloat:
5556 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005557 case glslang::EOpDoubleBitsToInt64:
5558 case glslang::EOpDoubleBitsToUint64:
5559 case glslang::EOpInt64BitsToDouble:
5560 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005561 case glslang::EOpFloat16BitsToInt16:
5562 case glslang::EOpFloat16BitsToUint16:
5563 case glslang::EOpInt16BitsToFloat16:
5564 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005565 unaryOp = spv::OpBitcast;
5566 break;
5567
John Kessenich140f3df2015-06-26 16:58:36 -06005568 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005569 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005570 break;
5571 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005572 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005573 break;
5574 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005575 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005576 break;
5577 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005578 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005579 break;
5580 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005581 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005582 break;
5583 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005584 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005585 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005586 case glslang::EOpPackSnorm4x8:
5587 libCall = spv::GLSLstd450PackSnorm4x8;
5588 break;
5589 case glslang::EOpUnpackSnorm4x8:
5590 libCall = spv::GLSLstd450UnpackSnorm4x8;
5591 break;
5592 case glslang::EOpPackUnorm4x8:
5593 libCall = spv::GLSLstd450PackUnorm4x8;
5594 break;
5595 case glslang::EOpUnpackUnorm4x8:
5596 libCall = spv::GLSLstd450UnpackUnorm4x8;
5597 break;
5598 case glslang::EOpPackDouble2x32:
5599 libCall = spv::GLSLstd450PackDouble2x32;
5600 break;
5601 case glslang::EOpUnpackDouble2x32:
5602 libCall = spv::GLSLstd450UnpackDouble2x32;
5603 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005604
Rex Xu8ff43de2016-04-22 16:51:45 +08005605 case glslang::EOpPackInt2x32:
5606 case glslang::EOpUnpackInt2x32:
5607 case glslang::EOpPackUint2x32:
5608 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005609 case glslang::EOpPack16:
5610 case glslang::EOpPack32:
5611 case glslang::EOpPack64:
5612 case glslang::EOpUnpack32:
5613 case glslang::EOpUnpack16:
5614 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005615 case glslang::EOpPackInt2x16:
5616 case glslang::EOpUnpackInt2x16:
5617 case glslang::EOpPackUint2x16:
5618 case glslang::EOpUnpackUint2x16:
5619 case glslang::EOpPackInt4x16:
5620 case glslang::EOpUnpackInt4x16:
5621 case glslang::EOpPackUint4x16:
5622 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005623 case glslang::EOpPackFloat2x16:
5624 case glslang::EOpUnpackFloat2x16:
5625 unaryOp = spv::OpBitcast;
5626 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005627
John Kessenich140f3df2015-06-26 16:58:36 -06005628 case glslang::EOpDPdx:
5629 unaryOp = spv::OpDPdx;
5630 break;
5631 case glslang::EOpDPdy:
5632 unaryOp = spv::OpDPdy;
5633 break;
5634 case glslang::EOpFwidth:
5635 unaryOp = spv::OpFwidth;
5636 break;
5637 case glslang::EOpDPdxFine:
5638 unaryOp = spv::OpDPdxFine;
5639 break;
5640 case glslang::EOpDPdyFine:
5641 unaryOp = spv::OpDPdyFine;
5642 break;
5643 case glslang::EOpFwidthFine:
5644 unaryOp = spv::OpFwidthFine;
5645 break;
5646 case glslang::EOpDPdxCoarse:
5647 unaryOp = spv::OpDPdxCoarse;
5648 break;
5649 case glslang::EOpDPdyCoarse:
5650 unaryOp = spv::OpDPdyCoarse;
5651 break;
5652 case glslang::EOpFwidthCoarse:
5653 unaryOp = spv::OpFwidthCoarse;
5654 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005655 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005656#ifdef AMD_EXTENSIONS
5657 if (typeProxy == glslang::EbtFloat16)
5658 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5659#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005660 libCall = spv::GLSLstd450InterpolateAtCentroid;
5661 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005662 case glslang::EOpAny:
5663 unaryOp = spv::OpAny;
5664 break;
5665 case glslang::EOpAll:
5666 unaryOp = spv::OpAll;
5667 break;
5668
5669 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005670 if (isFloat)
5671 libCall = spv::GLSLstd450FAbs;
5672 else
5673 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005674 break;
5675 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005676 if (isFloat)
5677 libCall = spv::GLSLstd450FSign;
5678 else
5679 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005680 break;
5681
John Kessenichfc51d282015-08-19 13:34:18 -06005682 case glslang::EOpAtomicCounterIncrement:
5683 case glslang::EOpAtomicCounterDecrement:
5684 case glslang::EOpAtomicCounter:
5685 {
5686 // Handle all of the atomics in one place, in createAtomicOperation()
5687 std::vector<spv::Id> operands;
5688 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005689 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005690 }
5691
John Kessenichfc51d282015-08-19 13:34:18 -06005692 case glslang::EOpBitFieldReverse:
5693 unaryOp = spv::OpBitReverse;
5694 break;
5695 case glslang::EOpBitCount:
5696 unaryOp = spv::OpBitCount;
5697 break;
5698 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005699 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005700 break;
5701 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005702 if (isUnsigned)
5703 libCall = spv::GLSLstd450FindUMsb;
5704 else
5705 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005706 break;
5707
Rex Xu574ab042016-04-14 16:53:07 +08005708 case glslang::EOpBallot:
5709 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005710 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005711 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005712 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005713#ifdef AMD_EXTENSIONS
5714 case glslang::EOpMinInvocations:
5715 case glslang::EOpMaxInvocations:
5716 case glslang::EOpAddInvocations:
5717 case glslang::EOpMinInvocationsNonUniform:
5718 case glslang::EOpMaxInvocationsNonUniform:
5719 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005720 case glslang::EOpMinInvocationsInclusiveScan:
5721 case glslang::EOpMaxInvocationsInclusiveScan:
5722 case glslang::EOpAddInvocationsInclusiveScan:
5723 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5724 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5725 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5726 case glslang::EOpMinInvocationsExclusiveScan:
5727 case glslang::EOpMaxInvocationsExclusiveScan:
5728 case glslang::EOpAddInvocationsExclusiveScan:
5729 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5730 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5731 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005732#endif
Rex Xu51596642016-09-21 18:56:12 +08005733 {
5734 std::vector<spv::Id> operands;
5735 operands.push_back(operand);
5736 return createInvocationsOperation(op, typeId, operands, typeProxy);
5737 }
John Kessenich66011cb2018-03-06 16:12:04 -07005738 case glslang::EOpSubgroupAll:
5739 case glslang::EOpSubgroupAny:
5740 case glslang::EOpSubgroupAllEqual:
5741 case glslang::EOpSubgroupBroadcastFirst:
5742 case glslang::EOpSubgroupBallot:
5743 case glslang::EOpSubgroupInverseBallot:
5744 case glslang::EOpSubgroupBallotBitCount:
5745 case glslang::EOpSubgroupBallotInclusiveBitCount:
5746 case glslang::EOpSubgroupBallotExclusiveBitCount:
5747 case glslang::EOpSubgroupBallotFindLSB:
5748 case glslang::EOpSubgroupBallotFindMSB:
5749 case glslang::EOpSubgroupAdd:
5750 case glslang::EOpSubgroupMul:
5751 case glslang::EOpSubgroupMin:
5752 case glslang::EOpSubgroupMax:
5753 case glslang::EOpSubgroupAnd:
5754 case glslang::EOpSubgroupOr:
5755 case glslang::EOpSubgroupXor:
5756 case glslang::EOpSubgroupInclusiveAdd:
5757 case glslang::EOpSubgroupInclusiveMul:
5758 case glslang::EOpSubgroupInclusiveMin:
5759 case glslang::EOpSubgroupInclusiveMax:
5760 case glslang::EOpSubgroupInclusiveAnd:
5761 case glslang::EOpSubgroupInclusiveOr:
5762 case glslang::EOpSubgroupInclusiveXor:
5763 case glslang::EOpSubgroupExclusiveAdd:
5764 case glslang::EOpSubgroupExclusiveMul:
5765 case glslang::EOpSubgroupExclusiveMin:
5766 case glslang::EOpSubgroupExclusiveMax:
5767 case glslang::EOpSubgroupExclusiveAnd:
5768 case glslang::EOpSubgroupExclusiveOr:
5769 case glslang::EOpSubgroupExclusiveXor:
5770 case glslang::EOpSubgroupQuadSwapHorizontal:
5771 case glslang::EOpSubgroupQuadSwapVertical:
5772 case glslang::EOpSubgroupQuadSwapDiagonal: {
5773 std::vector<spv::Id> operands;
5774 operands.push_back(operand);
5775 return createSubgroupOperation(op, typeId, operands, typeProxy);
5776 }
Rex Xu9d93a232016-05-05 12:30:44 +08005777#ifdef AMD_EXTENSIONS
5778 case glslang::EOpMbcnt:
5779 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5780 libCall = spv::MbcntAMD;
5781 break;
5782
5783 case glslang::EOpCubeFaceIndex:
5784 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5785 libCall = spv::CubeFaceIndexAMD;
5786 break;
5787
5788 case glslang::EOpCubeFaceCoord:
5789 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5790 libCall = spv::CubeFaceCoordAMD;
5791 break;
5792#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005793#ifdef NV_EXTENSIONS
5794 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005795 unaryOp = spv::OpGroupNonUniformPartitionNV;
5796 break;
5797#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005798 case glslang::EOpConstructReference:
5799 unaryOp = spv::OpBitcast;
5800 break;
Jeff Bolz88220d52019-05-08 10:24:46 -05005801
5802 case glslang::EOpCopyObject:
5803 unaryOp = spv::OpCopyObject;
5804 break;
5805
John Kessenich140f3df2015-06-26 16:58:36 -06005806 default:
5807 return 0;
5808 }
5809
5810 spv::Id id;
5811 if (libCall >= 0) {
5812 std::vector<spv::Id> args;
5813 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005814 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005815 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005816 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005817 }
John Kessenich140f3df2015-06-26 16:58:36 -06005818
John Kessenichead86222018-03-28 18:01:20 -06005819 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005820 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005821 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005822}
5823
John Kessenich7a53f762016-01-20 11:19:27 -07005824// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005825spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5826 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005827{
5828 // Handle unary operations vector by vector.
5829 // The result type is the same type as the original type.
5830 // The algorithm is to:
5831 // - break the matrix into vectors
5832 // - apply the operation to each vector
5833 // - make a matrix out the vector results
5834
5835 // get the types sorted out
5836 int numCols = builder.getNumColumns(operand);
5837 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005838 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5839 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005840 std::vector<spv::Id> results;
5841
5842 // do each vector op
5843 for (int c = 0; c < numCols; ++c) {
5844 std::vector<unsigned int> indexes;
5845 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005846 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5847 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005848 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005849 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005850 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005851 }
5852
5853 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005854 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005855 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005856 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005857}
5858
John Kessenichad7645f2018-06-04 19:11:25 -06005859// For converting integers where both the bitwidth and the signedness could
5860// change, but only do the width change here. The caller is still responsible
5861// for the signedness conversion.
5862spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005863{
John Kessenichad7645f2018-06-04 19:11:25 -06005864 // Get the result type width, based on the type to convert to.
5865 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005866 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005867 case glslang::EOpConvInt16ToUint8:
5868 case glslang::EOpConvIntToUint8:
5869 case glslang::EOpConvInt64ToUint8:
5870 case glslang::EOpConvUint16ToInt8:
5871 case glslang::EOpConvUintToInt8:
5872 case glslang::EOpConvUint64ToInt8:
5873 width = 8;
5874 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005875 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005876 case glslang::EOpConvIntToUint16:
5877 case glslang::EOpConvInt64ToUint16:
5878 case glslang::EOpConvUint8ToInt16:
5879 case glslang::EOpConvUintToInt16:
5880 case glslang::EOpConvUint64ToInt16:
5881 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005882 break;
5883 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005884 case glslang::EOpConvInt16ToUint:
5885 case glslang::EOpConvInt64ToUint:
5886 case glslang::EOpConvUint8ToInt:
5887 case glslang::EOpConvUint16ToInt:
5888 case glslang::EOpConvUint64ToInt:
5889 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005890 break;
5891 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005892 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005893 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005894 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005895 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005896 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005897 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005898 break;
5899
5900 default:
5901 assert(false && "Default missing");
5902 break;
5903 }
5904
John Kessenichad7645f2018-06-04 19:11:25 -06005905 // Get the conversion operation and result type,
5906 // based on the target width, but the source type.
5907 spv::Id type = spv::NoType;
5908 spv::Op convOp = spv::OpNop;
5909 switch(op) {
5910 case glslang::EOpConvInt8ToUint16:
5911 case glslang::EOpConvInt8ToUint:
5912 case glslang::EOpConvInt8ToUint64:
5913 case glslang::EOpConvInt16ToUint8:
5914 case glslang::EOpConvInt16ToUint:
5915 case glslang::EOpConvInt16ToUint64:
5916 case glslang::EOpConvIntToUint8:
5917 case glslang::EOpConvIntToUint16:
5918 case glslang::EOpConvIntToUint64:
5919 case glslang::EOpConvInt64ToUint8:
5920 case glslang::EOpConvInt64ToUint16:
5921 case glslang::EOpConvInt64ToUint:
5922 convOp = spv::OpSConvert;
5923 type = builder.makeIntType(width);
5924 break;
5925 default:
5926 convOp = spv::OpUConvert;
5927 type = builder.makeUintType(width);
5928 break;
5929 }
5930
John Kessenich66011cb2018-03-06 16:12:04 -07005931 if (vectorSize > 0)
5932 type = builder.makeVectorType(type, vectorSize);
5933
John Kessenichad7645f2018-06-04 19:11:25 -06005934 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005935}
5936
John Kessenichead86222018-03-28 18:01:20 -06005937spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5938 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005939{
5940 spv::Op convOp = spv::OpNop;
5941 spv::Id zero = 0;
5942 spv::Id one = 0;
5943
5944 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5945
5946 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005947 case glslang::EOpConvInt8ToBool:
5948 case glslang::EOpConvUint8ToBool:
5949 zero = builder.makeUint8Constant(0);
5950 zero = makeSmearedConstant(zero, vectorSize);
5951 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005952 case glslang::EOpConvInt16ToBool:
5953 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005954 zero = builder.makeUint16Constant(0);
5955 zero = makeSmearedConstant(zero, vectorSize);
5956 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5957 case glslang::EOpConvIntToBool:
5958 case glslang::EOpConvUintToBool:
5959 zero = builder.makeUintConstant(0);
5960 zero = makeSmearedConstant(zero, vectorSize);
5961 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5962 case glslang::EOpConvInt64ToBool:
5963 case glslang::EOpConvUint64ToBool:
5964 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005965 zero = makeSmearedConstant(zero, vectorSize);
5966 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5967
5968 case glslang::EOpConvFloatToBool:
5969 zero = builder.makeFloatConstant(0.0F);
5970 zero = makeSmearedConstant(zero, vectorSize);
5971 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5972
5973 case glslang::EOpConvDoubleToBool:
5974 zero = builder.makeDoubleConstant(0.0);
5975 zero = makeSmearedConstant(zero, vectorSize);
5976 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5977
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005978 case glslang::EOpConvFloat16ToBool:
5979 zero = builder.makeFloat16Constant(0.0F);
5980 zero = makeSmearedConstant(zero, vectorSize);
5981 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005982
John Kessenich140f3df2015-06-26 16:58:36 -06005983 case glslang::EOpConvBoolToFloat:
5984 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005985 zero = builder.makeFloatConstant(0.0F);
5986 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005987 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005988
John Kessenich140f3df2015-06-26 16:58:36 -06005989 case glslang::EOpConvBoolToDouble:
5990 convOp = spv::OpSelect;
5991 zero = builder.makeDoubleConstant(0.0);
5992 one = builder.makeDoubleConstant(1.0);
5993 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005994
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005995 case glslang::EOpConvBoolToFloat16:
5996 convOp = spv::OpSelect;
5997 zero = builder.makeFloat16Constant(0.0F);
5998 one = builder.makeFloat16Constant(1.0F);
5999 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006000
6001 case glslang::EOpConvBoolToInt8:
6002 zero = builder.makeInt8Constant(0);
6003 one = builder.makeInt8Constant(1);
6004 convOp = spv::OpSelect;
6005 break;
6006
6007 case glslang::EOpConvBoolToUint8:
6008 zero = builder.makeUint8Constant(0);
6009 one = builder.makeUint8Constant(1);
6010 convOp = spv::OpSelect;
6011 break;
6012
6013 case glslang::EOpConvBoolToInt16:
6014 zero = builder.makeInt16Constant(0);
6015 one = builder.makeInt16Constant(1);
6016 convOp = spv::OpSelect;
6017 break;
6018
6019 case glslang::EOpConvBoolToUint16:
6020 zero = builder.makeUint16Constant(0);
6021 one = builder.makeUint16Constant(1);
6022 convOp = spv::OpSelect;
6023 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006024
John Kessenich140f3df2015-06-26 16:58:36 -06006025 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006026 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006027 if (op == glslang::EOpConvBoolToInt64)
6028 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006029 else
6030 zero = builder.makeIntConstant(0);
6031
6032 if (op == glslang::EOpConvBoolToInt64)
6033 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08006034 else
6035 one = builder.makeIntConstant(1);
6036
John Kessenich140f3df2015-06-26 16:58:36 -06006037 convOp = spv::OpSelect;
6038 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006039
John Kessenich140f3df2015-06-26 16:58:36 -06006040 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006041 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08006042 if (op == glslang::EOpConvBoolToUint64)
6043 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006044 else
6045 zero = builder.makeUintConstant(0);
6046
6047 if (op == glslang::EOpConvBoolToUint64)
6048 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08006049 else
6050 one = builder.makeUintConstant(1);
6051
John Kessenich140f3df2015-06-26 16:58:36 -06006052 convOp = spv::OpSelect;
6053 break;
6054
John Kessenich66011cb2018-03-06 16:12:04 -07006055 case glslang::EOpConvInt8ToFloat16:
6056 case glslang::EOpConvInt8ToFloat:
6057 case glslang::EOpConvInt8ToDouble:
6058 case glslang::EOpConvInt16ToFloat16:
6059 case glslang::EOpConvInt16ToFloat:
6060 case glslang::EOpConvInt16ToDouble:
6061 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006062 case glslang::EOpConvIntToFloat:
6063 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006064 case glslang::EOpConvInt64ToFloat:
6065 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006066 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006067 convOp = spv::OpConvertSToF;
6068 break;
6069
John Kessenich66011cb2018-03-06 16:12:04 -07006070 case glslang::EOpConvUint8ToFloat16:
6071 case glslang::EOpConvUint8ToFloat:
6072 case glslang::EOpConvUint8ToDouble:
6073 case glslang::EOpConvUint16ToFloat16:
6074 case glslang::EOpConvUint16ToFloat:
6075 case glslang::EOpConvUint16ToDouble:
6076 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006077 case glslang::EOpConvUintToFloat:
6078 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006079 case glslang::EOpConvUint64ToFloat:
6080 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006081 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006082 convOp = spv::OpConvertUToF;
6083 break;
6084
6085 case glslang::EOpConvDoubleToFloat:
6086 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006087 case glslang::EOpConvDoubleToFloat16:
6088 case glslang::EOpConvFloat16ToDouble:
6089 case glslang::EOpConvFloatToFloat16:
6090 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06006091 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08006092 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06006093 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06006094 break;
6095
John Kessenich66011cb2018-03-06 16:12:04 -07006096 case glslang::EOpConvFloat16ToInt8:
6097 case glslang::EOpConvFloatToInt8:
6098 case glslang::EOpConvDoubleToInt8:
6099 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006100 case glslang::EOpConvFloatToInt16:
6101 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006102 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006103 case glslang::EOpConvFloatToInt:
6104 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006105 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006106 case glslang::EOpConvFloatToInt64:
6107 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006108 convOp = spv::OpConvertFToS;
6109 break;
6110
John Kessenich66011cb2018-03-06 16:12:04 -07006111 case glslang::EOpConvUint8ToInt8:
6112 case glslang::EOpConvInt8ToUint8:
6113 case glslang::EOpConvUint16ToInt16:
6114 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006115 case glslang::EOpConvUintToInt:
6116 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006117 case glslang::EOpConvUint64ToInt64:
6118 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006119 if (builder.isInSpecConstCodeGenMode()) {
6120 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006121 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6122 zero = builder.makeUint8Constant(0);
6123 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006124 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006125 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6126 zero = builder.makeUint64Constant(0);
6127 } else {
Rex Xucabbb782017-03-24 13:41:14 +08006128 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006129 }
qining189b2032016-04-12 23:16:20 -04006130 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006131 // Use OpIAdd, instead of OpBitcast to do the conversion when
6132 // generating for OpSpecConstantOp instruction.
6133 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6134 }
6135 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006136 convOp = spv::OpBitcast;
6137 break;
6138
John Kessenich66011cb2018-03-06 16:12:04 -07006139 case glslang::EOpConvFloat16ToUint8:
6140 case glslang::EOpConvFloatToUint8:
6141 case glslang::EOpConvDoubleToUint8:
6142 case glslang::EOpConvFloat16ToUint16:
6143 case glslang::EOpConvFloatToUint16:
6144 case glslang::EOpConvDoubleToUint16:
6145 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006146 case glslang::EOpConvFloatToUint:
6147 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006148 case glslang::EOpConvFloatToUint64:
6149 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006150 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006151 convOp = spv::OpConvertFToU;
6152 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006153
John Kessenich66011cb2018-03-06 16:12:04 -07006154 case glslang::EOpConvInt8ToInt16:
6155 case glslang::EOpConvInt8ToInt:
6156 case glslang::EOpConvInt8ToInt64:
6157 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006158 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006159 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006160 case glslang::EOpConvIntToInt8:
6161 case glslang::EOpConvIntToInt16:
6162 case glslang::EOpConvIntToInt64:
6163 case glslang::EOpConvInt64ToInt8:
6164 case glslang::EOpConvInt64ToInt16:
6165 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006166 convOp = spv::OpSConvert;
6167 break;
6168
John Kessenich66011cb2018-03-06 16:12:04 -07006169 case glslang::EOpConvUint8ToUint16:
6170 case glslang::EOpConvUint8ToUint:
6171 case glslang::EOpConvUint8ToUint64:
6172 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006173 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006174 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006175 case glslang::EOpConvUintToUint8:
6176 case glslang::EOpConvUintToUint16:
6177 case glslang::EOpConvUintToUint64:
6178 case glslang::EOpConvUint64ToUint8:
6179 case glslang::EOpConvUint64ToUint16:
6180 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006181 convOp = spv::OpUConvert;
6182 break;
6183
John Kessenich66011cb2018-03-06 16:12:04 -07006184 case glslang::EOpConvInt8ToUint16:
6185 case glslang::EOpConvInt8ToUint:
6186 case glslang::EOpConvInt8ToUint64:
6187 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006188 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006189 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006190 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006191 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006192 case glslang::EOpConvIntToUint64:
6193 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006194 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006195 case glslang::EOpConvInt64ToUint:
6196 case glslang::EOpConvUint8ToInt16:
6197 case glslang::EOpConvUint8ToInt:
6198 case glslang::EOpConvUint8ToInt64:
6199 case glslang::EOpConvUint16ToInt8:
6200 case glslang::EOpConvUint16ToInt:
6201 case glslang::EOpConvUint16ToInt64:
6202 case glslang::EOpConvUintToInt8:
6203 case glslang::EOpConvUintToInt16:
6204 case glslang::EOpConvUintToInt64:
6205 case glslang::EOpConvUint64ToInt8:
6206 case glslang::EOpConvUint64ToInt16:
6207 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006208 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006209 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006210
6211 if (builder.isInSpecConstCodeGenMode()) {
6212 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006213 switch(op) {
6214 case glslang::EOpConvInt16ToUint8:
6215 case glslang::EOpConvIntToUint8:
6216 case glslang::EOpConvInt64ToUint8:
6217 case glslang::EOpConvUint16ToInt8:
6218 case glslang::EOpConvUintToInt8:
6219 case glslang::EOpConvUint64ToInt8:
6220 zero = builder.makeUint8Constant(0);
6221 break;
6222 case glslang::EOpConvInt8ToUint16:
6223 case glslang::EOpConvIntToUint16:
6224 case glslang::EOpConvInt64ToUint16:
6225 case glslang::EOpConvUint8ToInt16:
6226 case glslang::EOpConvUintToInt16:
6227 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006228 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006229 break;
6230 case glslang::EOpConvInt8ToUint:
6231 case glslang::EOpConvInt16ToUint:
6232 case glslang::EOpConvInt64ToUint:
6233 case glslang::EOpConvUint8ToInt:
6234 case glslang::EOpConvUint16ToInt:
6235 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006236 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006237 break;
6238 case glslang::EOpConvInt8ToUint64:
6239 case glslang::EOpConvInt16ToUint64:
6240 case glslang::EOpConvIntToUint64:
6241 case glslang::EOpConvUint8ToInt64:
6242 case glslang::EOpConvUint16ToInt64:
6243 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006244 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006245 break;
6246 default:
6247 assert(false && "Default missing");
6248 break;
6249 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006250 zero = makeSmearedConstant(zero, vectorSize);
6251 // Use OpIAdd, instead of OpBitcast to do the conversion when
6252 // generating for OpSpecConstantOp instruction.
6253 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6254 }
6255 // For normal run-time conversion instruction, use OpBitcast.
6256 convOp = spv::OpBitcast;
6257 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006258 case glslang::EOpConvUint64ToPtr:
6259 convOp = spv::OpConvertUToPtr;
6260 break;
6261 case glslang::EOpConvPtrToUint64:
6262 convOp = spv::OpConvertPtrToU;
6263 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006264 default:
6265 break;
6266 }
6267
6268 spv::Id result = 0;
6269 if (convOp == spv::OpNop)
6270 return result;
6271
6272 if (convOp == spv::OpSelect) {
6273 zero = makeSmearedConstant(zero, vectorSize);
6274 one = makeSmearedConstant(one, vectorSize);
6275 result = builder.createTriOp(convOp, destType, operand, one, zero);
6276 } else
6277 result = builder.createUnaryOp(convOp, destType, operand);
6278
John Kessenichead86222018-03-28 18:01:20 -06006279 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006280 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006281 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006282}
6283
6284spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6285{
6286 if (vectorSize == 0)
6287 return constant;
6288
6289 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6290 std::vector<spv::Id> components;
6291 for (int c = 0; c < vectorSize; ++c)
6292 components.push_back(constant);
6293 return builder.makeCompositeConstant(vectorTypeId, components);
6294}
6295
John Kessenich426394d2015-07-23 10:22:48 -06006296// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006297spv::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 -06006298{
6299 spv::Op opCode = spv::OpNop;
6300
6301 switch (op) {
6302 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006303 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006304 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006305 opCode = spv::OpAtomicIAdd;
6306 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006307 case glslang::EOpAtomicCounterSubtract:
6308 opCode = spv::OpAtomicISub;
6309 break;
John Kessenich426394d2015-07-23 10:22:48 -06006310 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006311 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006312 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006313 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006314 break;
6315 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006316 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006317 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006318 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006319 break;
6320 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006321 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006322 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006323 opCode = spv::OpAtomicAnd;
6324 break;
6325 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006326 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006327 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006328 opCode = spv::OpAtomicOr;
6329 break;
6330 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006331 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006332 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006333 opCode = spv::OpAtomicXor;
6334 break;
6335 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006336 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006337 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006338 opCode = spv::OpAtomicExchange;
6339 break;
6340 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006341 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006342 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006343 opCode = spv::OpAtomicCompareExchange;
6344 break;
6345 case glslang::EOpAtomicCounterIncrement:
6346 opCode = spv::OpAtomicIIncrement;
6347 break;
6348 case glslang::EOpAtomicCounterDecrement:
6349 opCode = spv::OpAtomicIDecrement;
6350 break;
6351 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006352 case glslang::EOpImageAtomicLoad:
6353 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006354 opCode = spv::OpAtomicLoad;
6355 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006356 case glslang::EOpAtomicStore:
6357 case glslang::EOpImageAtomicStore:
6358 opCode = spv::OpAtomicStore;
6359 break;
John Kessenich426394d2015-07-23 10:22:48 -06006360 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006361 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006362 break;
6363 }
6364
Rex Xue8fe8b02017-09-26 15:42:56 +08006365 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6366 builder.addCapability(spv::CapabilityInt64Atomics);
6367
John Kessenich426394d2015-07-23 10:22:48 -06006368 // Sort out the operands
6369 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006370 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006371 // - compare-exchange swaps the value and comparator
6372 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006373 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006374 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6375 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6376 spv::Id scopeId;
6377 if (glslangIntermediate->usingVulkanMemoryModel()) {
6378 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6379 } else {
6380 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6381 }
6382 // semantics default to relaxed
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006383 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.volatil ? spv::MemorySemanticsVolatileMask : spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006384 spv::Id semanticsId2 = semanticsId;
6385
6386 pointerId = operands[0];
6387 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6388 // no additional operands
6389 } else if (opCode == spv::OpAtomicCompareExchange) {
6390 compareId = operands[1];
6391 valueId = operands[2];
6392 if (operands.size() > 3) {
6393 scopeId = operands[3];
6394 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6395 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6396 }
6397 } else if (opCode == spv::OpAtomicLoad) {
6398 if (operands.size() > 1) {
6399 scopeId = operands[1];
6400 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6401 }
6402 } else {
6403 // atomic store or RMW
6404 valueId = operands[1];
6405 if (operands.size() > 2) {
6406 scopeId = operands[2];
6407 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6408 }
Rex Xu04db3f52015-09-16 11:44:02 +08006409 }
John Kessenich426394d2015-07-23 10:22:48 -06006410
Jeff Bolz36831c92018-09-05 10:11:41 -05006411 // Check for capabilities
6412 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006413 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6414 spv::MemorySemanticsMakeVisibleKHRMask |
6415 spv::MemorySemanticsOutputMemoryKHRMask |
6416 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006417 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6418 }
John Kessenich426394d2015-07-23 10:22:48 -06006419
Jeff Bolz36831c92018-09-05 10:11:41 -05006420 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6421 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6422 }
John Kessenich48d6e792017-10-06 21:21:48 -06006423
Jeff Bolz36831c92018-09-05 10:11:41 -05006424 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6425 spvAtomicOperands.push_back(pointerId);
6426 spvAtomicOperands.push_back(scopeId);
6427 spvAtomicOperands.push_back(semanticsId);
6428 if (opCode == spv::OpAtomicCompareExchange) {
6429 spvAtomicOperands.push_back(semanticsId2);
6430 spvAtomicOperands.push_back(valueId);
6431 spvAtomicOperands.push_back(compareId);
6432 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6433 spvAtomicOperands.push_back(valueId);
6434 }
John Kessenich48d6e792017-10-06 21:21:48 -06006435
Jeff Bolz36831c92018-09-05 10:11:41 -05006436 if (opCode == spv::OpAtomicStore) {
6437 builder.createNoResultOp(opCode, spvAtomicOperands);
6438 return 0;
6439 } else {
6440 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6441
6442 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6443 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6444 if (op == glslang::EOpAtomicCounterDecrement)
6445 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6446
6447 return resultId;
6448 }
John Kessenich426394d2015-07-23 10:22:48 -06006449}
6450
John Kessenich91cef522016-05-05 16:45:40 -06006451// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006452spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006453{
Corentin Walleze7061422018-08-08 15:20:15 +02006454#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006455 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6456 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006457#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006458
Rex Xu51596642016-09-21 18:56:12 +08006459 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006460 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006461 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6462
chaocf200da82016-12-20 12:44:35 -08006463 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6464 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006465 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6466 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006467 } else if (op == glslang::EOpAnyInvocation ||
6468 op == glslang::EOpAllInvocations ||
6469 op == glslang::EOpAllInvocationsEqual) {
6470 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6471 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006472 } else {
6473 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006474#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006475 if (op == glslang::EOpMinInvocationsNonUniform ||
6476 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006477 op == glslang::EOpAddInvocationsNonUniform ||
6478 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6479 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6480 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6481 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6482 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6483 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006484 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006485#endif
Rex Xu51596642016-09-21 18:56:12 +08006486
Rex Xu9d93a232016-05-05 12:30:44 +08006487#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006488 switch (op) {
6489 case glslang::EOpMinInvocations:
6490 case glslang::EOpMaxInvocations:
6491 case glslang::EOpAddInvocations:
6492 case glslang::EOpMinInvocationsNonUniform:
6493 case glslang::EOpMaxInvocationsNonUniform:
6494 case glslang::EOpAddInvocationsNonUniform:
6495 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006496 break;
6497 case glslang::EOpMinInvocationsInclusiveScan:
6498 case glslang::EOpMaxInvocationsInclusiveScan:
6499 case glslang::EOpAddInvocationsInclusiveScan:
6500 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6501 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6502 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6503 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006504 break;
6505 case glslang::EOpMinInvocationsExclusiveScan:
6506 case glslang::EOpMaxInvocationsExclusiveScan:
6507 case glslang::EOpAddInvocationsExclusiveScan:
6508 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6509 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6510 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6511 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006512 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006513 default:
6514 break;
Rex Xu430ef402016-10-14 17:22:23 +08006515 }
John Kessenich149afc32018-08-14 13:31:43 -06006516 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6517 spvGroupOperands.push_back(scope);
6518 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006519 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006520 spvGroupOperands.push_back(groupOp);
6521 }
Rex Xu9d93a232016-05-05 12:30:44 +08006522#endif
Rex Xu51596642016-09-21 18:56:12 +08006523 }
6524
John Kessenich149afc32018-08-14 13:31:43 -06006525 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6526 spv::IdImmediate op = { true, *opIt };
6527 spvGroupOperands.push_back(op);
6528 }
John Kessenich91cef522016-05-05 16:45:40 -06006529
6530 switch (op) {
6531 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006532 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006533 break;
John Kessenich91cef522016-05-05 16:45:40 -06006534 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006535 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006536 break;
John Kessenich91cef522016-05-05 16:45:40 -06006537 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006538 opCode = spv::OpSubgroupAllEqualKHR;
6539 break;
Rex Xu51596642016-09-21 18:56:12 +08006540 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006541 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006542 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006543 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006544 break;
6545 case glslang::EOpReadFirstInvocation:
6546 opCode = spv::OpSubgroupFirstInvocationKHR;
6547 break;
6548 case glslang::EOpBallot:
6549 {
6550 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6551 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6552 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6553 //
6554 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6555 //
6556 spv::Id uintType = builder.makeUintType(32);
6557 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6558 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6559
6560 std::vector<spv::Id> components;
6561 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6562 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6563
6564 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6565 return builder.createUnaryOp(spv::OpBitcast, typeId,
6566 builder.createCompositeConstruct(uvec2Type, components));
6567 }
6568
Rex Xu9d93a232016-05-05 12:30:44 +08006569#ifdef AMD_EXTENSIONS
6570 case glslang::EOpMinInvocations:
6571 case glslang::EOpMaxInvocations:
6572 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006573 case glslang::EOpMinInvocationsInclusiveScan:
6574 case glslang::EOpMaxInvocationsInclusiveScan:
6575 case glslang::EOpAddInvocationsInclusiveScan:
6576 case glslang::EOpMinInvocationsExclusiveScan:
6577 case glslang::EOpMaxInvocationsExclusiveScan:
6578 case glslang::EOpAddInvocationsExclusiveScan:
6579 if (op == glslang::EOpMinInvocations ||
6580 op == glslang::EOpMinInvocationsInclusiveScan ||
6581 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006582 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006583 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006584 else {
6585 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006586 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006587 else
Rex Xu51596642016-09-21 18:56:12 +08006588 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006589 }
Rex Xu430ef402016-10-14 17:22:23 +08006590 } else if (op == glslang::EOpMaxInvocations ||
6591 op == glslang::EOpMaxInvocationsInclusiveScan ||
6592 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006593 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006594 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006595 else {
6596 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006597 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006598 else
Rex Xu51596642016-09-21 18:56:12 +08006599 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006600 }
6601 } else {
6602 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006603 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006604 else
Rex Xu51596642016-09-21 18:56:12 +08006605 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006606 }
6607
Rex Xu2bbbe062016-08-23 15:41:05 +08006608 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006609 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006610
6611 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006612 case glslang::EOpMinInvocationsNonUniform:
6613 case glslang::EOpMaxInvocationsNonUniform:
6614 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006615 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6616 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6617 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6618 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6619 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6620 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6621 if (op == glslang::EOpMinInvocationsNonUniform ||
6622 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6623 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006624 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006625 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006626 else {
6627 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006628 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006629 else
Rex Xu51596642016-09-21 18:56:12 +08006630 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006631 }
6632 }
Rex Xu430ef402016-10-14 17:22:23 +08006633 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6634 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6635 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006636 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006637 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006638 else {
6639 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006640 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006641 else
Rex Xu51596642016-09-21 18:56:12 +08006642 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006643 }
6644 }
6645 else {
6646 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006647 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006648 else
Rex Xu51596642016-09-21 18:56:12 +08006649 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006650 }
6651
Rex Xu2bbbe062016-08-23 15:41:05 +08006652 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006653 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006654
6655 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006656#endif
John Kessenich91cef522016-05-05 16:45:40 -06006657 default:
6658 logger->missingFunctionality("invocation operation");
6659 return spv::NoResult;
6660 }
Rex Xu51596642016-09-21 18:56:12 +08006661
6662 assert(opCode != spv::OpNop);
6663 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006664}
6665
Rex Xu2bbbe062016-08-23 15:41:05 +08006666// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006667spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6668 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006669{
Rex Xub7072052016-09-26 15:53:40 +08006670#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006671 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6672 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006673 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006674 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006675 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6676 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6677 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006678#else
6679 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6680 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006681 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6682 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006683#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006684
6685 // Handle group invocation operations scalar by scalar.
6686 // The result type is the same type as the original type.
6687 // The algorithm is to:
6688 // - break the vector into scalars
6689 // - apply the operation to each scalar
6690 // - make a vector out the scalar results
6691
6692 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006693 int numComponents = builder.getNumComponents(operands[0]);
6694 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006695 std::vector<spv::Id> results;
6696
6697 // do each scalar op
6698 for (int comp = 0; comp < numComponents; ++comp) {
6699 std::vector<unsigned int> indexes;
6700 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006701 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6702 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006703 if (op == spv::OpSubgroupReadInvocationKHR) {
6704 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006705 spv::IdImmediate operand = { true, operands[1] };
6706 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006707 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006708 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6709 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006710 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006711 spv::IdImmediate operand = { true, operands[1] };
6712 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006713 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006714 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6715 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006716 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006717 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006718 spvGroupOperands.push_back(scalar);
6719 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006720
Rex Xub7072052016-09-26 15:53:40 +08006721 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006722 }
6723
6724 // put the pieces together
6725 return builder.createCompositeConstruct(typeId, results);
6726}
Rex Xu2bbbe062016-08-23 15:41:05 +08006727
John Kessenich66011cb2018-03-06 16:12:04 -07006728// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006729spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6730 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006731{
6732 // Add the required capabilities.
6733 switch (op) {
6734 case glslang::EOpSubgroupElect:
6735 builder.addCapability(spv::CapabilityGroupNonUniform);
6736 break;
6737 case glslang::EOpSubgroupAll:
6738 case glslang::EOpSubgroupAny:
6739 case glslang::EOpSubgroupAllEqual:
6740 builder.addCapability(spv::CapabilityGroupNonUniform);
6741 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6742 break;
6743 case glslang::EOpSubgroupBroadcast:
6744 case glslang::EOpSubgroupBroadcastFirst:
6745 case glslang::EOpSubgroupBallot:
6746 case glslang::EOpSubgroupInverseBallot:
6747 case glslang::EOpSubgroupBallotBitExtract:
6748 case glslang::EOpSubgroupBallotBitCount:
6749 case glslang::EOpSubgroupBallotInclusiveBitCount:
6750 case glslang::EOpSubgroupBallotExclusiveBitCount:
6751 case glslang::EOpSubgroupBallotFindLSB:
6752 case glslang::EOpSubgroupBallotFindMSB:
6753 builder.addCapability(spv::CapabilityGroupNonUniform);
6754 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6755 break;
6756 case glslang::EOpSubgroupShuffle:
6757 case glslang::EOpSubgroupShuffleXor:
6758 builder.addCapability(spv::CapabilityGroupNonUniform);
6759 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6760 break;
6761 case glslang::EOpSubgroupShuffleUp:
6762 case glslang::EOpSubgroupShuffleDown:
6763 builder.addCapability(spv::CapabilityGroupNonUniform);
6764 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6765 break;
6766 case glslang::EOpSubgroupAdd:
6767 case glslang::EOpSubgroupMul:
6768 case glslang::EOpSubgroupMin:
6769 case glslang::EOpSubgroupMax:
6770 case glslang::EOpSubgroupAnd:
6771 case glslang::EOpSubgroupOr:
6772 case glslang::EOpSubgroupXor:
6773 case glslang::EOpSubgroupInclusiveAdd:
6774 case glslang::EOpSubgroupInclusiveMul:
6775 case glslang::EOpSubgroupInclusiveMin:
6776 case glslang::EOpSubgroupInclusiveMax:
6777 case glslang::EOpSubgroupInclusiveAnd:
6778 case glslang::EOpSubgroupInclusiveOr:
6779 case glslang::EOpSubgroupInclusiveXor:
6780 case glslang::EOpSubgroupExclusiveAdd:
6781 case glslang::EOpSubgroupExclusiveMul:
6782 case glslang::EOpSubgroupExclusiveMin:
6783 case glslang::EOpSubgroupExclusiveMax:
6784 case glslang::EOpSubgroupExclusiveAnd:
6785 case glslang::EOpSubgroupExclusiveOr:
6786 case glslang::EOpSubgroupExclusiveXor:
6787 builder.addCapability(spv::CapabilityGroupNonUniform);
6788 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6789 break;
6790 case glslang::EOpSubgroupClusteredAdd:
6791 case glslang::EOpSubgroupClusteredMul:
6792 case glslang::EOpSubgroupClusteredMin:
6793 case glslang::EOpSubgroupClusteredMax:
6794 case glslang::EOpSubgroupClusteredAnd:
6795 case glslang::EOpSubgroupClusteredOr:
6796 case glslang::EOpSubgroupClusteredXor:
6797 builder.addCapability(spv::CapabilityGroupNonUniform);
6798 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6799 break;
6800 case glslang::EOpSubgroupQuadBroadcast:
6801 case glslang::EOpSubgroupQuadSwapHorizontal:
6802 case glslang::EOpSubgroupQuadSwapVertical:
6803 case glslang::EOpSubgroupQuadSwapDiagonal:
6804 builder.addCapability(spv::CapabilityGroupNonUniform);
6805 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6806 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006807#ifdef NV_EXTENSIONS
6808 case glslang::EOpSubgroupPartitionedAdd:
6809 case glslang::EOpSubgroupPartitionedMul:
6810 case glslang::EOpSubgroupPartitionedMin:
6811 case glslang::EOpSubgroupPartitionedMax:
6812 case glslang::EOpSubgroupPartitionedAnd:
6813 case glslang::EOpSubgroupPartitionedOr:
6814 case glslang::EOpSubgroupPartitionedXor:
6815 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6816 case glslang::EOpSubgroupPartitionedInclusiveMul:
6817 case glslang::EOpSubgroupPartitionedInclusiveMin:
6818 case glslang::EOpSubgroupPartitionedInclusiveMax:
6819 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6820 case glslang::EOpSubgroupPartitionedInclusiveOr:
6821 case glslang::EOpSubgroupPartitionedInclusiveXor:
6822 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6823 case glslang::EOpSubgroupPartitionedExclusiveMul:
6824 case glslang::EOpSubgroupPartitionedExclusiveMin:
6825 case glslang::EOpSubgroupPartitionedExclusiveMax:
6826 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6827 case glslang::EOpSubgroupPartitionedExclusiveOr:
6828 case glslang::EOpSubgroupPartitionedExclusiveXor:
6829 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6830 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6831 break;
6832#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006833 default: assert(0 && "Unhandled subgroup operation!");
6834 }
6835
6836 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6837 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6838 const bool isBool = typeProxy == glslang::EbtBool;
6839
6840 spv::Op opCode = spv::OpNop;
6841
6842 // Figure out which opcode to use.
6843 switch (op) {
6844 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6845 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6846 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6847 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6848 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6849 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6850 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6851 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6852 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6853 case glslang::EOpSubgroupBallotBitCount:
6854 case glslang::EOpSubgroupBallotInclusiveBitCount:
6855 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6856 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6857 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6858 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6859 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6860 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6861 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6862 case glslang::EOpSubgroupAdd:
6863 case glslang::EOpSubgroupInclusiveAdd:
6864 case glslang::EOpSubgroupExclusiveAdd:
6865 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006866#ifdef NV_EXTENSIONS
6867 case glslang::EOpSubgroupPartitionedAdd:
6868 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6869 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6870#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006871 if (isFloat) {
6872 opCode = spv::OpGroupNonUniformFAdd;
6873 } else {
6874 opCode = spv::OpGroupNonUniformIAdd;
6875 }
6876 break;
6877 case glslang::EOpSubgroupMul:
6878 case glslang::EOpSubgroupInclusiveMul:
6879 case glslang::EOpSubgroupExclusiveMul:
6880 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006881#ifdef NV_EXTENSIONS
6882 case glslang::EOpSubgroupPartitionedMul:
6883 case glslang::EOpSubgroupPartitionedInclusiveMul:
6884 case glslang::EOpSubgroupPartitionedExclusiveMul:
6885#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006886 if (isFloat) {
6887 opCode = spv::OpGroupNonUniformFMul;
6888 } else {
6889 opCode = spv::OpGroupNonUniformIMul;
6890 }
6891 break;
6892 case glslang::EOpSubgroupMin:
6893 case glslang::EOpSubgroupInclusiveMin:
6894 case glslang::EOpSubgroupExclusiveMin:
6895 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006896#ifdef NV_EXTENSIONS
6897 case glslang::EOpSubgroupPartitionedMin:
6898 case glslang::EOpSubgroupPartitionedInclusiveMin:
6899 case glslang::EOpSubgroupPartitionedExclusiveMin:
6900#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006901 if (isFloat) {
6902 opCode = spv::OpGroupNonUniformFMin;
6903 } else if (isUnsigned) {
6904 opCode = spv::OpGroupNonUniformUMin;
6905 } else {
6906 opCode = spv::OpGroupNonUniformSMin;
6907 }
6908 break;
6909 case glslang::EOpSubgroupMax:
6910 case glslang::EOpSubgroupInclusiveMax:
6911 case glslang::EOpSubgroupExclusiveMax:
6912 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006913#ifdef NV_EXTENSIONS
6914 case glslang::EOpSubgroupPartitionedMax:
6915 case glslang::EOpSubgroupPartitionedInclusiveMax:
6916 case glslang::EOpSubgroupPartitionedExclusiveMax:
6917#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006918 if (isFloat) {
6919 opCode = spv::OpGroupNonUniformFMax;
6920 } else if (isUnsigned) {
6921 opCode = spv::OpGroupNonUniformUMax;
6922 } else {
6923 opCode = spv::OpGroupNonUniformSMax;
6924 }
6925 break;
6926 case glslang::EOpSubgroupAnd:
6927 case glslang::EOpSubgroupInclusiveAnd:
6928 case glslang::EOpSubgroupExclusiveAnd:
6929 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006930#ifdef NV_EXTENSIONS
6931 case glslang::EOpSubgroupPartitionedAnd:
6932 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6933 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6934#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006935 if (isBool) {
6936 opCode = spv::OpGroupNonUniformLogicalAnd;
6937 } else {
6938 opCode = spv::OpGroupNonUniformBitwiseAnd;
6939 }
6940 break;
6941 case glslang::EOpSubgroupOr:
6942 case glslang::EOpSubgroupInclusiveOr:
6943 case glslang::EOpSubgroupExclusiveOr:
6944 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006945#ifdef NV_EXTENSIONS
6946 case glslang::EOpSubgroupPartitionedOr:
6947 case glslang::EOpSubgroupPartitionedInclusiveOr:
6948 case glslang::EOpSubgroupPartitionedExclusiveOr:
6949#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006950 if (isBool) {
6951 opCode = spv::OpGroupNonUniformLogicalOr;
6952 } else {
6953 opCode = spv::OpGroupNonUniformBitwiseOr;
6954 }
6955 break;
6956 case glslang::EOpSubgroupXor:
6957 case glslang::EOpSubgroupInclusiveXor:
6958 case glslang::EOpSubgroupExclusiveXor:
6959 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006960#ifdef NV_EXTENSIONS
6961 case glslang::EOpSubgroupPartitionedXor:
6962 case glslang::EOpSubgroupPartitionedInclusiveXor:
6963 case glslang::EOpSubgroupPartitionedExclusiveXor:
6964#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006965 if (isBool) {
6966 opCode = spv::OpGroupNonUniformLogicalXor;
6967 } else {
6968 opCode = spv::OpGroupNonUniformBitwiseXor;
6969 }
6970 break;
6971 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6972 case glslang::EOpSubgroupQuadSwapHorizontal:
6973 case glslang::EOpSubgroupQuadSwapVertical:
6974 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6975 default: assert(0 && "Unhandled subgroup operation!");
6976 }
6977
John Kessenich149afc32018-08-14 13:31:43 -06006978 // get the right Group Operation
6979 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006980 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006981 default:
6982 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006983 case glslang::EOpSubgroupBallotBitCount:
6984 case glslang::EOpSubgroupAdd:
6985 case glslang::EOpSubgroupMul:
6986 case glslang::EOpSubgroupMin:
6987 case glslang::EOpSubgroupMax:
6988 case glslang::EOpSubgroupAnd:
6989 case glslang::EOpSubgroupOr:
6990 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006991 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006992 break;
6993 case glslang::EOpSubgroupBallotInclusiveBitCount:
6994 case glslang::EOpSubgroupInclusiveAdd:
6995 case glslang::EOpSubgroupInclusiveMul:
6996 case glslang::EOpSubgroupInclusiveMin:
6997 case glslang::EOpSubgroupInclusiveMax:
6998 case glslang::EOpSubgroupInclusiveAnd:
6999 case glslang::EOpSubgroupInclusiveOr:
7000 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007001 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007002 break;
7003 case glslang::EOpSubgroupBallotExclusiveBitCount:
7004 case glslang::EOpSubgroupExclusiveAdd:
7005 case glslang::EOpSubgroupExclusiveMul:
7006 case glslang::EOpSubgroupExclusiveMin:
7007 case glslang::EOpSubgroupExclusiveMax:
7008 case glslang::EOpSubgroupExclusiveAnd:
7009 case glslang::EOpSubgroupExclusiveOr:
7010 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007011 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007012 break;
7013 case glslang::EOpSubgroupClusteredAdd:
7014 case glslang::EOpSubgroupClusteredMul:
7015 case glslang::EOpSubgroupClusteredMin:
7016 case glslang::EOpSubgroupClusteredMax:
7017 case glslang::EOpSubgroupClusteredAnd:
7018 case glslang::EOpSubgroupClusteredOr:
7019 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007020 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007021 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007022#ifdef NV_EXTENSIONS
7023 case glslang::EOpSubgroupPartitionedAdd:
7024 case glslang::EOpSubgroupPartitionedMul:
7025 case glslang::EOpSubgroupPartitionedMin:
7026 case glslang::EOpSubgroupPartitionedMax:
7027 case glslang::EOpSubgroupPartitionedAnd:
7028 case glslang::EOpSubgroupPartitionedOr:
7029 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007030 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007031 break;
7032 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7033 case glslang::EOpSubgroupPartitionedInclusiveMul:
7034 case glslang::EOpSubgroupPartitionedInclusiveMin:
7035 case glslang::EOpSubgroupPartitionedInclusiveMax:
7036 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7037 case glslang::EOpSubgroupPartitionedInclusiveOr:
7038 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007039 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007040 break;
7041 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7042 case glslang::EOpSubgroupPartitionedExclusiveMul:
7043 case glslang::EOpSubgroupPartitionedExclusiveMin:
7044 case glslang::EOpSubgroupPartitionedExclusiveMax:
7045 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7046 case glslang::EOpSubgroupPartitionedExclusiveOr:
7047 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007048 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007049 break;
7050#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007051 }
7052
John Kessenich149afc32018-08-14 13:31:43 -06007053 // build the instruction
7054 std::vector<spv::IdImmediate> spvGroupOperands;
7055
7056 // Every operation begins with the Execution Scope operand.
7057 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7058 spvGroupOperands.push_back(executionScope);
7059
7060 // Next, for all operations that use a Group Operation, push that as an operand.
7061 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007062 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007063 spvGroupOperands.push_back(groupOperand);
7064 }
7065
John Kessenich66011cb2018-03-06 16:12:04 -07007066 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007067 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7068 spv::IdImmediate operand = { true, *opIt };
7069 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007070 }
7071
7072 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007073 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007074 switch (op) {
7075 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007076 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7077 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7078 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7079 }
7080 if (directionId != spv::NoResult) {
7081 spv::IdImmediate direction = { true, directionId };
7082 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007083 }
7084
7085 return builder.createOp(opCode, typeId, spvGroupOperands);
7086}
7087
John Kessenich5e4b1242015-08-06 22:53:06 -06007088spv::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 -06007089{
John Kessenich66011cb2018-03-06 16:12:04 -07007090 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7091 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007092
John Kessenich140f3df2015-06-26 16:58:36 -06007093 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007094 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007095 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007096 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007097 spv::Id typeId0 = 0;
7098 if (consumedOperands > 0)
7099 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007100 spv::Id typeId1 = 0;
7101 if (consumedOperands > 1)
7102 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007103 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007104
7105 switch (op) {
7106 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007107 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007108 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007109 else if (isUnsigned)
7110 libCall = spv::GLSLstd450UMin;
7111 else
7112 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007113 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007114 break;
7115 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007116 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007117 break;
7118 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007119 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007120 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007121 else if (isUnsigned)
7122 libCall = spv::GLSLstd450UMax;
7123 else
7124 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007125 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007126 break;
7127 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007128 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007129 break;
7130 case glslang::EOpDot:
7131 opCode = spv::OpDot;
7132 break;
7133 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007134 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007135 break;
7136
7137 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007138 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007139 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007140 else if (isUnsigned)
7141 libCall = spv::GLSLstd450UClamp;
7142 else
7143 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007144 builder.promoteScalar(precision, operands.front(), operands[1]);
7145 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007146 break;
7147 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007148 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7149 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007150 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007151 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007152 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007153 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007154 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007155 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007156 break;
7157 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007158 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007159 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007160 break;
7161 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007162 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007163 builder.promoteScalar(precision, operands[0], operands[2]);
7164 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007165 break;
7166
7167 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007168 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007169 break;
7170 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007171 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007172 break;
7173 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007174 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007175 break;
7176 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007177 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007178 break;
7179 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007180 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007181 break;
Rex Xu7a26c172015-12-08 17:12:09 +08007182 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007183#ifdef AMD_EXTENSIONS
7184 if (typeProxy == glslang::EbtFloat16)
7185 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7186#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007187 libCall = spv::GLSLstd450InterpolateAtSample;
7188 break;
7189 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007190#ifdef AMD_EXTENSIONS
7191 if (typeProxy == glslang::EbtFloat16)
7192 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7193#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007194 libCall = spv::GLSLstd450InterpolateAtOffset;
7195 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007196 case glslang::EOpAddCarry:
7197 opCode = spv::OpIAddCarry;
7198 typeId = builder.makeStructResultType(typeId0, typeId0);
7199 consumedOperands = 2;
7200 break;
7201 case glslang::EOpSubBorrow:
7202 opCode = spv::OpISubBorrow;
7203 typeId = builder.makeStructResultType(typeId0, typeId0);
7204 consumedOperands = 2;
7205 break;
7206 case glslang::EOpUMulExtended:
7207 opCode = spv::OpUMulExtended;
7208 typeId = builder.makeStructResultType(typeId0, typeId0);
7209 consumedOperands = 2;
7210 break;
7211 case glslang::EOpIMulExtended:
7212 opCode = spv::OpSMulExtended;
7213 typeId = builder.makeStructResultType(typeId0, typeId0);
7214 consumedOperands = 2;
7215 break;
7216 case glslang::EOpBitfieldExtract:
7217 if (isUnsigned)
7218 opCode = spv::OpBitFieldUExtract;
7219 else
7220 opCode = spv::OpBitFieldSExtract;
7221 break;
7222 case glslang::EOpBitfieldInsert:
7223 opCode = spv::OpBitFieldInsert;
7224 break;
7225
7226 case glslang::EOpFma:
7227 libCall = spv::GLSLstd450Fma;
7228 break;
7229 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007230 {
7231 libCall = spv::GLSLstd450FrexpStruct;
7232 assert(builder.isPointerType(typeId1));
7233 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007234 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007235#ifdef AMD_EXTENSIONS
7236 if (width == 16)
7237 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7238 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
7239#endif
Rex Xu470026f2017-03-29 17:12:40 +08007240 if (builder.getNumComponents(operands[0]) == 1)
7241 frexpIntType = builder.makeIntegerType(width, true);
7242 else
7243 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7244 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7245 consumedOperands = 1;
7246 }
John Kessenich55e7d112015-11-15 21:33:39 -07007247 break;
7248 case glslang::EOpLdexp:
7249 libCall = spv::GLSLstd450Ldexp;
7250 break;
7251
Rex Xu574ab042016-04-14 16:53:07 +08007252 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007253 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007254
John Kessenich66011cb2018-03-06 16:12:04 -07007255 case glslang::EOpSubgroupBroadcast:
7256 case glslang::EOpSubgroupBallotBitExtract:
7257 case glslang::EOpSubgroupShuffle:
7258 case glslang::EOpSubgroupShuffleXor:
7259 case glslang::EOpSubgroupShuffleUp:
7260 case glslang::EOpSubgroupShuffleDown:
7261 case glslang::EOpSubgroupClusteredAdd:
7262 case glslang::EOpSubgroupClusteredMul:
7263 case glslang::EOpSubgroupClusteredMin:
7264 case glslang::EOpSubgroupClusteredMax:
7265 case glslang::EOpSubgroupClusteredAnd:
7266 case glslang::EOpSubgroupClusteredOr:
7267 case glslang::EOpSubgroupClusteredXor:
7268 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007269#ifdef NV_EXTENSIONS
7270 case glslang::EOpSubgroupPartitionedAdd:
7271 case glslang::EOpSubgroupPartitionedMul:
7272 case glslang::EOpSubgroupPartitionedMin:
7273 case glslang::EOpSubgroupPartitionedMax:
7274 case glslang::EOpSubgroupPartitionedAnd:
7275 case glslang::EOpSubgroupPartitionedOr:
7276 case glslang::EOpSubgroupPartitionedXor:
7277 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7278 case glslang::EOpSubgroupPartitionedInclusiveMul:
7279 case glslang::EOpSubgroupPartitionedInclusiveMin:
7280 case glslang::EOpSubgroupPartitionedInclusiveMax:
7281 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7282 case glslang::EOpSubgroupPartitionedInclusiveOr:
7283 case glslang::EOpSubgroupPartitionedInclusiveXor:
7284 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7285 case glslang::EOpSubgroupPartitionedExclusiveMul:
7286 case glslang::EOpSubgroupPartitionedExclusiveMin:
7287 case glslang::EOpSubgroupPartitionedExclusiveMax:
7288 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7289 case glslang::EOpSubgroupPartitionedExclusiveOr:
7290 case glslang::EOpSubgroupPartitionedExclusiveXor:
7291#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007292 return createSubgroupOperation(op, typeId, operands, typeProxy);
7293
Rex Xu9d93a232016-05-05 12:30:44 +08007294#ifdef AMD_EXTENSIONS
7295 case glslang::EOpSwizzleInvocations:
7296 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7297 libCall = spv::SwizzleInvocationsAMD;
7298 break;
7299 case glslang::EOpSwizzleInvocationsMasked:
7300 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7301 libCall = spv::SwizzleInvocationsMaskedAMD;
7302 break;
7303 case glslang::EOpWriteInvocation:
7304 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7305 libCall = spv::WriteInvocationAMD;
7306 break;
7307
7308 case glslang::EOpMin3:
7309 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7310 if (isFloat)
7311 libCall = spv::FMin3AMD;
7312 else {
7313 if (isUnsigned)
7314 libCall = spv::UMin3AMD;
7315 else
7316 libCall = spv::SMin3AMD;
7317 }
7318 break;
7319 case glslang::EOpMax3:
7320 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7321 if (isFloat)
7322 libCall = spv::FMax3AMD;
7323 else {
7324 if (isUnsigned)
7325 libCall = spv::UMax3AMD;
7326 else
7327 libCall = spv::SMax3AMD;
7328 }
7329 break;
7330 case glslang::EOpMid3:
7331 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7332 if (isFloat)
7333 libCall = spv::FMid3AMD;
7334 else {
7335 if (isUnsigned)
7336 libCall = spv::UMid3AMD;
7337 else
7338 libCall = spv::SMid3AMD;
7339 }
7340 break;
7341
7342 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007343 if (typeProxy == glslang::EbtFloat16)
7344 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007345 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7346 libCall = spv::InterpolateAtVertexAMD;
7347 break;
7348#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007349 case glslang::EOpBarrier:
7350 {
7351 // This is for the extended controlBarrier function, with four operands.
7352 // The unextended barrier() goes through createNoArgOperation.
7353 assert(operands.size() == 4);
7354 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7355 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7356 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7357 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007358 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7359 spv::MemorySemanticsMakeVisibleKHRMask |
7360 spv::MemorySemanticsOutputMemoryKHRMask |
7361 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007362 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7363 }
7364 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7365 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7366 }
7367 return 0;
7368 }
7369 break;
7370 case glslang::EOpMemoryBarrier:
7371 {
7372 // This is for the extended memoryBarrier function, with three operands.
7373 // The unextended memoryBarrier() goes through createNoArgOperation.
7374 assert(operands.size() == 3);
7375 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7376 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7377 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007378 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7379 spv::MemorySemanticsMakeVisibleKHRMask |
7380 spv::MemorySemanticsOutputMemoryKHRMask |
7381 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007382 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7383 }
7384 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7385 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7386 }
7387 return 0;
7388 }
7389 break;
Chao Chen3c366992018-09-19 11:41:59 -07007390
7391#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007392 case glslang::EOpReportIntersectionNV:
7393 {
7394 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007395 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007396 }
7397 break;
7398 case glslang::EOpTraceNV:
7399 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007400 builder.createNoResultOp(spv::OpTraceNV, operands);
7401 return 0;
7402 }
7403 break;
7404 case glslang::EOpExecuteCallableNV:
7405 {
7406 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007407 return 0;
7408 }
7409 break;
Chao Chen3c366992018-09-19 11:41:59 -07007410 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7411 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7412 return 0;
7413#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007414 case glslang::EOpCooperativeMatrixMulAdd:
7415 opCode = spv::OpCooperativeMatrixMulAddNV;
7416 break;
7417
John Kessenich140f3df2015-06-26 16:58:36 -06007418 default:
7419 return 0;
7420 }
7421
7422 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007423 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007424 // Use an extended instruction from the standard library.
7425 // Construct the call arguments, without modifying the original operands vector.
7426 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7427 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007428 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007429 } else if (opCode == spv::OpDot && !isFloat) {
7430 // int dot(int, int)
7431 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7432 const int componentCount = builder.getNumComponents(operands[0]);
7433 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7434 builder.setPrecision(mulOp, precision);
7435 id = builder.createCompositeExtract(mulOp, typeId, 0);
7436 for (int i = 1; i < componentCount; ++i) {
7437 builder.setPrecision(id, precision);
7438 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7439 }
John Kessenich2359bd02015-12-06 19:29:11 -07007440 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007441 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007442 case 0:
7443 // should all be handled by visitAggregate and createNoArgOperation
7444 assert(0);
7445 return 0;
7446 case 1:
7447 // should all be handled by createUnaryOperation
7448 assert(0);
7449 return 0;
7450 case 2:
7451 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7452 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007453 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007454 // anything 3 or over doesn't have l-value operands, so all should be consumed
7455 assert(consumedOperands == operands.size());
7456 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007457 break;
7458 }
7459 }
7460
John Kessenich55e7d112015-11-15 21:33:39 -07007461 // Decode the return types that were structures
7462 switch (op) {
7463 case glslang::EOpAddCarry:
7464 case glslang::EOpSubBorrow:
7465 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7466 id = builder.createCompositeExtract(id, typeId0, 0);
7467 break;
7468 case glslang::EOpUMulExtended:
7469 case glslang::EOpIMulExtended:
7470 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7471 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7472 break;
7473 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007474 {
7475 assert(operands.size() == 2);
7476 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7477 // "exp" is floating-point type (from HLSL intrinsic)
7478 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7479 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7480 builder.createStore(member1, operands[1]);
7481 } else
7482 // "exp" is integer type (from GLSL built-in function)
7483 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7484 id = builder.createCompositeExtract(id, typeId0, 0);
7485 }
John Kessenich55e7d112015-11-15 21:33:39 -07007486 break;
7487 default:
7488 break;
7489 }
7490
John Kessenich32cfd492016-02-02 12:37:46 -07007491 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007492}
7493
Rex Xu9d93a232016-05-05 12:30:44 +08007494// Intrinsics with no arguments (or no return value, and no precision).
7495spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007496{
Jeff Bolz36831c92018-09-05 10:11:41 -05007497 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7498 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007499
7500 switch (op) {
7501 case glslang::EOpEmitVertex:
7502 builder.createNoResultOp(spv::OpEmitVertex);
7503 return 0;
7504 case glslang::EOpEndPrimitive:
7505 builder.createNoResultOp(spv::OpEndPrimitive);
7506 return 0;
7507 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007508 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007509 if (glslangIntermediate->usingVulkanMemoryModel()) {
7510 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7511 spv::MemorySemanticsOutputMemoryKHRMask |
7512 spv::MemorySemanticsAcquireReleaseMask);
7513 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7514 } else {
7515 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7516 }
John Kessenich82979362017-12-11 04:02:24 -07007517 } else {
7518 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7519 spv::MemorySemanticsWorkgroupMemoryMask |
7520 spv::MemorySemanticsAcquireReleaseMask);
7521 }
John Kessenich140f3df2015-06-26 16:58:36 -06007522 return 0;
7523 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007524 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7525 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007526 return 0;
7527 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007528 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7529 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007530 return 0;
7531 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007532 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7533 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007534 return 0;
7535 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007536 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7537 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007538 return 0;
7539 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007540 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7541 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007542 return 0;
7543 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007544 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7545 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007546 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007547 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007548 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007549 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007550 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007551 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007552 case glslang::EOpDeviceMemoryBarrier:
7553 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7554 spv::MemorySemanticsImageMemoryMask |
7555 spv::MemorySemanticsAcquireReleaseMask);
7556 return 0;
7557 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7558 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7559 spv::MemorySemanticsImageMemoryMask |
7560 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007561 return 0;
7562 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007563 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7564 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007565 return 0;
7566 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007567 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7568 spv::MemorySemanticsWorkgroupMemoryMask |
7569 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007570 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007571 case glslang::EOpSubgroupBarrier:
7572 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7573 spv::MemorySemanticsAcquireReleaseMask);
7574 return spv::NoResult;
7575 case glslang::EOpSubgroupMemoryBarrier:
7576 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7577 spv::MemorySemanticsAcquireReleaseMask);
7578 return spv::NoResult;
7579 case glslang::EOpSubgroupMemoryBarrierBuffer:
7580 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7581 spv::MemorySemanticsAcquireReleaseMask);
7582 return spv::NoResult;
7583 case glslang::EOpSubgroupMemoryBarrierImage:
7584 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7585 spv::MemorySemanticsAcquireReleaseMask);
7586 return spv::NoResult;
7587 case glslang::EOpSubgroupMemoryBarrierShared:
7588 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7589 spv::MemorySemanticsAcquireReleaseMask);
7590 return spv::NoResult;
7591 case glslang::EOpSubgroupElect: {
7592 std::vector<spv::Id> operands;
7593 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7594 }
Rex Xu9d93a232016-05-05 12:30:44 +08007595#ifdef AMD_EXTENSIONS
7596 case glslang::EOpTime:
7597 {
7598 std::vector<spv::Id> args; // Dummy arguments
7599 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7600 return builder.setPrecision(id, precision);
7601 }
7602#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007603#ifdef NV_EXTENSIONS
7604 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007605 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007606 return 0;
7607 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007608 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007609 return 0;
7610#endif
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007611
7612 case glslang::EOpBeginInvocationInterlock:
7613 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7614 return 0;
7615 case glslang::EOpEndInvocationInterlock:
7616 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7617 return 0;
7618
Jeff Bolzba6170b2019-07-01 09:23:23 -05007619 case glslang::EOpIsHelperInvocation:
7620 {
7621 std::vector<spv::Id> args; // Dummy arguments
7622 spv::Id id = builder.createOp(spv::OpIsHelperInvocationEXT, typeId, args);
7623 return id;
7624 }
7625
John Kessenich140f3df2015-06-26 16:58:36 -06007626 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007627 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007628 return 0;
7629 }
7630}
7631
7632spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7633{
John Kessenich2f273362015-07-18 22:34:27 -06007634 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007635 spv::Id id;
7636 if (symbolValues.end() != iter) {
7637 id = iter->second;
7638 return id;
7639 }
7640
7641 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007642 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7643 auto forcedType = getForcedType(builtIn, symbol->getType());
7644 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007645 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007646 if (forcedType.second != spv::NoType)
7647 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007648
Rex Xuc884b4a2016-06-29 15:03:44 +08007649 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007650 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7651 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7652 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007653#ifdef NV_EXTENSIONS
7654 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7655#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007656 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007657 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007658 if (symbol->getQualifier().hasIndex())
7659 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7660 if (symbol->getQualifier().hasComponent())
7661 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007662 // atomic counters use this:
7663 if (symbol->getQualifier().hasOffset())
7664 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007665 }
7666
scygan2c864272016-05-18 18:09:17 +02007667 if (symbol->getQualifier().hasLocation())
7668 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007669 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007670 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007671 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007672 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007673 }
John Kessenich140f3df2015-06-26 16:58:36 -06007674 if (symbol->getQualifier().hasSet())
7675 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007676 else if (IsDescriptorResource(symbol->getType())) {
7677 // default to 0
7678 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7679 }
John Kessenich140f3df2015-06-26 16:58:36 -06007680 if (symbol->getQualifier().hasBinding())
7681 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007682 else if (IsDescriptorResource(symbol->getType())) {
7683 // default to 0
7684 builder.addDecoration(id, spv::DecorationBinding, 0);
7685 }
John Kessenich6c292d32016-02-15 20:58:50 -07007686 if (symbol->getQualifier().hasAttachment())
7687 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007688 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007689 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007690 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007691 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007692 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7693 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7694 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7695 }
7696 if (symbol->getQualifier().hasXfbOffset())
7697 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007698 }
7699
Rex Xu1da878f2016-02-21 20:59:01 +08007700 if (symbol->getType().isImage()) {
7701 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007702 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007703 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007704 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007705 }
7706
John Kessenich9c14f772019-06-17 08:38:35 -06007707 // add built-in variable decoration
7708 if (builtIn != spv::BuiltInMax) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007709 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich9c14f772019-06-17 08:38:35 -06007710 }
John Kessenich140f3df2015-06-26 16:58:36 -06007711
John Kessenich5611c6d2018-04-05 11:25:02 -06007712 // nonuniform
7713 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7714
John Kessenichecba76f2017-01-06 00:34:48 -07007715#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007716 if (builtIn == spv::BuiltInSampleMask) {
7717 spv::Decoration decoration;
7718 // GL_NV_sample_mask_override_coverage extension
7719 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007720 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007721 else
7722 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007723 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007724 if (decoration != spv::DecorationMax) {
7725 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7726 }
7727 }
chaoc771d89f2017-01-13 01:10:53 -08007728 else if (builtIn == spv::BuiltInLayer) {
7729 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007730 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007731 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007732 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7733 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7734 }
John Kessenichb41bff62017-08-11 13:07:17 -06007735 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007736 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7737 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007738 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7739 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7740 }
7741 }
7742
chaoc6e5acae2016-12-20 13:28:52 -08007743 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007744 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007745 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007746 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7747 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007748 if (symbol->getQualifier().pervertexNV) {
7749 builder.addDecoration(id, spv::DecorationPerVertexNV);
7750 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7751 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7752 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007753#endif
7754
John Kessenich5d610ee2018-03-07 18:05:55 -07007755 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7756 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7757 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7758 symbol->getType().getQualifier().semanticName);
7759 }
7760
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007761 if (symbol->getBasicType() == glslang::EbtReference) {
7762 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7763 }
7764
John Kessenich140f3df2015-06-26 16:58:36 -06007765 return id;
7766}
7767
Chao Chen3c366992018-09-19 11:41:59 -07007768#ifdef NV_EXTENSIONS
7769// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7770void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7771{
7772 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007773 if (qualifier.perPrimitiveNV) {
7774 // Need to add capability/extension for fragment shader.
7775 // Mesh shader already adds this by default.
7776 if (glslangIntermediate->getStage() == EShLangFragment) {
7777 builder.addCapability(spv::CapabilityMeshShadingNV);
7778 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7779 }
Chao Chen3c366992018-09-19 11:41:59 -07007780 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007781 }
Chao Chen3c366992018-09-19 11:41:59 -07007782 if (qualifier.perViewNV)
7783 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7784 if (qualifier.perTaskNV)
7785 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7786 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007787 if (qualifier.perPrimitiveNV) {
7788 // Need to add capability/extension for fragment shader.
7789 // Mesh shader already adds this by default.
7790 if (glslangIntermediate->getStage() == EShLangFragment) {
7791 builder.addCapability(spv::CapabilityMeshShadingNV);
7792 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7793 }
Chao Chen3c366992018-09-19 11:41:59 -07007794 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007795 }
Chao Chen3c366992018-09-19 11:41:59 -07007796 if (qualifier.perViewNV)
7797 builder.addDecoration(id, spv::DecorationPerViewNV);
7798 if (qualifier.perTaskNV)
7799 builder.addDecoration(id, spv::DecorationPerTaskNV);
7800 }
7801}
7802#endif
7803
John Kessenich55e7d112015-11-15 21:33:39 -07007804// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007805// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007806//
7807// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7808//
7809// Recursively walk the nodes. The nodes form a tree whose leaves are
7810// regular constants, which themselves are trees that createSpvConstant()
7811// recursively walks. So, this function walks the "top" of the tree:
7812// - emit specialization constant-building instructions for specConstant
7813// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007814spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007815{
John Kessenich7cc0e282016-03-20 00:46:02 -06007816 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007817
qining4f4bb812016-04-03 23:55:17 -04007818 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007819 if (! node.getQualifier().specConstant) {
7820 // hand off to the non-spec-constant path
7821 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7822 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007823 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007824 nextConst, false);
7825 }
7826
7827 // We now know we have a specialization constant to build
7828
John Kessenichd94c0032016-05-30 19:29:40 -06007829 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007830 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7831 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7832 std::vector<spv::Id> dimConstId;
7833 for (int dim = 0; dim < 3; ++dim) {
7834 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7835 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007836 if (specConst) {
7837 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7838 glslangIntermediate->getLocalSizeSpecId(dim));
7839 }
qining4f4bb812016-04-03 23:55:17 -04007840 }
7841 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7842 }
7843
7844 // An AST node labelled as specialization constant should be a symbol node.
7845 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7846 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007847 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007848 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007849 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7850 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7851 // will set the builder into spec constant op instruction generating mode.
7852 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007853 result = accessChainLoad(sub_tree->getType());
7854 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007855 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007856 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007857 } else {
7858 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007859 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007860 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007861 builder.addName(result, sn->getName().c_str());
7862 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007863 }
qining4f4bb812016-04-03 23:55:17 -04007864
7865 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7866 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007867 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007868 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007869}
7870
John Kessenich140f3df2015-06-26 16:58:36 -06007871// Use 'consts' as the flattened glslang source of scalar constants to recursively
7872// build the aggregate SPIR-V constant.
7873//
7874// If there are not enough elements present in 'consts', 0 will be substituted;
7875// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7876//
qining08408382016-03-21 09:51:37 -04007877spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007878{
7879 // vector of constants for SPIR-V
7880 std::vector<spv::Id> spvConsts;
7881
7882 // Type is used for struct and array constants
7883 spv::Id typeId = convertGlslangToSpvType(glslangType);
7884
7885 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007886 glslang::TType elementType(glslangType, 0);
7887 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007888 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007889 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007890 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007891 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007892 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007893 } else if (glslangType.isCoopMat()) {
7894 glslang::TType componentType(glslangType.getBasicType());
7895 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007896 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007897 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7898 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007899 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007900 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007901 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7902 bool zero = nextConst >= consts.size();
7903 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007904 case glslang::EbtInt8:
7905 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7906 break;
7907 case glslang::EbtUint8:
7908 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7909 break;
7910 case glslang::EbtInt16:
7911 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7912 break;
7913 case glslang::EbtUint16:
7914 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7915 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007916 case glslang::EbtInt:
7917 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7918 break;
7919 case glslang::EbtUint:
7920 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7921 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007922 case glslang::EbtInt64:
7923 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7924 break;
7925 case glslang::EbtUint64:
7926 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7927 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007928 case glslang::EbtFloat:
7929 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7930 break;
7931 case glslang::EbtDouble:
7932 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7933 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007934 case glslang::EbtFloat16:
7935 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7936 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007937 case glslang::EbtBool:
7938 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7939 break;
7940 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007941 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007942 break;
7943 }
7944 ++nextConst;
7945 }
7946 } else {
7947 // we have a non-aggregate (scalar) constant
7948 bool zero = nextConst >= consts.size();
7949 spv::Id scalar = 0;
7950 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007951 case glslang::EbtInt8:
7952 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7953 break;
7954 case glslang::EbtUint8:
7955 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7956 break;
7957 case glslang::EbtInt16:
7958 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7959 break;
7960 case glslang::EbtUint16:
7961 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7962 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007963 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007964 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007965 break;
7966 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007967 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007968 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007969 case glslang::EbtInt64:
7970 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7971 break;
7972 case glslang::EbtUint64:
7973 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7974 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007975 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007976 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007977 break;
7978 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007979 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007980 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007981 case glslang::EbtFloat16:
7982 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7983 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007984 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007985 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007986 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007987 case glslang::EbtReference:
7988 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7989 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7990 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007991 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007992 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007993 break;
7994 }
7995 ++nextConst;
7996 return scalar;
7997 }
7998
7999 return builder.makeCompositeConstant(typeId, spvConsts);
8000}
8001
John Kessenich7c1aa102015-10-15 13:29:11 -06008002// Return true if the node is a constant or symbol whose reading has no
8003// non-trivial observable cost or effect.
8004bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
8005{
8006 // don't know what this is
8007 if (node == nullptr)
8008 return false;
8009
8010 // a constant is safe
8011 if (node->getAsConstantUnion() != nullptr)
8012 return true;
8013
8014 // not a symbol means non-trivial
8015 if (node->getAsSymbolNode() == nullptr)
8016 return false;
8017
8018 // a symbol, depends on what's being read
8019 switch (node->getType().getQualifier().storage) {
8020 case glslang::EvqTemporary:
8021 case glslang::EvqGlobal:
8022 case glslang::EvqIn:
8023 case glslang::EvqInOut:
8024 case glslang::EvqConst:
8025 case glslang::EvqConstReadOnly:
8026 case glslang::EvqUniform:
8027 return true;
8028 default:
8029 return false;
8030 }
qining25262b32016-05-06 17:25:16 -04008031}
John Kessenich7c1aa102015-10-15 13:29:11 -06008032
8033// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008034// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008035// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008036// Return true if trivial.
8037bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8038{
8039 if (node == nullptr)
8040 return false;
8041
John Kessenich84cc15f2017-05-24 16:44:47 -06008042 // count non scalars as trivial, as well as anything coming from HLSL
8043 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008044 return true;
8045
John Kessenich7c1aa102015-10-15 13:29:11 -06008046 // symbols and constants are trivial
8047 if (isTrivialLeaf(node))
8048 return true;
8049
8050 // otherwise, it needs to be a simple operation or one or two leaf nodes
8051
8052 // not a simple operation
8053 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8054 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8055 if (binaryNode == nullptr && unaryNode == nullptr)
8056 return false;
8057
8058 // not on leaf nodes
8059 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8060 return false;
8061
8062 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8063 return false;
8064 }
8065
8066 switch (node->getAsOperator()->getOp()) {
8067 case glslang::EOpLogicalNot:
8068 case glslang::EOpConvIntToBool:
8069 case glslang::EOpConvUintToBool:
8070 case glslang::EOpConvFloatToBool:
8071 case glslang::EOpConvDoubleToBool:
8072 case glslang::EOpEqual:
8073 case glslang::EOpNotEqual:
8074 case glslang::EOpLessThan:
8075 case glslang::EOpGreaterThan:
8076 case glslang::EOpLessThanEqual:
8077 case glslang::EOpGreaterThanEqual:
8078 case glslang::EOpIndexDirect:
8079 case glslang::EOpIndexDirectStruct:
8080 case glslang::EOpLogicalXor:
8081 case glslang::EOpAny:
8082 case glslang::EOpAll:
8083 return true;
8084 default:
8085 return false;
8086 }
8087}
8088
8089// Emit short-circuiting code, where 'right' is never evaluated unless
8090// the left side is true (for &&) or false (for ||).
8091spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
8092{
8093 spv::Id boolTypeId = builder.makeBoolType();
8094
8095 // emit left operand
8096 builder.clearAccessChain();
8097 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008098 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008099
8100 // Operands to accumulate OpPhi operands
8101 std::vector<spv::Id> phiOperands;
8102 // accumulate left operand's phi information
8103 phiOperands.push_back(leftId);
8104 phiOperands.push_back(builder.getBuildPoint()->getId());
8105
8106 // Make the two kinds of operation symmetric with a "!"
8107 // || => emit "if (! left) result = right"
8108 // && => emit "if ( left) result = right"
8109 //
8110 // TODO: this runtime "not" for || could be avoided by adding functionality
8111 // to 'builder' to have an "else" without an "then"
8112 if (op == glslang::EOpLogicalOr)
8113 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8114
8115 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008116 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008117
8118 // emit right operand as the "then" part of the "if"
8119 builder.clearAccessChain();
8120 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008121 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008122
8123 // accumulate left operand's phi information
8124 phiOperands.push_back(rightId);
8125 phiOperands.push_back(builder.getBuildPoint()->getId());
8126
8127 // finish the "if"
8128 ifBuilder.makeEndIf();
8129
8130 // phi together the two results
8131 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8132}
8133
Frank Henigman541f7bb2018-01-16 00:18:26 -05008134#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08008135// Return type Id of the imported set of extended instructions corresponds to the name.
8136// Import this set if it has not been imported yet.
8137spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8138{
8139 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8140 return extBuiltinMap[name];
8141 else {
Rex Xu51596642016-09-21 18:56:12 +08008142 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008143 spv::Id extBuiltins = builder.import(name);
8144 extBuiltinMap[name] = extBuiltins;
8145 return extBuiltins;
8146 }
8147}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008148#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008149
John Kessenich140f3df2015-06-26 16:58:36 -06008150}; // end anonymous namespace
8151
8152namespace glslang {
8153
John Kessenich68d78fd2015-07-12 19:28:10 -06008154void GetSpirvVersion(std::string& version)
8155{
John Kessenich9e55f632015-07-15 10:03:39 -06008156 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008157 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008158 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008159 version = buf;
8160}
8161
John Kessenicha372a3e2017-11-02 22:32:14 -06008162// For low-order part of the generator's magic number. Bump up
8163// when there is a change in the style (e.g., if SSA form changes,
8164// or a different instruction sequence to do something gets used).
8165int GetSpirvGeneratorVersion()
8166{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008167 // return 1; // start
8168 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008169 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008170 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008171 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008172 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8173 // versions 4 and 6 each generate OpArrayLength as it has long been done
8174 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008175}
8176
John Kessenich140f3df2015-06-26 16:58:36 -06008177// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008178void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008179{
8180 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008181 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008182 if (out.fail())
8183 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008184 for (int i = 0; i < (int)spirv.size(); ++i) {
8185 unsigned int word = spirv[i];
8186 out.write((const char*)&word, 4);
8187 }
8188 out.close();
8189}
8190
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008191// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008192void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008193{
8194 std::ofstream out;
8195 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008196 if (out.fail())
8197 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008198 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008199 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008200 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008201 if (varName != nullptr) {
8202 out << "\t #pragma once" << std::endl;
8203 out << "const uint32_t " << varName << "[] = {" << std::endl;
8204 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008205 const int WORDS_PER_LINE = 8;
8206 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8207 out << "\t";
8208 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8209 const unsigned int word = spirv[i + j];
8210 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8211 if (i + j + 1 < (int)spirv.size()) {
8212 out << ",";
8213 }
8214 }
8215 out << std::endl;
8216 }
Flavio15017db2017-02-15 14:29:33 -08008217 if (varName != nullptr) {
8218 out << "};";
8219 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008220 out.close();
8221}
8222
John Kessenich140f3df2015-06-26 16:58:36 -06008223//
8224// Set up the glslang traversal
8225//
John Kessenich4e11b612018-08-30 16:56:59 -06008226void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008227{
Lei Zhang17535f72016-05-04 15:55:59 -04008228 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008229 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008230}
8231
John Kessenich4e11b612018-08-30 16:56:59 -06008232void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008233 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008234{
John Kessenich140f3df2015-06-26 16:58:36 -06008235 TIntermNode* root = intermediate.getTreeRoot();
8236
8237 if (root == 0)
8238 return;
8239
John Kessenich4e11b612018-08-30 16:56:59 -06008240 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008241 if (options == nullptr)
8242 options = &defaultOptions;
8243
John Kessenich4e11b612018-08-30 16:56:59 -06008244 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008245
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008246 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008247 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008248 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008249 it.dumpSpv(spirv);
8250
GregFfb03a552018-03-29 11:49:14 -06008251#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008252 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8253 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008254 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8255 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008256 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008257 prelegalization = false;
8258 }
John Kessenich717c80a2018-08-23 15:17:10 -06008259
John Kessenich4e11b612018-08-30 16:56:59 -06008260 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008261 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008262
John Kessenich717c80a2018-08-23 15:17:10 -06008263 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008264 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008265
GregFcd1f1692017-09-21 18:40:22 -06008266#endif
8267
John Kessenich4e11b612018-08-30 16:56:59 -06008268 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008269}
8270
8271}; // end namespace glslang