blob: 16d90b893434f3f9ffef7795b6c9c06bd99a302e [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
3114 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003115 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003116 break;
3117 }
3118
3119 return false;
3120}
3121
John Kessenich9c14f772019-06-17 08:38:35 -06003122spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node, spv::Id forcedType)
John Kessenich140f3df2015-06-26 16:58:36 -06003123{
qining25262b32016-05-06 17:25:16 -04003124 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003125 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003126 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003127 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003128 spv::Id result = createSpvConstant(*node);
3129 if (result != spv::NoResult)
3130 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003131 }
3132
3133 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003134 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich9c14f772019-06-17 08:38:35 -06003135 spv::Id spvType = forcedType == spv::NoType ? convertGlslangToSpvType(node->getType())
3136 : forcedType;
John Kessenich140f3df2015-06-26 16:58:36 -06003137
Rex Xucabbb782017-03-24 13:41:14 +08003138 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
3139 node->getType().containsBasicType(glslang::EbtInt16) ||
3140 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08003141 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003142 switch (storageClass) {
3143 case spv::StorageClassInput:
3144 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07003145 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003146 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003147 break;
3148 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07003149 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003150 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06003151 break;
3152 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003153 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003154 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3155 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003156 else
3157 builder.addCapability(spv::CapabilityStorageUniform16);
3158 break;
3159 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003160 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003161 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3162 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3163 break;
3164 default:
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003165 if (node->getType().containsBasicType(glslang::EbtFloat16))
3166 builder.addCapability(spv::CapabilityFloat16);
3167 if (node->getType().containsBasicType(glslang::EbtInt16) ||
3168 node->getType().containsBasicType(glslang::EbtUint16))
3169 builder.addCapability(spv::CapabilityInt16);
John Kessenich18310872018-05-14 22:08:53 -06003170 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003171 }
3172 }
Rex Xuf89ad982017-04-07 23:22:33 +08003173
John Kessenich312dcfb2018-07-03 13:19:51 -06003174 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3175 node->getType().containsBasicType(glslang::EbtUint8);
3176 if (contains8BitType) {
3177 if (storageClass == spv::StorageClassPushConstant) {
3178 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3179 builder.addCapability(spv::CapabilityStoragePushConstant8);
3180 } else if (storageClass == spv::StorageClassUniform) {
3181 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3182 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003183 } else if (storageClass == spv::StorageClassStorageBuffer) {
3184 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3185 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
Jeff Bolz2b2316d2019-02-17 22:49:28 -06003186 } else {
3187 builder.addCapability(spv::CapabilityInt8);
John Kessenich312dcfb2018-07-03 13:19:51 -06003188 }
3189 }
3190
John Kessenich140f3df2015-06-26 16:58:36 -06003191 const char* name = node->getName().c_str();
3192 if (glslang::IsAnonymous(name))
3193 name = "";
3194
3195 return builder.createVariable(storageClass, spvType, name);
3196}
3197
3198// Return type Id of the sampled type.
3199spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3200{
3201 switch (sampler.type) {
3202 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003203#ifdef AMD_EXTENSIONS
3204 case glslang::EbtFloat16:
3205 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3206 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3207 return builder.makeFloatType(16);
3208#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003209 case glslang::EbtInt: return builder.makeIntType(32);
3210 case glslang::EbtUint: return builder.makeUintType(32);
3211 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003212 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003213 return builder.makeFloatType(32);
3214 }
3215}
3216
John Kessenich8c8505c2016-07-26 12:50:38 -06003217// If node is a swizzle operation, return the type that should be used if
3218// the swizzle base is first consumed by another operation, before the swizzle
3219// is applied.
3220spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3221{
John Kessenichecba76f2017-01-06 00:34:48 -07003222 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003223 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3224 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3225 else
3226 return spv::NoType;
3227}
3228
3229// When inverting a swizzle with a parent op, this function
3230// will apply the swizzle operation to a completed parent operation.
3231spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3232{
3233 std::vector<unsigned> swizzle;
3234 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3235 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3236}
3237
John Kessenich8c8505c2016-07-26 12:50:38 -06003238// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3239void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3240{
3241 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3242 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3243 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3244}
3245
John Kessenich3ac051e2015-12-20 11:29:16 -07003246// Convert from a glslang type to an SPV type, by calling into a
3247// recursive version of this function. This establishes the inherited
3248// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003249spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003250{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003251 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003252}
3253
3254// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003255// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003256// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003257spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003258 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3259 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003260{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003261 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003262
3263 switch (type.getBasicType()) {
3264 case glslang::EbtVoid:
3265 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003266 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003267 break;
3268 case glslang::EbtFloat:
3269 spvType = builder.makeFloatType(32);
3270 break;
3271 case glslang::EbtDouble:
3272 spvType = builder.makeFloatType(64);
3273 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003274 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003275 spvType = builder.makeFloatType(16);
3276 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003277 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003278 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3279 // a 32-bit int where non-0 means true.
3280 if (explicitLayout != glslang::ElpNone)
3281 spvType = builder.makeUintType(32);
3282 else
3283 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003284 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003285 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003286 spvType = builder.makeIntType(8);
3287 break;
3288 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003289 spvType = builder.makeUintType(8);
3290 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003291 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003292 spvType = builder.makeIntType(16);
3293 break;
3294 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003295 spvType = builder.makeUintType(16);
3296 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003297 case glslang::EbtInt:
3298 spvType = builder.makeIntType(32);
3299 break;
3300 case glslang::EbtUint:
3301 spvType = builder.makeUintType(32);
3302 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003303 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003304 spvType = builder.makeIntType(64);
3305 break;
3306 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003307 spvType = builder.makeUintType(64);
3308 break;
John Kessenich426394d2015-07-23 10:22:48 -06003309 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003310 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003311 spvType = builder.makeUintType(32);
3312 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003313#ifdef NV_EXTENSIONS
3314 case glslang::EbtAccStructNV:
3315 spvType = builder.makeAccelerationStructureNVType();
3316 break;
3317#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003318 case glslang::EbtSampler:
3319 {
3320 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003321 if (sampler.sampler) {
3322 // pure sampler
3323 spvType = builder.makeSamplerType();
3324 } else {
3325 // an image is present, make its type
3326 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3327 sampler.image ? 2 : 1, TranslateImageFormat(type));
3328 if (sampler.combined) {
3329 // already has both image and sampler, make the combined type
3330 spvType = builder.makeSampledImageType(spvType);
3331 }
John Kessenich55e7d112015-11-15 21:33:39 -07003332 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003333 }
John Kessenich140f3df2015-06-26 16:58:36 -06003334 break;
3335 case glslang::EbtStruct:
3336 case glslang::EbtBlock:
3337 {
3338 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003339 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003340
3341 // Try to share structs for different layouts, but not yet for other
3342 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003343 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003344 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003345 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003346 break;
3347
3348 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003349 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003350 memberRemapper[glslangMembers].resize(glslangMembers->size());
3351 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003352 }
3353 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003354 case glslang::EbtReference:
3355 {
3356 // Make the forward pointer, then recurse to convert the structure type, then
3357 // patch up the forward pointer with a real pointer type.
3358 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3359 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3360 forwardPointers[type.getReferentType()] = forwardId;
3361 }
3362 spvType = forwardPointers[type.getReferentType()];
3363 if (!forwardReferenceOnly) {
3364 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3365 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3366 forwardPointers[type.getReferentType()],
3367 referentType);
3368 }
3369 }
3370 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003371 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003372 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003373 break;
3374 }
3375
3376 if (type.isMatrix())
3377 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3378 else {
3379 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3380 if (type.getVectorSize() > 1)
3381 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3382 }
3383
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003384 if (type.isCoopMat()) {
3385 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3386 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3387 if (type.getBasicType() == glslang::EbtFloat16)
3388 builder.addCapability(spv::CapabilityFloat16);
3389
3390 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3391 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3392 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3393
3394 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3395 }
3396
John Kessenich140f3df2015-06-26 16:58:36 -06003397 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003398 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3399
John Kessenichc9a80832015-09-12 12:17:44 -06003400 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003401 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003402 // We need to decorate array strides for types needing explicit layout, except blocks.
3403 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003404 // Use a dummy glslang type for querying internal strides of
3405 // arrays of arrays, but using just a one-dimensional array.
3406 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003407 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3408 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003409
3410 // Will compute the higher-order strides here, rather than making a whole
3411 // pile of types and doing repetitive recursion on their contents.
3412 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3413 }
John Kessenichf8842e52016-01-04 19:22:56 -07003414
3415 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003416 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003417 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003418 if (stride > 0)
3419 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003420 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003421 }
3422 } else {
3423 // single-dimensional array, and don't yet have stride
3424
John Kessenichf8842e52016-01-04 19:22:56 -07003425 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003426 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3427 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003428 }
John Kessenich31ed4832015-09-09 17:51:38 -06003429
John Kessenichead86222018-03-28 18:01:20 -06003430 // Do the outer dimension, which might not be known for a runtime-sized array.
3431 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3432 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003433 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003434 else {
3435 if (!lastBufferBlockMember) {
3436 builder.addExtension("SPV_EXT_descriptor_indexing");
3437 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3438 }
John Kessenichead86222018-03-28 18:01:20 -06003439 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003440 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003441 if (stride > 0)
3442 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003443 }
3444
3445 return spvType;
3446}
3447
John Kessenich0e737842017-03-24 18:38:16 -06003448// TODO: this functionality should exist at a higher level, in creating the AST
3449//
3450// Identify interface members that don't have their required extension turned on.
3451//
3452bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3453{
Chao Chen3c366992018-09-19 11:41:59 -07003454#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003455 auto& extensions = glslangIntermediate->getRequestedExtensions();
3456
Rex Xubcf291a2017-03-29 23:01:36 +08003457 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3458 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3459 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003460 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3461 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3462 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003463
3464 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3465 if (member.getFieldName() == "gl_ViewportMask" &&
3466 extensions.find("GL_NV_viewport_array2") == extensions.end())
3467 return true;
3468 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3469 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3470 return true;
3471 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3472 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3473 return true;
3474 }
3475#endif
John Kessenich0e737842017-03-24 18:38:16 -06003476
3477 return false;
3478};
3479
John Kessenich6090df02016-06-30 21:18:02 -06003480// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3481// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3482// Mutually recursive with convertGlslangToSpvType().
3483spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3484 const glslang::TTypeList* glslangMembers,
3485 glslang::TLayoutPacking explicitLayout,
3486 const glslang::TQualifier& qualifier)
3487{
3488 // Create a vector of struct types for SPIR-V to consume
3489 std::vector<spv::Id> spvMembers;
3490 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 -06003491 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003492 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3493 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3494 if (glslangMember.hiddenMember()) {
3495 ++memberDelta;
3496 if (type.getBasicType() == glslang::EbtBlock)
3497 memberRemapper[glslangMembers][i] = -1;
3498 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003499 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003500 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003501 if (filterMember(glslangMember))
3502 continue;
3503 }
John Kessenich6090df02016-06-30 21:18:02 -06003504 // modify just this child's view of the qualifier
3505 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3506 InheritQualifiers(memberQualifier, qualifier);
3507
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003508 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003509 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003510 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003511
3512 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003513 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3514 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003515
3516 // Make forward pointers for any pointer members, and create a list of members to
3517 // convert to spirv types after creating the struct.
3518 if (glslangMember.getBasicType() == glslang::EbtReference) {
3519 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3520 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3521 }
3522 spvMembers.push_back(
3523 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3524 } else {
3525 spvMembers.push_back(
3526 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3527 }
John Kessenich6090df02016-06-30 21:18:02 -06003528 }
3529 }
3530
3531 // Make the SPIR-V type
3532 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003533 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003534 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3535
3536 // Decorate it
3537 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3538
John Kessenichd72f4882019-01-16 14:55:37 +07003539 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003540 auto it = deferredForwardPointers[i];
3541 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3542 }
3543
John Kessenich6090df02016-06-30 21:18:02 -06003544 return spvType;
3545}
3546
3547void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3548 const glslang::TTypeList* glslangMembers,
3549 glslang::TLayoutPacking explicitLayout,
3550 const glslang::TQualifier& qualifier,
3551 spv::Id spvType)
3552{
3553 // Name and decorate the non-hidden members
3554 int offset = -1;
3555 int locationOffset = 0; // for use within the members of this struct
3556 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3557 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3558 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003559 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003560 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003561 if (filterMember(glslangMember))
3562 continue;
3563 }
John Kessenich6090df02016-06-30 21:18:02 -06003564
3565 // modify just this child's view of the qualifier
3566 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3567 InheritQualifiers(memberQualifier, qualifier);
3568
3569 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003570 if (member < 0)
3571 continue;
3572
3573 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3574 builder.addMemberDecoration(spvType, member,
3575 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3576 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3577 // Add interpolation and auxiliary storage decorations only to
3578 // top-level members of Input and Output storage classes
3579 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3580 type.getQualifier().storage == glslang::EvqVaryingOut) {
3581 if (type.getBasicType() == glslang::EbtBlock ||
3582 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3583 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3584 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003585#ifdef NV_EXTENSIONS
3586 addMeshNVDecoration(spvType, member, memberQualifier);
3587#endif
John Kessenich6090df02016-06-30 21:18:02 -06003588 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003589 }
3590 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003591
John Kessenich5d610ee2018-03-07 18:05:55 -07003592 if (type.getBasicType() == glslang::EbtBlock &&
3593 qualifier.storage == glslang::EvqBuffer) {
3594 // Add memory decorations only to top-level members of shader storage block
3595 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003596 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003597 for (unsigned int i = 0; i < memory.size(); ++i)
3598 builder.addMemberDecoration(spvType, member, memory[i]);
3599 }
John Kessenich6090df02016-06-30 21:18:02 -06003600
John Kessenich5d610ee2018-03-07 18:05:55 -07003601 // Location assignment was already completed correctly by the front end,
3602 // just track whether a member needs to be decorated.
3603 // Ignore member locations if the container is an array, as that's
3604 // ill-specified and decisions have been made to not allow this.
3605 if (! type.isArray() && memberQualifier.hasLocation())
3606 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003607
John Kessenich5d610ee2018-03-07 18:05:55 -07003608 if (qualifier.hasLocation()) // track for upcoming inheritance
3609 locationOffset += glslangIntermediate->computeTypeLocationSize(
3610 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003611
John Kessenich5d610ee2018-03-07 18:05:55 -07003612 // component, XFB, others
3613 if (glslangMember.getQualifier().hasComponent())
3614 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3615 glslangMember.getQualifier().layoutComponent);
3616 if (glslangMember.getQualifier().hasXfbOffset())
3617 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3618 glslangMember.getQualifier().layoutXfbOffset);
3619 else if (explicitLayout != glslang::ElpNone) {
3620 // figure out what to do with offset, which is accumulating
3621 int nextOffset;
3622 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3623 if (offset >= 0)
3624 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3625 offset = nextOffset;
3626 }
John Kessenich6090df02016-06-30 21:18:02 -06003627
John Kessenich5d610ee2018-03-07 18:05:55 -07003628 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3629 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3630 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003631
John Kessenich5d610ee2018-03-07 18:05:55 -07003632 // built-in variable decorations
3633 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3634 if (builtIn != spv::BuiltInMax)
3635 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003636
John Kessenich5611c6d2018-04-05 11:25:02 -06003637 // nonuniform
3638 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3639
John Kessenichead86222018-03-28 18:01:20 -06003640 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3641 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3642 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3643 memberQualifier.semanticName);
3644 }
3645
chaoc771d89f2017-01-13 01:10:53 -08003646#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003647 if (builtIn == spv::BuiltInLayer) {
3648 // SPV_NV_viewport_array2 extension
3649 if (glslangMember.getQualifier().layoutViewportRelative){
3650 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3651 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3652 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003653 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003654 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3655 builder.addMemberDecoration(spvType, member,
3656 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3657 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3658 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3659 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003660 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003661 }
3662 if (glslangMember.getQualifier().layoutPassthrough) {
3663 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3664 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3665 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3666 }
chaoc771d89f2017-01-13 01:10:53 -08003667#endif
John Kessenich6090df02016-06-30 21:18:02 -06003668 }
3669
3670 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003671 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3672 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003673}
3674
John Kessenich6c292d32016-02-15 20:58:50 -07003675// Turn the expression forming the array size into an id.
3676// This is not quite trivial, because of specialization constants.
3677// Sometimes, a raw constant is turned into an Id, and sometimes
3678// a specialization constant expression is.
3679spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3680{
3681 // First, see if this is sized with a node, meaning a specialization constant:
3682 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3683 if (specNode != nullptr) {
3684 builder.clearAccessChain();
3685 specNode->traverse(this);
3686 return accessChainLoad(specNode->getAsTyped()->getType());
3687 }
qining25262b32016-05-06 17:25:16 -04003688
John Kessenich6c292d32016-02-15 20:58:50 -07003689 // Otherwise, need a compile-time (front end) size, get it:
3690 int size = arraySizes.getDimSize(dim);
3691 assert(size > 0);
3692 return builder.makeUintConstant(size);
3693}
3694
John Kessenich103bef92016-02-08 21:38:15 -07003695// Wrap the builder's accessChainLoad to:
3696// - localize handling of RelaxedPrecision
3697// - use the SPIR-V inferred type instead of another conversion of the glslang type
3698// (avoids unnecessary work and possible type punning for structures)
3699// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003700spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3701{
John Kessenich103bef92016-02-08 21:38:15 -07003702 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003703
3704 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3705 coherentFlags |= TranslateCoherent(type);
3706
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003707 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003708 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003709
John Kessenich5611c6d2018-04-05 11:25:02 -06003710 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003711 TranslateNonUniformDecoration(type.getQualifier()),
3712 nominalTypeId,
3713 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003714 TranslateMemoryScope(coherentFlags),
3715 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003716
3717 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003718 if (type.getBasicType() == glslang::EbtBool) {
3719 if (builder.isScalarType(nominalTypeId)) {
3720 // Conversion for bool
3721 spv::Id boolType = builder.makeBoolType();
3722 if (nominalTypeId != boolType)
3723 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3724 } else if (builder.isVectorType(nominalTypeId)) {
3725 // Conversion for bvec
3726 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3727 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3728 if (nominalTypeId != bvecType)
3729 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3730 }
3731 }
John Kessenich103bef92016-02-08 21:38:15 -07003732
3733 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003734}
3735
Rex Xu27253232016-02-23 17:51:09 +08003736// Wrap the builder's accessChainStore to:
3737// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003738//
3739// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003740void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3741{
3742 // Need to convert to abstract types when necessary
3743 if (type.getBasicType() == glslang::EbtBool) {
3744 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3745
3746 if (builder.isScalarType(nominalTypeId)) {
3747 // Conversion for bool
3748 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003749 if (nominalTypeId != boolType) {
3750 // keep these outside arguments, for determinant order-of-evaluation
3751 spv::Id one = builder.makeUintConstant(1);
3752 spv::Id zero = builder.makeUintConstant(0);
3753 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3754 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003755 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003756 } else if (builder.isVectorType(nominalTypeId)) {
3757 // Conversion for bvec
3758 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3759 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003760 if (nominalTypeId != bvecType) {
3761 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003762 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3763 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3764 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003765 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003766 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3767 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003768 }
3769 }
3770
Jeff Bolz36831c92018-09-05 10:11:41 -05003771 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3772 coherentFlags |= TranslateCoherent(type);
3773
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003774 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003775 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003776
Jeff Bolz36831c92018-09-05 10:11:41 -05003777 builder.accessChainStore(rvalue,
3778 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003779 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003780}
3781
John Kessenich4bf71552016-09-02 11:20:21 -06003782// For storing when types match at the glslang level, but not might match at the
3783// SPIR-V level.
3784//
3785// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003786// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003787// as in a member-decorated way.
3788//
3789// NOTE: This function can handle any store request; if it's not special it
3790// simplifies to a simple OpStore.
3791//
3792// Implicitly uses the existing builder.accessChain as the storage target.
3793void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3794{
John Kessenichb3e24e42016-09-11 12:33:43 -06003795 // we only do the complex path here if it's an aggregate
3796 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003797 accessChainStore(type, rValue);
3798 return;
3799 }
3800
John Kessenichb3e24e42016-09-11 12:33:43 -06003801 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003802 spv::Id rType = builder.getTypeId(rValue);
3803 spv::Id lValue = builder.accessChainGetLValue();
3804 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3805 if (lType == rType) {
3806 accessChainStore(type, rValue);
3807 return;
3808 }
3809
John Kessenichb3e24e42016-09-11 12:33:43 -06003810 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003811 // where the two types were the same type in GLSL. This requires member
3812 // by member copy, recursively.
3813
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003814 // SPIR-V 1.4 added an instruction to do help do this.
3815 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3816 // However, bool in uniform space is changed to int, so
3817 // OpCopyLogical does not work for that.
3818 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3819 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3820 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3821 if (lBool == rBool) {
3822 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3823 accessChainStore(type, logicalCopy);
3824 return;
3825 }
3826 }
3827
John Kessenichb3e24e42016-09-11 12:33:43 -06003828 // If an array, copy element by element.
3829 if (type.isArray()) {
3830 glslang::TType glslangElementType(type, 0);
3831 spv::Id elementRType = builder.getContainedTypeId(rType);
3832 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3833 // get the source member
3834 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003835
John Kessenichb3e24e42016-09-11 12:33:43 -06003836 // set up the target storage
3837 builder.clearAccessChain();
3838 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003839 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003840
John Kessenichb3e24e42016-09-11 12:33:43 -06003841 // store the member
3842 multiTypeStore(glslangElementType, elementRValue);
3843 }
3844 } else {
3845 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003846
John Kessenichb3e24e42016-09-11 12:33:43 -06003847 // loop over structure members
3848 const glslang::TTypeList& members = *type.getStruct();
3849 for (int m = 0; m < (int)members.size(); ++m) {
3850 const glslang::TType& glslangMemberType = *members[m].type;
3851
3852 // get the source member
3853 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3854 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3855
3856 // set up the target storage
3857 builder.clearAccessChain();
3858 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003859 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003860
3861 // store the member
3862 multiTypeStore(glslangMemberType, memberRValue);
3863 }
John Kessenich4bf71552016-09-02 11:20:21 -06003864 }
3865}
3866
John Kessenichf85e8062015-12-19 13:57:10 -07003867// Decide whether or not this type should be
3868// decorated with offsets and strides, and if so
3869// whether std140 or std430 rules should be applied.
3870glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003871{
John Kessenichf85e8062015-12-19 13:57:10 -07003872 // has to be a block
3873 if (type.getBasicType() != glslang::EbtBlock)
3874 return glslang::ElpNone;
3875
Chao Chen3c366992018-09-19 11:41:59 -07003876 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003877 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003878 type.getQualifier().storage != glslang::EvqBuffer &&
3879 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003880 return glslang::ElpNone;
3881
3882 // return the layout to use
3883 switch (type.getQualifier().layoutPacking) {
3884 case glslang::ElpStd140:
3885 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003886 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003887 return type.getQualifier().layoutPacking;
3888 default:
3889 return glslang::ElpNone;
3890 }
John Kessenich31ed4832015-09-09 17:51:38 -06003891}
3892
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003893// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003894int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003895{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003896 int size;
John Kessenich49987892015-12-29 17:11:44 -07003897 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003898 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003899
3900 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003901}
3902
John Kessenich49987892015-12-29 17:11:44 -07003903// 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 -07003904// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003905int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003906{
John Kessenich49987892015-12-29 17:11:44 -07003907 glslang::TType elementType;
3908 elementType.shallowCopy(matrixType);
3909 elementType.clearArraySizes();
3910
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003911 int size;
John Kessenich49987892015-12-29 17:11:44 -07003912 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003913 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003914
3915 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003916}
3917
John Kessenich5e4b1242015-08-06 22:53:06 -06003918// Given a member type of a struct, realign the current offset for it, and compute
3919// the next (not yet aligned) offset for the next member, which will get aligned
3920// on the next call.
3921// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3922// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3923// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003924void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003925 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003926{
3927 // this will get a positive value when deemed necessary
3928 nextOffset = -1;
3929
John Kessenich5e4b1242015-08-06 22:53:06 -06003930 // override anything in currentOffset with user-set offset
3931 if (memberType.getQualifier().hasOffset())
3932 currentOffset = memberType.getQualifier().layoutOffset;
3933
3934 // It could be that current linker usage in glslang updated all the layoutOffset,
3935 // in which case the following code does not matter. But, that's not quite right
3936 // once cross-compilation unit GLSL validation is done, as the original user
3937 // settings are needed in layoutOffset, and then the following will come into play.
3938
John Kessenichf85e8062015-12-19 13:57:10 -07003939 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003940 if (! memberType.getQualifier().hasOffset())
3941 currentOffset = -1;
3942
3943 return;
3944 }
3945
John Kessenichf85e8062015-12-19 13:57:10 -07003946 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003947 if (currentOffset < 0)
3948 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003949
John Kessenich5e4b1242015-08-06 22:53:06 -06003950 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3951 // but possibly not yet correctly aligned.
3952
3953 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003954 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003955 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003956
3957 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003958 // TODO: make this consistent in early phases of code:
3959 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3960 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3961 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003962 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003963 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003964 int dummySize;
3965 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3966 if (componentAlignment <= 4)
3967 memberAlignment = componentAlignment;
3968 }
3969
3970 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003971 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003972
3973 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003974 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003975 glslang::RoundToPow2(currentOffset, 16);
3976
John Kessenich5e4b1242015-08-06 22:53:06 -06003977 nextOffset = currentOffset + memberSize;
3978}
3979
David Netoa901ffe2016-06-08 14:11:40 +01003980void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003981{
David Netoa901ffe2016-06-08 14:11:40 +01003982 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3983 switch (glslangBuiltIn)
3984 {
3985 case glslang::EbvClipDistance:
3986 case glslang::EbvCullDistance:
3987 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003988#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003989 case glslang::EbvViewportMaskNV:
3990 case glslang::EbvSecondaryPositionNV:
3991 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003992 case glslang::EbvPositionPerViewNV:
3993 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003994 case glslang::EbvTaskCountNV:
3995 case glslang::EbvPrimitiveCountNV:
3996 case glslang::EbvPrimitiveIndicesNV:
3997 case glslang::EbvClipDistancePerViewNV:
3998 case glslang::EbvCullDistancePerViewNV:
3999 case glslang::EbvLayerPerViewNV:
4000 case glslang::EbvMeshViewCountNV:
4001 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08004002#endif
David Netoa901ffe2016-06-08 14:11:40 +01004003 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
4004 // Alternately, we could just call this for any glslang built-in, since the
4005 // capability already guards against duplicates.
4006 TranslateBuiltInDecoration(glslangBuiltIn, false);
4007 break;
4008 default:
4009 // Capabilities were already generated when the struct was declared.
4010 break;
4011 }
John Kessenichebb50532016-05-16 19:22:05 -06004012}
4013
John Kessenich6fccb3c2016-09-19 16:01:41 -06004014bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06004015{
John Kessenicheee9d532016-09-19 18:09:30 -06004016 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004017}
4018
John Kessenichd41993d2017-09-10 15:21:05 -06004019// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07004020// Assumes called after originalParam(), which filters out block/buffer/opaque-based
4021// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06004022bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06004023{
John Kessenich6a14f782017-12-04 02:48:10 -07004024 assert(qualifier == glslang::EvqIn ||
4025 qualifier == glslang::EvqOut ||
4026 qualifier == glslang::EvqInOut ||
4027 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06004028 return qualifier != glslang::EvqConstReadOnly;
4029}
4030
4031// Is parameter pass-by-original?
4032bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
4033 bool implicitThisParam)
4034{
4035 if (implicitThisParam) // implicit this
4036 return true;
4037 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07004038 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06004039 return paramType.containsOpaque() || // sampler, etc.
4040 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
4041}
4042
John Kessenich140f3df2015-06-26 16:58:36 -06004043// Make all the functions, skeletally, without actually visiting their bodies.
4044void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
4045{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004046 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06004047 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
4048 if (paramPrecision != spv::NoPrecision)
4049 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05004050 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004051 if (type.getBasicType() == glslang::EbtReference) {
4052 // Original and non-writable params pass the pointer directly and
4053 // use restrict/aliased, others are stored to a pointer in Function
4054 // memory and use RestrictPointer/AliasedPointer.
4055 if (originalParam(type.getQualifier().storage, type, false) ||
4056 !writableParam(type.getQualifier().storage)) {
4057 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
4058 } else {
4059 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
4060 }
4061 }
John Kessenichfad62972017-07-18 02:35:46 -06004062 };
4063
John Kessenich140f3df2015-06-26 16:58:36 -06004064 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4065 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06004066 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06004067 continue;
4068
4069 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06004070 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06004071 //
qining25262b32016-05-06 17:25:16 -04004072 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06004073 // function. What it is an address of varies:
4074 //
John Kessenich4bf71552016-09-02 11:20:21 -06004075 // - "in" parameters not marked as "const" can be written to without modifying the calling
4076 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06004077 //
4078 // - "const in" parameters can just be the r-value, as no writes need occur.
4079 //
John Kessenich4bf71552016-09-02 11:20:21 -06004080 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
4081 // 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 -06004082
4083 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06004084 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06004085 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
4086
John Kessenichfad62972017-07-18 02:35:46 -06004087 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
4088 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06004089
John Kessenichfad62972017-07-18 02:35:46 -06004090 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06004091 for (int p = 0; p < (int)parameters.size(); ++p) {
4092 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4093 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06004094 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06004095 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06004096 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06004097 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
4098 else
John Kessenich4bf71552016-09-02 11:20:21 -06004099 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05004100 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06004101 paramTypes.push_back(typeId);
4102 }
4103
4104 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004105 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4106 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004107 glslFunction->getName().c_str(), paramTypes,
4108 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004109 if (implicitThis)
4110 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004111
4112 // Track function to emit/call later
4113 functionMap[glslFunction->getName().c_str()] = function;
4114
4115 // Set the parameter id's
4116 for (int p = 0; p < (int)parameters.size(); ++p) {
4117 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4118 // give a name too
4119 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
Jeff Bolz2b2316d2019-02-17 22:49:28 -06004120
4121 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
4122 if (paramType.containsBasicType(glslang::EbtInt8) ||
4123 paramType.containsBasicType(glslang::EbtUint8))
4124 builder.addCapability(spv::CapabilityInt8);
4125 if (paramType.containsBasicType(glslang::EbtInt16) ||
4126 paramType.containsBasicType(glslang::EbtUint16))
4127 builder.addCapability(spv::CapabilityInt16);
4128 if (paramType.containsBasicType(glslang::EbtFloat16))
4129 builder.addCapability(spv::CapabilityFloat16);
John Kessenich140f3df2015-06-26 16:58:36 -06004130 }
4131 }
4132}
4133
4134// Process all the initializers, while skipping the functions and link objects
4135void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4136{
4137 builder.setBuildPoint(shaderEntry->getLastBlock());
4138 for (int i = 0; i < (int)initializers.size(); ++i) {
4139 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4140 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4141
4142 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004143 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004144 initializer->traverse(this);
4145 }
4146 }
4147}
4148
4149// Process all the functions, while skipping initializers.
4150void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4151{
4152 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4153 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004154 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004155 node->traverse(this);
4156 }
4157}
4158
4159void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4160{
qining25262b32016-05-06 17:25:16 -04004161 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004162 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004163 currentFunction = functionMap[node->getName().c_str()];
4164 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004165 builder.setBuildPoint(functionBlock);
4166}
4167
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004168void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments, spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06004169{
Rex Xufc618912015-09-09 16:42:49 +08004170 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004171
4172 glslang::TSampler sampler = {};
4173 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004174#ifdef AMD_EXTENSIONS
4175 bool f16ShadowCompare = false;
4176#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004177 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004178 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4179 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004180#ifdef AMD_EXTENSIONS
4181 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4182#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004183 }
4184
John Kessenich140f3df2015-06-26 16:58:36 -06004185 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4186 builder.clearAccessChain();
4187 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004188
4189 // Special case l-value operands
4190 bool lvalue = false;
4191 switch (node.getOp()) {
4192 case glslang::EOpImageAtomicAdd:
4193 case glslang::EOpImageAtomicMin:
4194 case glslang::EOpImageAtomicMax:
4195 case glslang::EOpImageAtomicAnd:
4196 case glslang::EOpImageAtomicOr:
4197 case glslang::EOpImageAtomicXor:
4198 case glslang::EOpImageAtomicExchange:
4199 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004200 case glslang::EOpImageAtomicLoad:
4201 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004202 if (i == 0)
4203 lvalue = true;
4204 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004205 case glslang::EOpSparseImageLoad:
4206 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4207 lvalue = true;
4208 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004209#ifdef AMD_EXTENSIONS
4210 case glslang::EOpSparseTexture:
4211 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4212 lvalue = true;
4213 break;
4214 case glslang::EOpSparseTextureClamp:
4215 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4216 lvalue = true;
4217 break;
4218 case glslang::EOpSparseTextureLod:
4219 case glslang::EOpSparseTextureOffset:
4220 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4221 lvalue = true;
4222 break;
4223#else
Rex Xu48edadf2015-12-31 16:11:41 +08004224 case glslang::EOpSparseTexture:
4225 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4226 lvalue = true;
4227 break;
4228 case glslang::EOpSparseTextureClamp:
4229 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4230 lvalue = true;
4231 break;
4232 case glslang::EOpSparseTextureLod:
4233 case glslang::EOpSparseTextureOffset:
4234 if (i == 3)
4235 lvalue = true;
4236 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004237#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004238 case glslang::EOpSparseTextureFetch:
4239 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4240 lvalue = true;
4241 break;
4242 case glslang::EOpSparseTextureFetchOffset:
4243 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4244 lvalue = true;
4245 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004246#ifdef AMD_EXTENSIONS
4247 case glslang::EOpSparseTextureLodOffset:
4248 case glslang::EOpSparseTextureGrad:
4249 case glslang::EOpSparseTextureOffsetClamp:
4250 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4251 lvalue = true;
4252 break;
4253 case glslang::EOpSparseTextureGradOffset:
4254 case glslang::EOpSparseTextureGradClamp:
4255 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4256 lvalue = true;
4257 break;
4258 case glslang::EOpSparseTextureGradOffsetClamp:
4259 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4260 lvalue = true;
4261 break;
4262#else
Rex Xu48edadf2015-12-31 16:11:41 +08004263 case glslang::EOpSparseTextureLodOffset:
4264 case glslang::EOpSparseTextureGrad:
4265 case glslang::EOpSparseTextureOffsetClamp:
4266 if (i == 4)
4267 lvalue = true;
4268 break;
4269 case glslang::EOpSparseTextureGradOffset:
4270 case glslang::EOpSparseTextureGradClamp:
4271 if (i == 5)
4272 lvalue = true;
4273 break;
4274 case glslang::EOpSparseTextureGradOffsetClamp:
4275 if (i == 6)
4276 lvalue = true;
4277 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004278#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004279 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004280 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4281 lvalue = true;
4282 break;
4283 case glslang::EOpSparseTextureGatherOffset:
4284 case glslang::EOpSparseTextureGatherOffsets:
4285 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4286 lvalue = true;
4287 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004288#ifdef AMD_EXTENSIONS
4289 case glslang::EOpSparseTextureGatherLod:
4290 if (i == 3)
4291 lvalue = true;
4292 break;
4293 case glslang::EOpSparseTextureGatherLodOffset:
4294 case glslang::EOpSparseTextureGatherLodOffsets:
4295 if (i == 4)
4296 lvalue = true;
4297 break;
Rex Xu129799a2017-07-05 17:23:28 +08004298 case glslang::EOpSparseImageLoadLod:
4299 if (i == 3)
4300 lvalue = true;
4301 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004302#endif
Chao Chen3a137962018-09-19 11:41:27 -07004303#ifdef NV_EXTENSIONS
4304 case glslang::EOpImageSampleFootprintNV:
4305 if (i == 4)
4306 lvalue = true;
4307 break;
4308 case glslang::EOpImageSampleFootprintClampNV:
4309 case glslang::EOpImageSampleFootprintLodNV:
4310 if (i == 5)
4311 lvalue = true;
4312 break;
4313 case glslang::EOpImageSampleFootprintGradNV:
4314 if (i == 6)
4315 lvalue = true;
4316 break;
4317 case glslang::EOpImageSampleFootprintGradClampNV:
4318 if (i == 7)
4319 lvalue = true;
4320 break;
4321#endif
Rex Xufc618912015-09-09 16:42:49 +08004322 default:
4323 break;
4324 }
4325
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004326 if (lvalue) {
Rex Xufc618912015-09-09 16:42:49 +08004327 arguments.push_back(builder.accessChainGetLValue());
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004328 lvalueCoherentFlags = builder.getAccessChain().coherentFlags;
4329 lvalueCoherentFlags |= TranslateCoherent(glslangArguments[i]->getAsTyped()->getType());
4330 } else
John Kessenich32cfd492016-02-02 12:37:46 -07004331 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004332 }
4333}
4334
John Kessenichfc51d282015-08-19 13:34:18 -06004335void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004336{
John Kessenichfc51d282015-08-19 13:34:18 -06004337 builder.clearAccessChain();
4338 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004339 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004340}
John Kessenich140f3df2015-06-26 16:58:36 -06004341
John Kessenichfc51d282015-08-19 13:34:18 -06004342spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4343{
John Kesseniche485c7a2017-05-31 18:50:53 -06004344 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004345 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004346
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004347 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004348
John Kessenichfc51d282015-08-19 13:34:18 -06004349 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004350
John Kessenichf43c7392019-03-31 10:51:57 -06004351 const glslang::TType &imageType = node->getAsAggregate()
4352 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4353 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004354 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004355#ifdef AMD_EXTENSIONS
4356 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004357 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4358 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004359#endif
4360
John Kessenichf43c7392019-03-31 10:51:57 -06004361 const auto signExtensionMask = [&]() {
4362 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4363 if (sampler.type == glslang::EbtUint)
4364 return spv::ImageOperandsZeroExtendMask;
4365 else if (sampler.type == glslang::EbtInt)
4366 return spv::ImageOperandsSignExtendMask;
4367 }
4368 return spv::ImageOperandsMaskNone;
4369 };
4370
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004371 spv::Builder::AccessChain::CoherentFlags lvalueCoherentFlags;
4372
John Kessenichfc51d282015-08-19 13:34:18 -06004373 std::vector<spv::Id> arguments;
4374 if (node->getAsAggregate())
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004375 translateArguments(*node->getAsAggregate(), arguments, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06004376 else
4377 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004378 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004379
4380 spv::Builder::TextureParameters params = { };
4381 params.sampler = arguments[0];
4382
Rex Xu04db3f52015-09-16 11:44:02 +08004383 glslang::TCrackedTextureOp cracked;
4384 node->crackTexture(sampler, cracked);
4385
amhagan05506bb2017-06-13 16:53:02 -04004386 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004387
John Kessenichfc51d282015-08-19 13:34:18 -06004388 // Check for queries
4389 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004390 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4391 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004392 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004393
John Kessenichfc51d282015-08-19 13:34:18 -06004394 switch (node->getOp()) {
4395 case glslang::EOpImageQuerySize:
4396 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004397 if (arguments.size() > 1) {
4398 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004399 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004400 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004401 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004402 case glslang::EOpImageQuerySamples:
4403 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004404 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004405 case glslang::EOpTextureQueryLod:
4406 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004407 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004408 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004409 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004410 case glslang::EOpSparseTexelsResident:
4411 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004412 default:
4413 assert(0);
4414 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004415 }
John Kessenich140f3df2015-06-26 16:58:36 -06004416 }
4417
LoopDawg4425f242018-02-18 11:40:01 -07004418 int components = node->getType().getVectorSize();
4419
4420 if (node->getOp() == glslang::EOpTextureFetch) {
4421 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4422 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4423 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4424 // here around e.g. which ones return scalars or other types.
4425 components = 4;
4426 }
4427
4428 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4429
4430 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4431
Rex Xufc618912015-09-09 16:42:49 +08004432 // Check for image functions other than queries
4433 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004434 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004435 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004436 spv::IdImmediate image = { true, *(opIt++) };
4437 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004438
4439 // Handle subpass operations
4440 // TODO: GLSL should change to have the "MS" only on the type rather than the
4441 // built-in function.
4442 if (cracked.subpass) {
4443 // add on the (0,0) coordinate
4444 spv::Id zero = builder.makeIntConstant(0);
4445 std::vector<spv::Id> comps;
4446 comps.push_back(zero);
4447 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004448 spv::IdImmediate coord = { true,
4449 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4450 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004451 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4452 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich6c292d32016-02-15 20:58:50 -07004453 if (sampler.ms) {
John Kessenichf43c7392019-03-31 10:51:57 -06004454 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4455 }
4456 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004457 operands.push_back(imageOperands);
John Kessenichf43c7392019-03-31 10:51:57 -06004458 if (sampler.ms) {
4459 spv::IdImmediate imageOperand = { true, *(opIt++) };
4460 operands.push_back(imageOperand);
4461 }
John Kessenich6c292d32016-02-15 20:58:50 -07004462 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004463 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4464 builder.setPrecision(result, precision);
4465 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004466 }
4467
John Kessenich149afc32018-08-14 13:31:43 -06004468 spv::IdImmediate coord = { true, *(opIt++) };
4469 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004470#ifdef AMD_EXTENSIONS
4471 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4472#else
John Kessenich56bab042015-09-16 10:54:31 -06004473 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004474#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004475 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004476 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004477 mask = mask | spv::ImageOperandsSampleMask;
4478 }
Rex Xu129799a2017-07-05 17:23:28 +08004479#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004480 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004481 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4482 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004483 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004484 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004485#endif
4486 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4487 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004488 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004489 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004490 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4491 operands.push_back(imageOperands);
4492 }
4493 if (mask & spv::ImageOperandsSampleMask) {
4494 spv::IdImmediate imageOperand = { true, *opIt++ };
4495 operands.push_back(imageOperand);
4496 }
4497#ifdef AMD_EXTENSIONS
4498 if (mask & spv::ImageOperandsLodMask) {
4499 spv::IdImmediate imageOperand = { true, *opIt++ };
4500 operands.push_back(imageOperand);
4501 }
4502#endif
4503 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004504 spv::IdImmediate imageOperand = { true,
4505 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004506 operands.push_back(imageOperand);
4507 }
4508
John Kessenich149afc32018-08-14 13:31:43 -06004509 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004510 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004511
John Kessenich149afc32018-08-14 13:31:43 -06004512 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004513 builder.setPrecision(result[0], precision);
4514
4515 // If needed, add a conversion constructor to the proper size.
4516 if (components != node->getType().getVectorSize())
4517 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4518
4519 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004520#ifdef AMD_EXTENSIONS
4521 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4522#else
John Kessenich56bab042015-09-16 10:54:31 -06004523 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004524#endif
Rex Xu129799a2017-07-05 17:23:28 +08004525
Jeff Bolz36831c92018-09-05 10:11:41 -05004526 // Push the texel value before the operands
4527#ifdef AMD_EXTENSIONS
4528 if (sampler.ms || cracked.lod) {
4529#else
4530 if (sampler.ms) {
4531#endif
John Kessenich149afc32018-08-14 13:31:43 -06004532 spv::IdImmediate texel = { true, *(opIt + 1) };
4533 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004534 } else {
4535 spv::IdImmediate texel = { true, *opIt };
4536 operands.push_back(texel);
4537 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004538
4539 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4540 if (sampler.ms) {
4541 mask = mask | spv::ImageOperandsSampleMask;
4542 }
4543#ifdef AMD_EXTENSIONS
4544 if (cracked.lod) {
4545 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4546 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4547 mask = mask | spv::ImageOperandsLodMask;
4548 }
4549#endif
4550 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4551 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004552 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004553 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004554 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4555 operands.push_back(imageOperands);
4556 }
4557 if (mask & spv::ImageOperandsSampleMask) {
4558 spv::IdImmediate imageOperand = { true, *opIt++ };
4559 operands.push_back(imageOperand);
4560 }
4561#ifdef AMD_EXTENSIONS
4562 if (mask & spv::ImageOperandsLodMask) {
4563 spv::IdImmediate imageOperand = { true, *opIt++ };
4564 operands.push_back(imageOperand);
4565 }
4566#endif
4567 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004568 spv::IdImmediate imageOperand = { true,
4569 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004570 operands.push_back(imageOperand);
4571 }
4572
John Kessenich56bab042015-09-16 10:54:31 -06004573 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004574 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004575 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004576 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004577#ifdef AMD_EXTENSIONS
John Kessenichf43c7392019-03-31 10:51:57 -06004578 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4579 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004580#else
Rex Xu5eafa472016-02-19 22:24:03 +08004581 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004582#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004583 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004584 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004585 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4586
Jeff Bolz36831c92018-09-05 10:11:41 -05004587 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004588 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004589 mask = mask | spv::ImageOperandsSampleMask;
4590 }
Rex Xu129799a2017-07-05 17:23:28 +08004591#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004592 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004593 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4594 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4595
Jeff Bolz36831c92018-09-05 10:11:41 -05004596 mask = mask | spv::ImageOperandsLodMask;
4597 }
4598#endif
4599 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4600 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004601 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004602 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004603 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004604 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004605 }
4606 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004607 spv::IdImmediate imageOperand = { true, *opIt++ };
4608 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004609 }
4610#ifdef AMD_EXTENSIONS
4611 if (mask & spv::ImageOperandsLodMask) {
4612 spv::IdImmediate imageOperand = { true, *opIt++ };
4613 operands.push_back(imageOperand);
4614 }
Rex Xu129799a2017-07-05 17:23:28 +08004615#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004616 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4617 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4618 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004619 }
4620
4621 // Create the return type that was a special structure
4622 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004623 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004624 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4625 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4626
4627 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4628
4629 // Decode the return type
4630 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4631 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004632 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004633 // Process image atomic operations
4634
4635 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4636 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004637 // For non-MS, the sample value should be 0
4638 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4639 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004640
Jeff Bolz36831c92018-09-05 10:11:41 -05004641 spv::Id resultTypeId;
4642 // imageAtomicStore has a void return type so base the pointer type on
4643 // the type of the value operand.
4644 if (node->getOp() == glslang::EOpImageAtomicStore) {
4645 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4646 } else {
4647 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4648 }
John Kessenich56bab042015-09-16 10:54:31 -06004649 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004650
4651 std::vector<spv::Id> operands;
4652 operands.push_back(pointer);
4653 for (; opIt != arguments.end(); ++opIt)
4654 operands.push_back(*opIt);
4655
Jeff Bolz38a52fc2019-06-14 09:56:28 -05004656 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType(), lvalueCoherentFlags);
Rex Xufc618912015-09-09 16:42:49 +08004657 }
4658 }
4659
amhagan05506bb2017-06-13 16:53:02 -04004660#ifdef AMD_EXTENSIONS
4661 // Check for fragment mask functions other than queries
4662 if (cracked.fragMask) {
4663 assert(sampler.ms);
4664
4665 auto opIt = arguments.begin();
4666 std::vector<spv::Id> operands;
4667
4668 // Extract the image if necessary
4669 if (builder.isSampledImage(params.sampler))
4670 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4671
4672 operands.push_back(params.sampler);
4673 ++opIt;
4674
4675 if (sampler.isSubpass()) {
4676 // add on the (0,0) coordinate
4677 spv::Id zero = builder.makeIntConstant(0);
4678 std::vector<spv::Id> comps;
4679 comps.push_back(zero);
4680 comps.push_back(zero);
4681 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4682 }
4683
4684 for (; opIt != arguments.end(); ++opIt)
4685 operands.push_back(*opIt);
4686
4687 spv::Op fragMaskOp = spv::OpNop;
4688 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4689 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4690 else if (node->getOp() == glslang::EOpFragmentFetch)
4691 fragMaskOp = spv::OpFragmentFetchAMD;
4692
4693 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4694 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4695 return builder.createOp(fragMaskOp, resultType(), operands);
4696 }
4697#endif
4698
Rex Xufc618912015-09-09 16:42:49 +08004699 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004700 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004701#ifdef NV_EXTENSIONS
4702 bool imageFootprint = node->isImageFootprint();
4703#endif
4704
Rex Xu71519fe2015-11-11 15:35:47 +08004705 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4706
John Kessenichfc51d282015-08-19 13:34:18 -06004707 // check for bias argument
4708 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004709#ifdef AMD_EXTENSIONS
4710 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4711#else
Rex Xu71519fe2015-11-11 15:35:47 +08004712 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004713#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004714 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004715#ifdef AMD_EXTENSIONS
4716 if (cracked.gather)
4717 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004718
4719 if (f16ShadowCompare)
4720 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004721#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004722 if (cracked.offset)
4723 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004724#ifdef AMD_EXTENSIONS
4725 else if (cracked.offsets)
4726 ++nonBiasArgCount;
4727#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004728 if (cracked.grad)
4729 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004730 if (cracked.lodClamp)
4731 ++nonBiasArgCount;
4732 if (sparse)
4733 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004734#ifdef NV_EXTENSIONS
4735 if (imageFootprint)
4736 //Following three extra arguments
4737 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4738 nonBiasArgCount += 3;
4739#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004740 if ((int)arguments.size() > nonBiasArgCount)
4741 bias = true;
4742 }
4743
John Kessenicha5c33d62016-06-02 23:45:21 -06004744 // See if the sampler param should really be just the SPV image part
4745 if (cracked.fetch) {
4746 // a fetch needs to have the image extracted first
4747 if (builder.isSampledImage(params.sampler))
4748 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4749 }
4750
Rex Xu225e0fc2016-11-17 17:47:59 +08004751#ifdef AMD_EXTENSIONS
4752 if (cracked.gather) {
4753 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4754 if (bias || cracked.lod ||
4755 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4756 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004757 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004758 }
4759 }
4760#endif
4761
John Kessenichfc51d282015-08-19 13:34:18 -06004762 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004763
John Kessenichfc51d282015-08-19 13:34:18 -06004764 params.coords = arguments[1];
4765 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004766 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004767
4768 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004769#ifdef AMD_EXTENSIONS
4770 if (cubeCompare || f16ShadowCompare) {
4771#else
Rex Xu48edadf2015-12-31 16:11:41 +08004772 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004773#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004774 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004775 ++extraArgs;
4776 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004777 params.Dref = arguments[2];
4778 ++extraArgs;
4779 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004780 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004781 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004782 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004783 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004784 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004785 dRefComp = builder.getNumComponents(params.coords) - 1;
4786 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004787 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4788 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004789
4790 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004791 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004792 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004793 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004794 } else if (glslangIntermediate->getStage() != EShLangFragment
4795#ifdef NV_EXTENSIONS
4796 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4797 && !(glslangIntermediate->getStage() == EShLangCompute &&
4798 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4799#endif
4800 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004801 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4802 noImplicitLod = true;
4803 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004804
4805 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004806 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004807 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004808 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004809 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004810
4811 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004812 if (cracked.grad) {
4813 params.gradX = arguments[2 + extraArgs];
4814 params.gradY = arguments[3 + extraArgs];
4815 extraArgs += 2;
4816 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004817
4818 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004819 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004820 params.offset = arguments[2 + extraArgs];
4821 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004822 } else if (cracked.offsets) {
4823 params.offsets = arguments[2 + extraArgs];
4824 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004825 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004826
4827 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004828 if (cracked.lodClamp) {
4829 params.lodClamp = arguments[2 + extraArgs];
4830 ++extraArgs;
4831 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004832 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004833 if (sparse) {
4834 params.texelOut = arguments[2 + extraArgs];
4835 ++extraArgs;
4836 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004837
John Kessenich76d4dfc2016-06-16 12:43:23 -06004838 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004839 if (cracked.gather && ! sampler.shadow) {
4840 // default component is 0, if missing, otherwise an argument
4841 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004842 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004843 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004844 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004845 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004846 }
Chao Chen3a137962018-09-19 11:41:27 -07004847#ifdef NV_EXTENSIONS
4848 spv::Id resultStruct = spv::NoResult;
4849 if (imageFootprint) {
4850 //Following three extra arguments
4851 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4852 params.granularity = arguments[2 + extraArgs];
4853 params.coarse = arguments[3 + extraArgs];
4854 resultStruct = arguments[4 + extraArgs];
4855 extraArgs += 3;
4856 }
4857#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004858 // bias
4859 if (bias) {
4860 params.bias = arguments[2 + extraArgs];
4861 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004862 }
John Kessenichfc51d282015-08-19 13:34:18 -06004863
Chao Chen3a137962018-09-19 11:41:27 -07004864#ifdef NV_EXTENSIONS
4865 if (imageFootprint) {
4866 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4867 builder.addCapability(spv::CapabilityImageFootprintNV);
4868
4869
4870 //resultStructType(OpenGL type) contains 5 elements:
4871 //struct gl_TextureFootprint2DNV {
4872 // uvec2 anchor;
4873 // uvec2 offset;
4874 // uvec2 mask;
4875 // uint lod;
4876 // uint granularity;
4877 //};
4878 //or
4879 //struct gl_TextureFootprint3DNV {
4880 // uvec3 anchor;
4881 // uvec3 offset;
4882 // uvec2 mask;
4883 // uint lod;
4884 // uint granularity;
4885 //};
4886 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4887 assert(builder.isStructType(resultStructType));
4888
4889 //resType (SPIR-V type) contains 6 elements:
4890 //Member 0 must be a Boolean type scalar(LOD),
4891 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4892 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4893 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4894 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4895 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4896 std::vector<spv::Id> members;
4897 members.push_back(resultType());
4898 for (int i = 0; i < 5; i++) {
4899 members.push_back(builder.getContainedTypeId(resultStructType, i));
4900 }
4901 spv::Id resType = builder.makeStructType(members, "ResType");
4902
4903 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004904 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4905 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004906
4907 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4908 for (int i = 0; i < 5; i++) {
4909 builder.clearAccessChain();
4910 builder.setAccessChainLValue(resultStruct);
4911
4912 //Accessing to a struct we created, no coherent flag is set
4913 spv::Builder::AccessChain::CoherentFlags flags;
4914 flags.clear();
4915
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004916 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004917 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4918 }
4919 return builder.createCompositeExtract(res, resultType(), 0);
4920 }
4921#endif
4922
John Kessenich65336482016-06-16 14:06:26 -06004923 // projective component (might not to move)
4924 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4925 // are divided by the last component of P."
4926 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4927 // unused components will appear after all used components."
4928 if (cracked.proj) {
4929 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4930 int projTargetComp;
4931 switch (sampler.dim) {
4932 case glslang::Esd1D: projTargetComp = 1; break;
4933 case glslang::Esd2D: projTargetComp = 2; break;
4934 case glslang::EsdRect: projTargetComp = 2; break;
4935 default: projTargetComp = projSourceComp; break;
4936 }
4937 // copy the projective coordinate if we have to
4938 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004939 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004940 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4941 projSourceComp);
4942 params.coords = builder.createCompositeInsert(projComp, params.coords,
4943 builder.getTypeId(params.coords), projTargetComp);
4944 }
4945 }
4946
Jeff Bolz36831c92018-09-05 10:11:41 -05004947 // nonprivate
4948 if (imageType.getQualifier().nonprivate) {
4949 params.nonprivate = true;
4950 }
4951
4952 // volatile
4953 if (imageType.getQualifier().volatil) {
4954 params.volatil = true;
4955 }
4956
St0fFa1184dd2018-04-09 21:08:14 +02004957 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004958 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4959 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004960 );
LoopDawg4425f242018-02-18 11:40:01 -07004961
4962 if (components != node->getType().getVectorSize())
4963 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4964
4965 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004966}
4967
4968spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4969{
4970 // Grab the function's pointer from the previously created function
4971 spv::Function* function = functionMap[node->getName().c_str()];
4972 if (! function)
4973 return 0;
4974
4975 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4976 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4977
4978 // See comments in makeFunctions() for details about the semantics for parameter passing.
4979 //
4980 // These imply we need a four step process:
4981 // 1. Evaluate the arguments
4982 // 2. Allocate and make copies of in, out, and inout arguments
4983 // 3. Make the call
4984 // 4. Copy back the results
4985
John Kessenichd3ed90b2018-05-04 11:43:03 -06004986 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004987 std::vector<spv::Builder::AccessChain> lValues;
4988 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004989 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004990 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004991 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004992 // build l-value
4993 builder.clearAccessChain();
4994 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004995 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004996 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004997 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004998 // save l-value
4999 lValues.push_back(builder.getAccessChain());
5000 } else {
5001 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07005002 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06005003 }
5004 }
5005
5006 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
5007 // copy the original into that space.
5008 //
5009 // Also, build up the list of actual arguments to pass in for the call
5010 int lValueCount = 0;
5011 int rValueCount = 0;
5012 std::vector<spv::Id> spvArgs;
5013 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
5014 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06005015 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07005016 builder.setAccessChain(lValues[lValueCount]);
5017 arg = builder.accessChainGetLValue();
5018 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06005019 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005020 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06005021 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06005022 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
5023 // need to copy the input into output space
5024 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07005025 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06005026 builder.clearAccessChain();
5027 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005028 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005029 }
5030 ++lValueCount;
5031 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005032 // process r-value, which involves a copy for a type mismatch
5033 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
5034 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
5035 builder.clearAccessChain();
5036 builder.setAccessChainLValue(argCopy);
5037 multiTypeStore(*argTypes[a], rValues[rValueCount]);
5038 arg = builder.createLoad(argCopy);
5039 } else
5040 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06005041 ++rValueCount;
5042 }
5043 spvArgs.push_back(arg);
5044 }
5045
5046 // 3. Make the call.
5047 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07005048 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06005049
5050 // 4. Copy back out an "out" arguments.
5051 lValueCount = 0;
5052 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06005053 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06005054 ++lValueCount;
5055 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06005056 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
5057 spv::Id copy = builder.createLoad(spvArgs[a]);
5058 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06005059 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06005060 }
5061 ++lValueCount;
5062 }
5063 }
5064
5065 return result;
5066}
5067
5068// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06005069spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06005070 spv::Id typeId, spv::Id left, spv::Id right,
5071 glslang::TBasicType typeProxy, bool reduceComparison)
5072{
John Kessenich66011cb2018-03-06 16:12:04 -07005073 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5074 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08005075 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06005076
5077 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06005078 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06005079 bool comparison = false;
5080
5081 switch (op) {
5082 case glslang::EOpAdd:
5083 case glslang::EOpAddAssign:
5084 if (isFloat)
5085 binOp = spv::OpFAdd;
5086 else
5087 binOp = spv::OpIAdd;
5088 break;
5089 case glslang::EOpSub:
5090 case glslang::EOpSubAssign:
5091 if (isFloat)
5092 binOp = spv::OpFSub;
5093 else
5094 binOp = spv::OpISub;
5095 break;
5096 case glslang::EOpMul:
5097 case glslang::EOpMulAssign:
5098 if (isFloat)
5099 binOp = spv::OpFMul;
5100 else
5101 binOp = spv::OpIMul;
5102 break;
5103 case glslang::EOpVectorTimesScalar:
5104 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06005105 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06005106 if (builder.isVector(right))
5107 std::swap(left, right);
5108 assert(builder.isScalar(right));
5109 needMatchingVectors = false;
5110 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01005111 } else if (isFloat)
5112 binOp = spv::OpFMul;
5113 else
John Kessenichec43d0a2015-07-04 17:17:31 -06005114 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06005115 break;
5116 case glslang::EOpVectorTimesMatrix:
5117 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005118 binOp = spv::OpVectorTimesMatrix;
5119 break;
5120 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005121 binOp = spv::OpMatrixTimesVector;
5122 break;
5123 case glslang::EOpMatrixTimesScalar:
5124 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005125 binOp = spv::OpMatrixTimesScalar;
5126 break;
5127 case glslang::EOpMatrixTimesMatrix:
5128 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005129 binOp = spv::OpMatrixTimesMatrix;
5130 break;
5131 case glslang::EOpOuterProduct:
5132 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005133 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005134 break;
5135
5136 case glslang::EOpDiv:
5137 case glslang::EOpDivAssign:
5138 if (isFloat)
5139 binOp = spv::OpFDiv;
5140 else if (isUnsigned)
5141 binOp = spv::OpUDiv;
5142 else
5143 binOp = spv::OpSDiv;
5144 break;
5145 case glslang::EOpMod:
5146 case glslang::EOpModAssign:
5147 if (isFloat)
5148 binOp = spv::OpFMod;
5149 else if (isUnsigned)
5150 binOp = spv::OpUMod;
5151 else
5152 binOp = spv::OpSMod;
5153 break;
5154 case glslang::EOpRightShift:
5155 case glslang::EOpRightShiftAssign:
5156 if (isUnsigned)
5157 binOp = spv::OpShiftRightLogical;
5158 else
5159 binOp = spv::OpShiftRightArithmetic;
5160 break;
5161 case glslang::EOpLeftShift:
5162 case glslang::EOpLeftShiftAssign:
5163 binOp = spv::OpShiftLeftLogical;
5164 break;
5165 case glslang::EOpAnd:
5166 case glslang::EOpAndAssign:
5167 binOp = spv::OpBitwiseAnd;
5168 break;
5169 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005170 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005171 binOp = spv::OpLogicalAnd;
5172 break;
5173 case glslang::EOpInclusiveOr:
5174 case glslang::EOpInclusiveOrAssign:
5175 binOp = spv::OpBitwiseOr;
5176 break;
5177 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005178 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005179 binOp = spv::OpLogicalOr;
5180 break;
5181 case glslang::EOpExclusiveOr:
5182 case glslang::EOpExclusiveOrAssign:
5183 binOp = spv::OpBitwiseXor;
5184 break;
5185 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005186 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005187 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005188 break;
5189
5190 case glslang::EOpLessThan:
5191 case glslang::EOpGreaterThan:
5192 case glslang::EOpLessThanEqual:
5193 case glslang::EOpGreaterThanEqual:
5194 case glslang::EOpEqual:
5195 case glslang::EOpNotEqual:
5196 case glslang::EOpVectorEqual:
5197 case glslang::EOpVectorNotEqual:
5198 comparison = true;
5199 break;
5200 default:
5201 break;
5202 }
5203
John Kessenich7c1aa102015-10-15 13:29:11 -06005204 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005205 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005206 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005207 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5208 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005209 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005210
5211 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005212 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005213 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005214
qining25262b32016-05-06 17:25:16 -04005215 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005216 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005217 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005218 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005219 }
5220
5221 if (! comparison)
5222 return 0;
5223
John Kessenich7c1aa102015-10-15 13:29:11 -06005224 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005225
John Kessenich4583b612016-08-07 19:14:22 -06005226 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005227 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5228 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06005229 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005230 return result;
5231 }
John Kessenich140f3df2015-06-26 16:58:36 -06005232
5233 switch (op) {
5234 case glslang::EOpLessThan:
5235 if (isFloat)
5236 binOp = spv::OpFOrdLessThan;
5237 else if (isUnsigned)
5238 binOp = spv::OpULessThan;
5239 else
5240 binOp = spv::OpSLessThan;
5241 break;
5242 case glslang::EOpGreaterThan:
5243 if (isFloat)
5244 binOp = spv::OpFOrdGreaterThan;
5245 else if (isUnsigned)
5246 binOp = spv::OpUGreaterThan;
5247 else
5248 binOp = spv::OpSGreaterThan;
5249 break;
5250 case glslang::EOpLessThanEqual:
5251 if (isFloat)
5252 binOp = spv::OpFOrdLessThanEqual;
5253 else if (isUnsigned)
5254 binOp = spv::OpULessThanEqual;
5255 else
5256 binOp = spv::OpSLessThanEqual;
5257 break;
5258 case glslang::EOpGreaterThanEqual:
5259 if (isFloat)
5260 binOp = spv::OpFOrdGreaterThanEqual;
5261 else if (isUnsigned)
5262 binOp = spv::OpUGreaterThanEqual;
5263 else
5264 binOp = spv::OpSGreaterThanEqual;
5265 break;
5266 case glslang::EOpEqual:
5267 case glslang::EOpVectorEqual:
5268 if (isFloat)
5269 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005270 else if (isBool)
5271 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005272 else
5273 binOp = spv::OpIEqual;
5274 break;
5275 case glslang::EOpNotEqual:
5276 case glslang::EOpVectorNotEqual:
5277 if (isFloat)
5278 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005279 else if (isBool)
5280 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005281 else
5282 binOp = spv::OpINotEqual;
5283 break;
5284 default:
5285 break;
5286 }
5287
qining25262b32016-05-06 17:25:16 -04005288 if (binOp != spv::OpNop) {
5289 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005290 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005291 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005292 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005293 }
John Kessenich140f3df2015-06-26 16:58:36 -06005294
5295 return 0;
5296}
5297
John Kessenich04bb8a02015-12-12 12:28:14 -07005298//
5299// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5300// These can be any of:
5301//
5302// matrix * scalar
5303// scalar * matrix
5304// matrix * matrix linear algebraic
5305// matrix * vector
5306// vector * matrix
5307// matrix * matrix componentwise
5308// matrix op matrix op in {+, -, /}
5309// matrix op scalar op in {+, -, /}
5310// scalar op matrix op in {+, -, /}
5311//
John Kessenichead86222018-03-28 18:01:20 -06005312spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5313 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005314{
5315 bool firstClass = true;
5316
5317 // First, handle first-class matrix operations (* and matrix/scalar)
5318 switch (op) {
5319 case spv::OpFDiv:
5320 if (builder.isMatrix(left) && builder.isScalar(right)) {
5321 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005322 spv::Id resultType = builder.getTypeId(right);
5323 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005324 op = spv::OpMatrixTimesScalar;
5325 } else
5326 firstClass = false;
5327 break;
5328 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005329 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005330 std::swap(left, right);
5331 assert(builder.isScalar(right));
5332 break;
5333 case spv::OpVectorTimesMatrix:
5334 assert(builder.isVector(left));
5335 assert(builder.isMatrix(right));
5336 break;
5337 case spv::OpMatrixTimesVector:
5338 assert(builder.isMatrix(left));
5339 assert(builder.isVector(right));
5340 break;
5341 case spv::OpMatrixTimesMatrix:
5342 assert(builder.isMatrix(left));
5343 assert(builder.isMatrix(right));
5344 break;
5345 default:
5346 firstClass = false;
5347 break;
5348 }
5349
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005350 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5351 firstClass = true;
5352
qining25262b32016-05-06 17:25:16 -04005353 if (firstClass) {
5354 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005355 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005356 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005357 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005358 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005359
LoopDawg592860c2016-06-09 08:57:35 -06005360 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005361 // The result type of all of them is the same type as the (a) matrix operand.
5362 // The algorithm is to:
5363 // - break the matrix(es) into vectors
5364 // - smear any scalar to a vector
5365 // - do vector operations
5366 // - make a matrix out the vector results
5367 switch (op) {
5368 case spv::OpFAdd:
5369 case spv::OpFSub:
5370 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005371 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005372 case spv::OpFMul:
5373 {
5374 // one time set up...
5375 bool leftMat = builder.isMatrix(left);
5376 bool rightMat = builder.isMatrix(right);
5377 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5378 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5379 spv::Id scalarType = builder.getScalarTypeId(typeId);
5380 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5381 std::vector<spv::Id> results;
5382 spv::Id smearVec = spv::NoResult;
5383 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005384 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005385 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005386 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005387
5388 // do each vector op
5389 for (unsigned int c = 0; c < numCols; ++c) {
5390 std::vector<unsigned int> indexes;
5391 indexes.push_back(c);
5392 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5393 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005394 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005395 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005396 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005397 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005398 }
5399
5400 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005401 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005402 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005403 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005404 }
5405 default:
5406 assert(0);
5407 return spv::NoResult;
5408 }
5409}
5410
John Kessenichead86222018-03-28 18:01:20 -06005411spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005412 spv::Id operand, glslang::TBasicType typeProxy, const spv::Builder::AccessChain::CoherentFlags &lvalueCoherentFlags)
John Kessenich140f3df2015-06-26 16:58:36 -06005413{
5414 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005415 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005416 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005417 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5418 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005419
5420 switch (op) {
5421 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005422 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005423 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005424 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005425 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005426 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005427 unaryOp = spv::OpSNegate;
5428 break;
5429
5430 case glslang::EOpLogicalNot:
5431 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005432 unaryOp = spv::OpLogicalNot;
5433 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005434 case glslang::EOpBitwiseNot:
5435 unaryOp = spv::OpNot;
5436 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005437
John Kessenich140f3df2015-06-26 16:58:36 -06005438 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005439 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005440 break;
5441 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005442 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005443 break;
5444 case glslang::EOpTranspose:
5445 unaryOp = spv::OpTranspose;
5446 break;
5447
5448 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005449 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005450 break;
5451 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005452 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005453 break;
5454 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005455 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005456 break;
5457 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005458 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005459 break;
5460 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005461 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005462 break;
5463 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005464 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005465 break;
5466 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005467 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005468 break;
5469 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005470 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005471 break;
5472
5473 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005474 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005475 break;
5476 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005477 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005478 break;
5479 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005480 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005481 break;
5482 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005483 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005484 break;
5485 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005486 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005487 break;
5488 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005489 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005490 break;
5491
5492 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005493 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005494 break;
5495 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005496 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005497 break;
5498
5499 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005500 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005501 break;
5502 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005503 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005504 break;
5505 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005506 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005507 break;
5508 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005509 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005510 break;
5511 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005512 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005513 break;
5514 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005515 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005516 break;
5517
5518 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005519 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005520 break;
5521 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005522 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005523 break;
5524 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005525 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005526 break;
5527 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005528 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005529 break;
5530 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005531 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005532 break;
5533 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005534 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005535 break;
5536
5537 case glslang::EOpIsNan:
5538 unaryOp = spv::OpIsNan;
5539 break;
5540 case glslang::EOpIsInf:
5541 unaryOp = spv::OpIsInf;
5542 break;
LoopDawg592860c2016-06-09 08:57:35 -06005543 case glslang::EOpIsFinite:
5544 unaryOp = spv::OpIsFinite;
5545 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005546
Rex Xucbc426e2015-12-15 16:03:10 +08005547 case glslang::EOpFloatBitsToInt:
5548 case glslang::EOpFloatBitsToUint:
5549 case glslang::EOpIntBitsToFloat:
5550 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005551 case glslang::EOpDoubleBitsToInt64:
5552 case glslang::EOpDoubleBitsToUint64:
5553 case glslang::EOpInt64BitsToDouble:
5554 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005555 case glslang::EOpFloat16BitsToInt16:
5556 case glslang::EOpFloat16BitsToUint16:
5557 case glslang::EOpInt16BitsToFloat16:
5558 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005559 unaryOp = spv::OpBitcast;
5560 break;
5561
John Kessenich140f3df2015-06-26 16:58:36 -06005562 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005563 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005564 break;
5565 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005566 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005567 break;
5568 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005569 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005570 break;
5571 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005572 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005573 break;
5574 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005575 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005576 break;
5577 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005578 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005579 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005580 case glslang::EOpPackSnorm4x8:
5581 libCall = spv::GLSLstd450PackSnorm4x8;
5582 break;
5583 case glslang::EOpUnpackSnorm4x8:
5584 libCall = spv::GLSLstd450UnpackSnorm4x8;
5585 break;
5586 case glslang::EOpPackUnorm4x8:
5587 libCall = spv::GLSLstd450PackUnorm4x8;
5588 break;
5589 case glslang::EOpUnpackUnorm4x8:
5590 libCall = spv::GLSLstd450UnpackUnorm4x8;
5591 break;
5592 case glslang::EOpPackDouble2x32:
5593 libCall = spv::GLSLstd450PackDouble2x32;
5594 break;
5595 case glslang::EOpUnpackDouble2x32:
5596 libCall = spv::GLSLstd450UnpackDouble2x32;
5597 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005598
Rex Xu8ff43de2016-04-22 16:51:45 +08005599 case glslang::EOpPackInt2x32:
5600 case glslang::EOpUnpackInt2x32:
5601 case glslang::EOpPackUint2x32:
5602 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005603 case glslang::EOpPack16:
5604 case glslang::EOpPack32:
5605 case glslang::EOpPack64:
5606 case glslang::EOpUnpack32:
5607 case glslang::EOpUnpack16:
5608 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005609 case glslang::EOpPackInt2x16:
5610 case glslang::EOpUnpackInt2x16:
5611 case glslang::EOpPackUint2x16:
5612 case glslang::EOpUnpackUint2x16:
5613 case glslang::EOpPackInt4x16:
5614 case glslang::EOpUnpackInt4x16:
5615 case glslang::EOpPackUint4x16:
5616 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005617 case glslang::EOpPackFloat2x16:
5618 case glslang::EOpUnpackFloat2x16:
5619 unaryOp = spv::OpBitcast;
5620 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005621
John Kessenich140f3df2015-06-26 16:58:36 -06005622 case glslang::EOpDPdx:
5623 unaryOp = spv::OpDPdx;
5624 break;
5625 case glslang::EOpDPdy:
5626 unaryOp = spv::OpDPdy;
5627 break;
5628 case glslang::EOpFwidth:
5629 unaryOp = spv::OpFwidth;
5630 break;
5631 case glslang::EOpDPdxFine:
5632 unaryOp = spv::OpDPdxFine;
5633 break;
5634 case glslang::EOpDPdyFine:
5635 unaryOp = spv::OpDPdyFine;
5636 break;
5637 case glslang::EOpFwidthFine:
5638 unaryOp = spv::OpFwidthFine;
5639 break;
5640 case glslang::EOpDPdxCoarse:
5641 unaryOp = spv::OpDPdxCoarse;
5642 break;
5643 case glslang::EOpDPdyCoarse:
5644 unaryOp = spv::OpDPdyCoarse;
5645 break;
5646 case glslang::EOpFwidthCoarse:
5647 unaryOp = spv::OpFwidthCoarse;
5648 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005649 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005650#ifdef AMD_EXTENSIONS
5651 if (typeProxy == glslang::EbtFloat16)
5652 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5653#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005654 libCall = spv::GLSLstd450InterpolateAtCentroid;
5655 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005656 case glslang::EOpAny:
5657 unaryOp = spv::OpAny;
5658 break;
5659 case glslang::EOpAll:
5660 unaryOp = spv::OpAll;
5661 break;
5662
5663 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005664 if (isFloat)
5665 libCall = spv::GLSLstd450FAbs;
5666 else
5667 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005668 break;
5669 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005670 if (isFloat)
5671 libCall = spv::GLSLstd450FSign;
5672 else
5673 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005674 break;
5675
John Kessenichfc51d282015-08-19 13:34:18 -06005676 case glslang::EOpAtomicCounterIncrement:
5677 case glslang::EOpAtomicCounterDecrement:
5678 case glslang::EOpAtomicCounter:
5679 {
5680 // Handle all of the atomics in one place, in createAtomicOperation()
5681 std::vector<spv::Id> operands;
5682 operands.push_back(operand);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05005683 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy, lvalueCoherentFlags);
John Kessenichfc51d282015-08-19 13:34:18 -06005684 }
5685
John Kessenichfc51d282015-08-19 13:34:18 -06005686 case glslang::EOpBitFieldReverse:
5687 unaryOp = spv::OpBitReverse;
5688 break;
5689 case glslang::EOpBitCount:
5690 unaryOp = spv::OpBitCount;
5691 break;
5692 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005693 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005694 break;
5695 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005696 if (isUnsigned)
5697 libCall = spv::GLSLstd450FindUMsb;
5698 else
5699 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005700 break;
5701
Rex Xu574ab042016-04-14 16:53:07 +08005702 case glslang::EOpBallot:
5703 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005704 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005705 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005706 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005707#ifdef AMD_EXTENSIONS
5708 case glslang::EOpMinInvocations:
5709 case glslang::EOpMaxInvocations:
5710 case glslang::EOpAddInvocations:
5711 case glslang::EOpMinInvocationsNonUniform:
5712 case glslang::EOpMaxInvocationsNonUniform:
5713 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005714 case glslang::EOpMinInvocationsInclusiveScan:
5715 case glslang::EOpMaxInvocationsInclusiveScan:
5716 case glslang::EOpAddInvocationsInclusiveScan:
5717 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5718 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5719 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5720 case glslang::EOpMinInvocationsExclusiveScan:
5721 case glslang::EOpMaxInvocationsExclusiveScan:
5722 case glslang::EOpAddInvocationsExclusiveScan:
5723 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5724 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5725 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005726#endif
Rex Xu51596642016-09-21 18:56:12 +08005727 {
5728 std::vector<spv::Id> operands;
5729 operands.push_back(operand);
5730 return createInvocationsOperation(op, typeId, operands, typeProxy);
5731 }
John Kessenich66011cb2018-03-06 16:12:04 -07005732 case glslang::EOpSubgroupAll:
5733 case glslang::EOpSubgroupAny:
5734 case glslang::EOpSubgroupAllEqual:
5735 case glslang::EOpSubgroupBroadcastFirst:
5736 case glslang::EOpSubgroupBallot:
5737 case glslang::EOpSubgroupInverseBallot:
5738 case glslang::EOpSubgroupBallotBitCount:
5739 case glslang::EOpSubgroupBallotInclusiveBitCount:
5740 case glslang::EOpSubgroupBallotExclusiveBitCount:
5741 case glslang::EOpSubgroupBallotFindLSB:
5742 case glslang::EOpSubgroupBallotFindMSB:
5743 case glslang::EOpSubgroupAdd:
5744 case glslang::EOpSubgroupMul:
5745 case glslang::EOpSubgroupMin:
5746 case glslang::EOpSubgroupMax:
5747 case glslang::EOpSubgroupAnd:
5748 case glslang::EOpSubgroupOr:
5749 case glslang::EOpSubgroupXor:
5750 case glslang::EOpSubgroupInclusiveAdd:
5751 case glslang::EOpSubgroupInclusiveMul:
5752 case glslang::EOpSubgroupInclusiveMin:
5753 case glslang::EOpSubgroupInclusiveMax:
5754 case glslang::EOpSubgroupInclusiveAnd:
5755 case glslang::EOpSubgroupInclusiveOr:
5756 case glslang::EOpSubgroupInclusiveXor:
5757 case glslang::EOpSubgroupExclusiveAdd:
5758 case glslang::EOpSubgroupExclusiveMul:
5759 case glslang::EOpSubgroupExclusiveMin:
5760 case glslang::EOpSubgroupExclusiveMax:
5761 case glslang::EOpSubgroupExclusiveAnd:
5762 case glslang::EOpSubgroupExclusiveOr:
5763 case glslang::EOpSubgroupExclusiveXor:
5764 case glslang::EOpSubgroupQuadSwapHorizontal:
5765 case glslang::EOpSubgroupQuadSwapVertical:
5766 case glslang::EOpSubgroupQuadSwapDiagonal: {
5767 std::vector<spv::Id> operands;
5768 operands.push_back(operand);
5769 return createSubgroupOperation(op, typeId, operands, typeProxy);
5770 }
Rex Xu9d93a232016-05-05 12:30:44 +08005771#ifdef AMD_EXTENSIONS
5772 case glslang::EOpMbcnt:
5773 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5774 libCall = spv::MbcntAMD;
5775 break;
5776
5777 case glslang::EOpCubeFaceIndex:
5778 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5779 libCall = spv::CubeFaceIndexAMD;
5780 break;
5781
5782 case glslang::EOpCubeFaceCoord:
5783 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5784 libCall = spv::CubeFaceCoordAMD;
5785 break;
5786#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005787#ifdef NV_EXTENSIONS
5788 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005789 unaryOp = spv::OpGroupNonUniformPartitionNV;
5790 break;
5791#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005792 case glslang::EOpConstructReference:
5793 unaryOp = spv::OpBitcast;
5794 break;
Jeff Bolz88220d52019-05-08 10:24:46 -05005795
5796 case glslang::EOpCopyObject:
5797 unaryOp = spv::OpCopyObject;
5798 break;
5799
John Kessenich140f3df2015-06-26 16:58:36 -06005800 default:
5801 return 0;
5802 }
5803
5804 spv::Id id;
5805 if (libCall >= 0) {
5806 std::vector<spv::Id> args;
5807 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005808 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005809 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005810 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005811 }
John Kessenich140f3df2015-06-26 16:58:36 -06005812
John Kessenichead86222018-03-28 18:01:20 -06005813 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005814 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005815 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005816}
5817
John Kessenich7a53f762016-01-20 11:19:27 -07005818// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005819spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5820 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005821{
5822 // Handle unary operations vector by vector.
5823 // The result type is the same type as the original type.
5824 // The algorithm is to:
5825 // - break the matrix into vectors
5826 // - apply the operation to each vector
5827 // - make a matrix out the vector results
5828
5829 // get the types sorted out
5830 int numCols = builder.getNumColumns(operand);
5831 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005832 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5833 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005834 std::vector<spv::Id> results;
5835
5836 // do each vector op
5837 for (int c = 0; c < numCols; ++c) {
5838 std::vector<unsigned int> indexes;
5839 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005840 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5841 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005842 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005843 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005844 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005845 }
5846
5847 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005848 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005849 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005850 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005851}
5852
John Kessenichad7645f2018-06-04 19:11:25 -06005853// For converting integers where both the bitwidth and the signedness could
5854// change, but only do the width change here. The caller is still responsible
5855// for the signedness conversion.
5856spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005857{
John Kessenichad7645f2018-06-04 19:11:25 -06005858 // Get the result type width, based on the type to convert to.
5859 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005860 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005861 case glslang::EOpConvInt16ToUint8:
5862 case glslang::EOpConvIntToUint8:
5863 case glslang::EOpConvInt64ToUint8:
5864 case glslang::EOpConvUint16ToInt8:
5865 case glslang::EOpConvUintToInt8:
5866 case glslang::EOpConvUint64ToInt8:
5867 width = 8;
5868 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005869 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005870 case glslang::EOpConvIntToUint16:
5871 case glslang::EOpConvInt64ToUint16:
5872 case glslang::EOpConvUint8ToInt16:
5873 case glslang::EOpConvUintToInt16:
5874 case glslang::EOpConvUint64ToInt16:
5875 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005876 break;
5877 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005878 case glslang::EOpConvInt16ToUint:
5879 case glslang::EOpConvInt64ToUint:
5880 case glslang::EOpConvUint8ToInt:
5881 case glslang::EOpConvUint16ToInt:
5882 case glslang::EOpConvUint64ToInt:
5883 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005884 break;
5885 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005886 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005887 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005888 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005889 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005890 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005891 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005892 break;
5893
5894 default:
5895 assert(false && "Default missing");
5896 break;
5897 }
5898
John Kessenichad7645f2018-06-04 19:11:25 -06005899 // Get the conversion operation and result type,
5900 // based on the target width, but the source type.
5901 spv::Id type = spv::NoType;
5902 spv::Op convOp = spv::OpNop;
5903 switch(op) {
5904 case glslang::EOpConvInt8ToUint16:
5905 case glslang::EOpConvInt8ToUint:
5906 case glslang::EOpConvInt8ToUint64:
5907 case glslang::EOpConvInt16ToUint8:
5908 case glslang::EOpConvInt16ToUint:
5909 case glslang::EOpConvInt16ToUint64:
5910 case glslang::EOpConvIntToUint8:
5911 case glslang::EOpConvIntToUint16:
5912 case glslang::EOpConvIntToUint64:
5913 case glslang::EOpConvInt64ToUint8:
5914 case glslang::EOpConvInt64ToUint16:
5915 case glslang::EOpConvInt64ToUint:
5916 convOp = spv::OpSConvert;
5917 type = builder.makeIntType(width);
5918 break;
5919 default:
5920 convOp = spv::OpUConvert;
5921 type = builder.makeUintType(width);
5922 break;
5923 }
5924
John Kessenich66011cb2018-03-06 16:12:04 -07005925 if (vectorSize > 0)
5926 type = builder.makeVectorType(type, vectorSize);
5927
John Kessenichad7645f2018-06-04 19:11:25 -06005928 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005929}
5930
John Kessenichead86222018-03-28 18:01:20 -06005931spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5932 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005933{
5934 spv::Op convOp = spv::OpNop;
5935 spv::Id zero = 0;
5936 spv::Id one = 0;
5937
5938 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5939
5940 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005941 case glslang::EOpConvInt8ToBool:
5942 case glslang::EOpConvUint8ToBool:
5943 zero = builder.makeUint8Constant(0);
5944 zero = makeSmearedConstant(zero, vectorSize);
5945 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005946 case glslang::EOpConvInt16ToBool:
5947 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005948 zero = builder.makeUint16Constant(0);
5949 zero = makeSmearedConstant(zero, vectorSize);
5950 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5951 case glslang::EOpConvIntToBool:
5952 case glslang::EOpConvUintToBool:
5953 zero = builder.makeUintConstant(0);
5954 zero = makeSmearedConstant(zero, vectorSize);
5955 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5956 case glslang::EOpConvInt64ToBool:
5957 case glslang::EOpConvUint64ToBool:
5958 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005959 zero = makeSmearedConstant(zero, vectorSize);
5960 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5961
5962 case glslang::EOpConvFloatToBool:
5963 zero = builder.makeFloatConstant(0.0F);
5964 zero = makeSmearedConstant(zero, vectorSize);
5965 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5966
5967 case glslang::EOpConvDoubleToBool:
5968 zero = builder.makeDoubleConstant(0.0);
5969 zero = makeSmearedConstant(zero, vectorSize);
5970 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5971
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005972 case glslang::EOpConvFloat16ToBool:
5973 zero = builder.makeFloat16Constant(0.0F);
5974 zero = makeSmearedConstant(zero, vectorSize);
5975 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005976
John Kessenich140f3df2015-06-26 16:58:36 -06005977 case glslang::EOpConvBoolToFloat:
5978 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005979 zero = builder.makeFloatConstant(0.0F);
5980 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005981 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005982
John Kessenich140f3df2015-06-26 16:58:36 -06005983 case glslang::EOpConvBoolToDouble:
5984 convOp = spv::OpSelect;
5985 zero = builder.makeDoubleConstant(0.0);
5986 one = builder.makeDoubleConstant(1.0);
5987 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005988
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005989 case glslang::EOpConvBoolToFloat16:
5990 convOp = spv::OpSelect;
5991 zero = builder.makeFloat16Constant(0.0F);
5992 one = builder.makeFloat16Constant(1.0F);
5993 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005994
5995 case glslang::EOpConvBoolToInt8:
5996 zero = builder.makeInt8Constant(0);
5997 one = builder.makeInt8Constant(1);
5998 convOp = spv::OpSelect;
5999 break;
6000
6001 case glslang::EOpConvBoolToUint8:
6002 zero = builder.makeUint8Constant(0);
6003 one = builder.makeUint8Constant(1);
6004 convOp = spv::OpSelect;
6005 break;
6006
6007 case glslang::EOpConvBoolToInt16:
6008 zero = builder.makeInt16Constant(0);
6009 one = builder.makeInt16Constant(1);
6010 convOp = spv::OpSelect;
6011 break;
6012
6013 case glslang::EOpConvBoolToUint16:
6014 zero = builder.makeUint16Constant(0);
6015 one = builder.makeUint16Constant(1);
6016 convOp = spv::OpSelect;
6017 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006018
John Kessenich140f3df2015-06-26 16:58:36 -06006019 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006020 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006021 if (op == glslang::EOpConvBoolToInt64)
6022 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006023 else
6024 zero = builder.makeIntConstant(0);
6025
6026 if (op == glslang::EOpConvBoolToInt64)
6027 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08006028 else
6029 one = builder.makeIntConstant(1);
6030
John Kessenich140f3df2015-06-26 16:58:36 -06006031 convOp = spv::OpSelect;
6032 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006033
John Kessenich140f3df2015-06-26 16:58:36 -06006034 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006035 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08006036 if (op == glslang::EOpConvBoolToUint64)
6037 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08006038 else
6039 zero = builder.makeUintConstant(0);
6040
6041 if (op == glslang::EOpConvBoolToUint64)
6042 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08006043 else
6044 one = builder.makeUintConstant(1);
6045
John Kessenich140f3df2015-06-26 16:58:36 -06006046 convOp = spv::OpSelect;
6047 break;
6048
John Kessenich66011cb2018-03-06 16:12:04 -07006049 case glslang::EOpConvInt8ToFloat16:
6050 case glslang::EOpConvInt8ToFloat:
6051 case glslang::EOpConvInt8ToDouble:
6052 case glslang::EOpConvInt16ToFloat16:
6053 case glslang::EOpConvInt16ToFloat:
6054 case glslang::EOpConvInt16ToDouble:
6055 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006056 case glslang::EOpConvIntToFloat:
6057 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006058 case glslang::EOpConvInt64ToFloat:
6059 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006060 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006061 convOp = spv::OpConvertSToF;
6062 break;
6063
John Kessenich66011cb2018-03-06 16:12:04 -07006064 case glslang::EOpConvUint8ToFloat16:
6065 case glslang::EOpConvUint8ToFloat:
6066 case glslang::EOpConvUint8ToDouble:
6067 case glslang::EOpConvUint16ToFloat16:
6068 case glslang::EOpConvUint16ToFloat:
6069 case glslang::EOpConvUint16ToDouble:
6070 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006071 case glslang::EOpConvUintToFloat:
6072 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08006073 case glslang::EOpConvUint64ToFloat:
6074 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006075 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06006076 convOp = spv::OpConvertUToF;
6077 break;
6078
6079 case glslang::EOpConvDoubleToFloat:
6080 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006081 case glslang::EOpConvDoubleToFloat16:
6082 case glslang::EOpConvFloat16ToDouble:
6083 case glslang::EOpConvFloatToFloat16:
6084 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06006085 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08006086 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06006087 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06006088 break;
6089
John Kessenich66011cb2018-03-06 16:12:04 -07006090 case glslang::EOpConvFloat16ToInt8:
6091 case glslang::EOpConvFloatToInt8:
6092 case glslang::EOpConvDoubleToInt8:
6093 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006094 case glslang::EOpConvFloatToInt16:
6095 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006096 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07006097 case glslang::EOpConvFloatToInt:
6098 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006099 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006100 case glslang::EOpConvFloatToInt64:
6101 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06006102 convOp = spv::OpConvertFToS;
6103 break;
6104
John Kessenich66011cb2018-03-06 16:12:04 -07006105 case glslang::EOpConvUint8ToInt8:
6106 case glslang::EOpConvInt8ToUint8:
6107 case glslang::EOpConvUint16ToInt16:
6108 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06006109 case glslang::EOpConvUintToInt:
6110 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006111 case glslang::EOpConvUint64ToInt64:
6112 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04006113 if (builder.isInSpecConstCodeGenMode()) {
6114 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006115 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
6116 zero = builder.makeUint8Constant(0);
6117 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006118 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006119 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6120 zero = builder.makeUint64Constant(0);
6121 } else {
Rex Xucabbb782017-03-24 13:41:14 +08006122 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006123 }
qining189b2032016-04-12 23:16:20 -04006124 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006125 // Use OpIAdd, instead of OpBitcast to do the conversion when
6126 // generating for OpSpecConstantOp instruction.
6127 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6128 }
6129 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006130 convOp = spv::OpBitcast;
6131 break;
6132
John Kessenich66011cb2018-03-06 16:12:04 -07006133 case glslang::EOpConvFloat16ToUint8:
6134 case glslang::EOpConvFloatToUint8:
6135 case glslang::EOpConvDoubleToUint8:
6136 case glslang::EOpConvFloat16ToUint16:
6137 case glslang::EOpConvFloatToUint16:
6138 case glslang::EOpConvDoubleToUint16:
6139 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006140 case glslang::EOpConvFloatToUint:
6141 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006142 case glslang::EOpConvFloatToUint64:
6143 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006144 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006145 convOp = spv::OpConvertFToU;
6146 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006147
John Kessenich66011cb2018-03-06 16:12:04 -07006148 case glslang::EOpConvInt8ToInt16:
6149 case glslang::EOpConvInt8ToInt:
6150 case glslang::EOpConvInt8ToInt64:
6151 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006152 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006153 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006154 case glslang::EOpConvIntToInt8:
6155 case glslang::EOpConvIntToInt16:
6156 case glslang::EOpConvIntToInt64:
6157 case glslang::EOpConvInt64ToInt8:
6158 case glslang::EOpConvInt64ToInt16:
6159 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006160 convOp = spv::OpSConvert;
6161 break;
6162
John Kessenich66011cb2018-03-06 16:12:04 -07006163 case glslang::EOpConvUint8ToUint16:
6164 case glslang::EOpConvUint8ToUint:
6165 case glslang::EOpConvUint8ToUint64:
6166 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006167 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006168 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006169 case glslang::EOpConvUintToUint8:
6170 case glslang::EOpConvUintToUint16:
6171 case glslang::EOpConvUintToUint64:
6172 case glslang::EOpConvUint64ToUint8:
6173 case glslang::EOpConvUint64ToUint16:
6174 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006175 convOp = spv::OpUConvert;
6176 break;
6177
John Kessenich66011cb2018-03-06 16:12:04 -07006178 case glslang::EOpConvInt8ToUint16:
6179 case glslang::EOpConvInt8ToUint:
6180 case glslang::EOpConvInt8ToUint64:
6181 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006182 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006183 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006184 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006185 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006186 case glslang::EOpConvIntToUint64:
6187 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006188 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006189 case glslang::EOpConvInt64ToUint:
6190 case glslang::EOpConvUint8ToInt16:
6191 case glslang::EOpConvUint8ToInt:
6192 case glslang::EOpConvUint8ToInt64:
6193 case glslang::EOpConvUint16ToInt8:
6194 case glslang::EOpConvUint16ToInt:
6195 case glslang::EOpConvUint16ToInt64:
6196 case glslang::EOpConvUintToInt8:
6197 case glslang::EOpConvUintToInt16:
6198 case glslang::EOpConvUintToInt64:
6199 case glslang::EOpConvUint64ToInt8:
6200 case glslang::EOpConvUint64ToInt16:
6201 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006202 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006203 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006204
6205 if (builder.isInSpecConstCodeGenMode()) {
6206 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006207 switch(op) {
6208 case glslang::EOpConvInt16ToUint8:
6209 case glslang::EOpConvIntToUint8:
6210 case glslang::EOpConvInt64ToUint8:
6211 case glslang::EOpConvUint16ToInt8:
6212 case glslang::EOpConvUintToInt8:
6213 case glslang::EOpConvUint64ToInt8:
6214 zero = builder.makeUint8Constant(0);
6215 break;
6216 case glslang::EOpConvInt8ToUint16:
6217 case glslang::EOpConvIntToUint16:
6218 case glslang::EOpConvInt64ToUint16:
6219 case glslang::EOpConvUint8ToInt16:
6220 case glslang::EOpConvUintToInt16:
6221 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006222 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006223 break;
6224 case glslang::EOpConvInt8ToUint:
6225 case glslang::EOpConvInt16ToUint:
6226 case glslang::EOpConvInt64ToUint:
6227 case glslang::EOpConvUint8ToInt:
6228 case glslang::EOpConvUint16ToInt:
6229 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006230 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006231 break;
6232 case glslang::EOpConvInt8ToUint64:
6233 case glslang::EOpConvInt16ToUint64:
6234 case glslang::EOpConvIntToUint64:
6235 case glslang::EOpConvUint8ToInt64:
6236 case glslang::EOpConvUint16ToInt64:
6237 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006238 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006239 break;
6240 default:
6241 assert(false && "Default missing");
6242 break;
6243 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006244 zero = makeSmearedConstant(zero, vectorSize);
6245 // Use OpIAdd, instead of OpBitcast to do the conversion when
6246 // generating for OpSpecConstantOp instruction.
6247 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6248 }
6249 // For normal run-time conversion instruction, use OpBitcast.
6250 convOp = spv::OpBitcast;
6251 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006252 case glslang::EOpConvUint64ToPtr:
6253 convOp = spv::OpConvertUToPtr;
6254 break;
6255 case glslang::EOpConvPtrToUint64:
6256 convOp = spv::OpConvertPtrToU;
6257 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006258 default:
6259 break;
6260 }
6261
6262 spv::Id result = 0;
6263 if (convOp == spv::OpNop)
6264 return result;
6265
6266 if (convOp == spv::OpSelect) {
6267 zero = makeSmearedConstant(zero, vectorSize);
6268 one = makeSmearedConstant(one, vectorSize);
6269 result = builder.createTriOp(convOp, destType, operand, one, zero);
6270 } else
6271 result = builder.createUnaryOp(convOp, destType, operand);
6272
John Kessenichead86222018-03-28 18:01:20 -06006273 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006274 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006275 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006276}
6277
6278spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6279{
6280 if (vectorSize == 0)
6281 return constant;
6282
6283 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6284 std::vector<spv::Id> components;
6285 for (int c = 0; c < vectorSize; ++c)
6286 components.push_back(constant);
6287 return builder.makeCompositeConstant(vectorTypeId, components);
6288}
6289
John Kessenich426394d2015-07-23 10:22:48 -06006290// For glslang ops that map to SPV atomic opCodes
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006291spv::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 -06006292{
6293 spv::Op opCode = spv::OpNop;
6294
6295 switch (op) {
6296 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006297 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006298 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006299 opCode = spv::OpAtomicIAdd;
6300 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006301 case glslang::EOpAtomicCounterSubtract:
6302 opCode = spv::OpAtomicISub;
6303 break;
John Kessenich426394d2015-07-23 10:22:48 -06006304 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006305 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006306 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006307 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006308 break;
6309 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006310 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006311 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006312 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006313 break;
6314 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006315 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006316 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006317 opCode = spv::OpAtomicAnd;
6318 break;
6319 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006320 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006321 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006322 opCode = spv::OpAtomicOr;
6323 break;
6324 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006325 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006326 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006327 opCode = spv::OpAtomicXor;
6328 break;
6329 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006330 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006331 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006332 opCode = spv::OpAtomicExchange;
6333 break;
6334 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006335 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006336 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006337 opCode = spv::OpAtomicCompareExchange;
6338 break;
6339 case glslang::EOpAtomicCounterIncrement:
6340 opCode = spv::OpAtomicIIncrement;
6341 break;
6342 case glslang::EOpAtomicCounterDecrement:
6343 opCode = spv::OpAtomicIDecrement;
6344 break;
6345 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006346 case glslang::EOpImageAtomicLoad:
6347 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006348 opCode = spv::OpAtomicLoad;
6349 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006350 case glslang::EOpAtomicStore:
6351 case glslang::EOpImageAtomicStore:
6352 opCode = spv::OpAtomicStore;
6353 break;
John Kessenich426394d2015-07-23 10:22:48 -06006354 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006355 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006356 break;
6357 }
6358
Rex Xue8fe8b02017-09-26 15:42:56 +08006359 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6360 builder.addCapability(spv::CapabilityInt64Atomics);
6361
John Kessenich426394d2015-07-23 10:22:48 -06006362 // Sort out the operands
6363 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006364 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006365 // - compare-exchange swaps the value and comparator
6366 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006367 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006368 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6369 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6370 spv::Id scopeId;
6371 if (glslangIntermediate->usingVulkanMemoryModel()) {
6372 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6373 } else {
6374 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6375 }
6376 // semantics default to relaxed
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006377 spv::Id semanticsId = builder.makeUintConstant(lvalueCoherentFlags.volatil ? spv::MemorySemanticsVolatileMask : spv::MemorySemanticsMaskNone);
Jeff Bolz36831c92018-09-05 10:11:41 -05006378 spv::Id semanticsId2 = semanticsId;
6379
6380 pointerId = operands[0];
6381 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6382 // no additional operands
6383 } else if (opCode == spv::OpAtomicCompareExchange) {
6384 compareId = operands[1];
6385 valueId = operands[2];
6386 if (operands.size() > 3) {
6387 scopeId = operands[3];
6388 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6389 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6390 }
6391 } else if (opCode == spv::OpAtomicLoad) {
6392 if (operands.size() > 1) {
6393 scopeId = operands[1];
6394 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6395 }
6396 } else {
6397 // atomic store or RMW
6398 valueId = operands[1];
6399 if (operands.size() > 2) {
6400 scopeId = operands[2];
6401 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6402 }
Rex Xu04db3f52015-09-16 11:44:02 +08006403 }
John Kessenich426394d2015-07-23 10:22:48 -06006404
Jeff Bolz36831c92018-09-05 10:11:41 -05006405 // Check for capabilities
6406 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05006407 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask |
6408 spv::MemorySemanticsMakeVisibleKHRMask |
6409 spv::MemorySemanticsOutputMemoryKHRMask |
6410 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006411 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6412 }
John Kessenich426394d2015-07-23 10:22:48 -06006413
Jeff Bolz36831c92018-09-05 10:11:41 -05006414 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6415 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6416 }
John Kessenich48d6e792017-10-06 21:21:48 -06006417
Jeff Bolz36831c92018-09-05 10:11:41 -05006418 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6419 spvAtomicOperands.push_back(pointerId);
6420 spvAtomicOperands.push_back(scopeId);
6421 spvAtomicOperands.push_back(semanticsId);
6422 if (opCode == spv::OpAtomicCompareExchange) {
6423 spvAtomicOperands.push_back(semanticsId2);
6424 spvAtomicOperands.push_back(valueId);
6425 spvAtomicOperands.push_back(compareId);
6426 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6427 spvAtomicOperands.push_back(valueId);
6428 }
John Kessenich48d6e792017-10-06 21:21:48 -06006429
Jeff Bolz36831c92018-09-05 10:11:41 -05006430 if (opCode == spv::OpAtomicStore) {
6431 builder.createNoResultOp(opCode, spvAtomicOperands);
6432 return 0;
6433 } else {
6434 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6435
6436 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6437 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6438 if (op == glslang::EOpAtomicCounterDecrement)
6439 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6440
6441 return resultId;
6442 }
John Kessenich426394d2015-07-23 10:22:48 -06006443}
6444
John Kessenich91cef522016-05-05 16:45:40 -06006445// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006446spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006447{
Corentin Walleze7061422018-08-08 15:20:15 +02006448#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006449 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6450 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006451#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006452
Rex Xu51596642016-09-21 18:56:12 +08006453 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006454 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006455 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6456
chaocf200da82016-12-20 12:44:35 -08006457 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6458 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006459 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6460 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006461 } else if (op == glslang::EOpAnyInvocation ||
6462 op == glslang::EOpAllInvocations ||
6463 op == glslang::EOpAllInvocationsEqual) {
6464 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6465 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006466 } else {
6467 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006468#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006469 if (op == glslang::EOpMinInvocationsNonUniform ||
6470 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006471 op == glslang::EOpAddInvocationsNonUniform ||
6472 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6473 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6474 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6475 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6476 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6477 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006478 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006479#endif
Rex Xu51596642016-09-21 18:56:12 +08006480
Rex Xu9d93a232016-05-05 12:30:44 +08006481#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006482 switch (op) {
6483 case glslang::EOpMinInvocations:
6484 case glslang::EOpMaxInvocations:
6485 case glslang::EOpAddInvocations:
6486 case glslang::EOpMinInvocationsNonUniform:
6487 case glslang::EOpMaxInvocationsNonUniform:
6488 case glslang::EOpAddInvocationsNonUniform:
6489 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006490 break;
6491 case glslang::EOpMinInvocationsInclusiveScan:
6492 case glslang::EOpMaxInvocationsInclusiveScan:
6493 case glslang::EOpAddInvocationsInclusiveScan:
6494 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6495 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6496 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6497 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006498 break;
6499 case glslang::EOpMinInvocationsExclusiveScan:
6500 case glslang::EOpMaxInvocationsExclusiveScan:
6501 case glslang::EOpAddInvocationsExclusiveScan:
6502 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6503 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6504 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6505 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006506 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006507 default:
6508 break;
Rex Xu430ef402016-10-14 17:22:23 +08006509 }
John Kessenich149afc32018-08-14 13:31:43 -06006510 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6511 spvGroupOperands.push_back(scope);
6512 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006513 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006514 spvGroupOperands.push_back(groupOp);
6515 }
Rex Xu9d93a232016-05-05 12:30:44 +08006516#endif
Rex Xu51596642016-09-21 18:56:12 +08006517 }
6518
John Kessenich149afc32018-08-14 13:31:43 -06006519 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6520 spv::IdImmediate op = { true, *opIt };
6521 spvGroupOperands.push_back(op);
6522 }
John Kessenich91cef522016-05-05 16:45:40 -06006523
6524 switch (op) {
6525 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006526 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006527 break;
John Kessenich91cef522016-05-05 16:45:40 -06006528 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006529 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006530 break;
John Kessenich91cef522016-05-05 16:45:40 -06006531 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006532 opCode = spv::OpSubgroupAllEqualKHR;
6533 break;
Rex Xu51596642016-09-21 18:56:12 +08006534 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006535 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006536 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006537 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006538 break;
6539 case glslang::EOpReadFirstInvocation:
6540 opCode = spv::OpSubgroupFirstInvocationKHR;
6541 break;
6542 case glslang::EOpBallot:
6543 {
6544 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6545 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6546 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6547 //
6548 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6549 //
6550 spv::Id uintType = builder.makeUintType(32);
6551 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6552 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6553
6554 std::vector<spv::Id> components;
6555 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6556 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6557
6558 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6559 return builder.createUnaryOp(spv::OpBitcast, typeId,
6560 builder.createCompositeConstruct(uvec2Type, components));
6561 }
6562
Rex Xu9d93a232016-05-05 12:30:44 +08006563#ifdef AMD_EXTENSIONS
6564 case glslang::EOpMinInvocations:
6565 case glslang::EOpMaxInvocations:
6566 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006567 case glslang::EOpMinInvocationsInclusiveScan:
6568 case glslang::EOpMaxInvocationsInclusiveScan:
6569 case glslang::EOpAddInvocationsInclusiveScan:
6570 case glslang::EOpMinInvocationsExclusiveScan:
6571 case glslang::EOpMaxInvocationsExclusiveScan:
6572 case glslang::EOpAddInvocationsExclusiveScan:
6573 if (op == glslang::EOpMinInvocations ||
6574 op == glslang::EOpMinInvocationsInclusiveScan ||
6575 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006576 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006577 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006578 else {
6579 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006580 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006581 else
Rex Xu51596642016-09-21 18:56:12 +08006582 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006583 }
Rex Xu430ef402016-10-14 17:22:23 +08006584 } else if (op == glslang::EOpMaxInvocations ||
6585 op == glslang::EOpMaxInvocationsInclusiveScan ||
6586 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006587 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006588 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006589 else {
6590 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006591 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006592 else
Rex Xu51596642016-09-21 18:56:12 +08006593 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006594 }
6595 } else {
6596 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006597 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006598 else
Rex Xu51596642016-09-21 18:56:12 +08006599 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006600 }
6601
Rex Xu2bbbe062016-08-23 15:41:05 +08006602 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006603 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006604
6605 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006606 case glslang::EOpMinInvocationsNonUniform:
6607 case glslang::EOpMaxInvocationsNonUniform:
6608 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006609 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6610 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6611 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6612 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6613 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6614 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6615 if (op == glslang::EOpMinInvocationsNonUniform ||
6616 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6617 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006618 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006619 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006620 else {
6621 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006622 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006623 else
Rex Xu51596642016-09-21 18:56:12 +08006624 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006625 }
6626 }
Rex Xu430ef402016-10-14 17:22:23 +08006627 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6628 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6629 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006630 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006631 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006632 else {
6633 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006634 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006635 else
Rex Xu51596642016-09-21 18:56:12 +08006636 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006637 }
6638 }
6639 else {
6640 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006641 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006642 else
Rex Xu51596642016-09-21 18:56:12 +08006643 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006644 }
6645
Rex Xu2bbbe062016-08-23 15:41:05 +08006646 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006647 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006648
6649 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006650#endif
John Kessenich91cef522016-05-05 16:45:40 -06006651 default:
6652 logger->missingFunctionality("invocation operation");
6653 return spv::NoResult;
6654 }
Rex Xu51596642016-09-21 18:56:12 +08006655
6656 assert(opCode != spv::OpNop);
6657 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006658}
6659
Rex Xu2bbbe062016-08-23 15:41:05 +08006660// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006661spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6662 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006663{
Rex Xub7072052016-09-26 15:53:40 +08006664#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006665 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6666 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006667 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006668 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006669 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6670 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6671 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006672#else
6673 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6674 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006675 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6676 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006677#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006678
6679 // Handle group invocation operations scalar by scalar.
6680 // The result type is the same type as the original type.
6681 // The algorithm is to:
6682 // - break the vector into scalars
6683 // - apply the operation to each scalar
6684 // - make a vector out the scalar results
6685
6686 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006687 int numComponents = builder.getNumComponents(operands[0]);
6688 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006689 std::vector<spv::Id> results;
6690
6691 // do each scalar op
6692 for (int comp = 0; comp < numComponents; ++comp) {
6693 std::vector<unsigned int> indexes;
6694 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006695 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6696 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006697 if (op == spv::OpSubgroupReadInvocationKHR) {
6698 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006699 spv::IdImmediate operand = { true, operands[1] };
6700 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006701 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006702 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6703 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006704 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006705 spv::IdImmediate operand = { true, operands[1] };
6706 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006707 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006708 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6709 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006710 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006711 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006712 spvGroupOperands.push_back(scalar);
6713 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006714
Rex Xub7072052016-09-26 15:53:40 +08006715 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006716 }
6717
6718 // put the pieces together
6719 return builder.createCompositeConstruct(typeId, results);
6720}
Rex Xu2bbbe062016-08-23 15:41:05 +08006721
John Kessenich66011cb2018-03-06 16:12:04 -07006722// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006723spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6724 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006725{
6726 // Add the required capabilities.
6727 switch (op) {
6728 case glslang::EOpSubgroupElect:
6729 builder.addCapability(spv::CapabilityGroupNonUniform);
6730 break;
6731 case glslang::EOpSubgroupAll:
6732 case glslang::EOpSubgroupAny:
6733 case glslang::EOpSubgroupAllEqual:
6734 builder.addCapability(spv::CapabilityGroupNonUniform);
6735 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6736 break;
6737 case glslang::EOpSubgroupBroadcast:
6738 case glslang::EOpSubgroupBroadcastFirst:
6739 case glslang::EOpSubgroupBallot:
6740 case glslang::EOpSubgroupInverseBallot:
6741 case glslang::EOpSubgroupBallotBitExtract:
6742 case glslang::EOpSubgroupBallotBitCount:
6743 case glslang::EOpSubgroupBallotInclusiveBitCount:
6744 case glslang::EOpSubgroupBallotExclusiveBitCount:
6745 case glslang::EOpSubgroupBallotFindLSB:
6746 case glslang::EOpSubgroupBallotFindMSB:
6747 builder.addCapability(spv::CapabilityGroupNonUniform);
6748 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6749 break;
6750 case glslang::EOpSubgroupShuffle:
6751 case glslang::EOpSubgroupShuffleXor:
6752 builder.addCapability(spv::CapabilityGroupNonUniform);
6753 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6754 break;
6755 case glslang::EOpSubgroupShuffleUp:
6756 case glslang::EOpSubgroupShuffleDown:
6757 builder.addCapability(spv::CapabilityGroupNonUniform);
6758 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6759 break;
6760 case glslang::EOpSubgroupAdd:
6761 case glslang::EOpSubgroupMul:
6762 case glslang::EOpSubgroupMin:
6763 case glslang::EOpSubgroupMax:
6764 case glslang::EOpSubgroupAnd:
6765 case glslang::EOpSubgroupOr:
6766 case glslang::EOpSubgroupXor:
6767 case glslang::EOpSubgroupInclusiveAdd:
6768 case glslang::EOpSubgroupInclusiveMul:
6769 case glslang::EOpSubgroupInclusiveMin:
6770 case glslang::EOpSubgroupInclusiveMax:
6771 case glslang::EOpSubgroupInclusiveAnd:
6772 case glslang::EOpSubgroupInclusiveOr:
6773 case glslang::EOpSubgroupInclusiveXor:
6774 case glslang::EOpSubgroupExclusiveAdd:
6775 case glslang::EOpSubgroupExclusiveMul:
6776 case glslang::EOpSubgroupExclusiveMin:
6777 case glslang::EOpSubgroupExclusiveMax:
6778 case glslang::EOpSubgroupExclusiveAnd:
6779 case glslang::EOpSubgroupExclusiveOr:
6780 case glslang::EOpSubgroupExclusiveXor:
6781 builder.addCapability(spv::CapabilityGroupNonUniform);
6782 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6783 break;
6784 case glslang::EOpSubgroupClusteredAdd:
6785 case glslang::EOpSubgroupClusteredMul:
6786 case glslang::EOpSubgroupClusteredMin:
6787 case glslang::EOpSubgroupClusteredMax:
6788 case glslang::EOpSubgroupClusteredAnd:
6789 case glslang::EOpSubgroupClusteredOr:
6790 case glslang::EOpSubgroupClusteredXor:
6791 builder.addCapability(spv::CapabilityGroupNonUniform);
6792 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6793 break;
6794 case glslang::EOpSubgroupQuadBroadcast:
6795 case glslang::EOpSubgroupQuadSwapHorizontal:
6796 case glslang::EOpSubgroupQuadSwapVertical:
6797 case glslang::EOpSubgroupQuadSwapDiagonal:
6798 builder.addCapability(spv::CapabilityGroupNonUniform);
6799 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6800 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006801#ifdef NV_EXTENSIONS
6802 case glslang::EOpSubgroupPartitionedAdd:
6803 case glslang::EOpSubgroupPartitionedMul:
6804 case glslang::EOpSubgroupPartitionedMin:
6805 case glslang::EOpSubgroupPartitionedMax:
6806 case glslang::EOpSubgroupPartitionedAnd:
6807 case glslang::EOpSubgroupPartitionedOr:
6808 case glslang::EOpSubgroupPartitionedXor:
6809 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6810 case glslang::EOpSubgroupPartitionedInclusiveMul:
6811 case glslang::EOpSubgroupPartitionedInclusiveMin:
6812 case glslang::EOpSubgroupPartitionedInclusiveMax:
6813 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6814 case glslang::EOpSubgroupPartitionedInclusiveOr:
6815 case glslang::EOpSubgroupPartitionedInclusiveXor:
6816 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6817 case glslang::EOpSubgroupPartitionedExclusiveMul:
6818 case glslang::EOpSubgroupPartitionedExclusiveMin:
6819 case glslang::EOpSubgroupPartitionedExclusiveMax:
6820 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6821 case glslang::EOpSubgroupPartitionedExclusiveOr:
6822 case glslang::EOpSubgroupPartitionedExclusiveXor:
6823 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6824 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6825 break;
6826#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006827 default: assert(0 && "Unhandled subgroup operation!");
6828 }
6829
6830 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6831 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6832 const bool isBool = typeProxy == glslang::EbtBool;
6833
6834 spv::Op opCode = spv::OpNop;
6835
6836 // Figure out which opcode to use.
6837 switch (op) {
6838 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6839 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6840 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6841 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6842 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6843 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6844 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6845 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6846 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6847 case glslang::EOpSubgroupBallotBitCount:
6848 case glslang::EOpSubgroupBallotInclusiveBitCount:
6849 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6850 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6851 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6852 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6853 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6854 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6855 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6856 case glslang::EOpSubgroupAdd:
6857 case glslang::EOpSubgroupInclusiveAdd:
6858 case glslang::EOpSubgroupExclusiveAdd:
6859 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006860#ifdef NV_EXTENSIONS
6861 case glslang::EOpSubgroupPartitionedAdd:
6862 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6863 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6864#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006865 if (isFloat) {
6866 opCode = spv::OpGroupNonUniformFAdd;
6867 } else {
6868 opCode = spv::OpGroupNonUniformIAdd;
6869 }
6870 break;
6871 case glslang::EOpSubgroupMul:
6872 case glslang::EOpSubgroupInclusiveMul:
6873 case glslang::EOpSubgroupExclusiveMul:
6874 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006875#ifdef NV_EXTENSIONS
6876 case glslang::EOpSubgroupPartitionedMul:
6877 case glslang::EOpSubgroupPartitionedInclusiveMul:
6878 case glslang::EOpSubgroupPartitionedExclusiveMul:
6879#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006880 if (isFloat) {
6881 opCode = spv::OpGroupNonUniformFMul;
6882 } else {
6883 opCode = spv::OpGroupNonUniformIMul;
6884 }
6885 break;
6886 case glslang::EOpSubgroupMin:
6887 case glslang::EOpSubgroupInclusiveMin:
6888 case glslang::EOpSubgroupExclusiveMin:
6889 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006890#ifdef NV_EXTENSIONS
6891 case glslang::EOpSubgroupPartitionedMin:
6892 case glslang::EOpSubgroupPartitionedInclusiveMin:
6893 case glslang::EOpSubgroupPartitionedExclusiveMin:
6894#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006895 if (isFloat) {
6896 opCode = spv::OpGroupNonUniformFMin;
6897 } else if (isUnsigned) {
6898 opCode = spv::OpGroupNonUniformUMin;
6899 } else {
6900 opCode = spv::OpGroupNonUniformSMin;
6901 }
6902 break;
6903 case glslang::EOpSubgroupMax:
6904 case glslang::EOpSubgroupInclusiveMax:
6905 case glslang::EOpSubgroupExclusiveMax:
6906 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006907#ifdef NV_EXTENSIONS
6908 case glslang::EOpSubgroupPartitionedMax:
6909 case glslang::EOpSubgroupPartitionedInclusiveMax:
6910 case glslang::EOpSubgroupPartitionedExclusiveMax:
6911#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006912 if (isFloat) {
6913 opCode = spv::OpGroupNonUniformFMax;
6914 } else if (isUnsigned) {
6915 opCode = spv::OpGroupNonUniformUMax;
6916 } else {
6917 opCode = spv::OpGroupNonUniformSMax;
6918 }
6919 break;
6920 case glslang::EOpSubgroupAnd:
6921 case glslang::EOpSubgroupInclusiveAnd:
6922 case glslang::EOpSubgroupExclusiveAnd:
6923 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006924#ifdef NV_EXTENSIONS
6925 case glslang::EOpSubgroupPartitionedAnd:
6926 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6927 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6928#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006929 if (isBool) {
6930 opCode = spv::OpGroupNonUniformLogicalAnd;
6931 } else {
6932 opCode = spv::OpGroupNonUniformBitwiseAnd;
6933 }
6934 break;
6935 case glslang::EOpSubgroupOr:
6936 case glslang::EOpSubgroupInclusiveOr:
6937 case glslang::EOpSubgroupExclusiveOr:
6938 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006939#ifdef NV_EXTENSIONS
6940 case glslang::EOpSubgroupPartitionedOr:
6941 case glslang::EOpSubgroupPartitionedInclusiveOr:
6942 case glslang::EOpSubgroupPartitionedExclusiveOr:
6943#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006944 if (isBool) {
6945 opCode = spv::OpGroupNonUniformLogicalOr;
6946 } else {
6947 opCode = spv::OpGroupNonUniformBitwiseOr;
6948 }
6949 break;
6950 case glslang::EOpSubgroupXor:
6951 case glslang::EOpSubgroupInclusiveXor:
6952 case glslang::EOpSubgroupExclusiveXor:
6953 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006954#ifdef NV_EXTENSIONS
6955 case glslang::EOpSubgroupPartitionedXor:
6956 case glslang::EOpSubgroupPartitionedInclusiveXor:
6957 case glslang::EOpSubgroupPartitionedExclusiveXor:
6958#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006959 if (isBool) {
6960 opCode = spv::OpGroupNonUniformLogicalXor;
6961 } else {
6962 opCode = spv::OpGroupNonUniformBitwiseXor;
6963 }
6964 break;
6965 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6966 case glslang::EOpSubgroupQuadSwapHorizontal:
6967 case glslang::EOpSubgroupQuadSwapVertical:
6968 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6969 default: assert(0 && "Unhandled subgroup operation!");
6970 }
6971
John Kessenich149afc32018-08-14 13:31:43 -06006972 // get the right Group Operation
6973 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006974 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006975 default:
6976 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006977 case glslang::EOpSubgroupBallotBitCount:
6978 case glslang::EOpSubgroupAdd:
6979 case glslang::EOpSubgroupMul:
6980 case glslang::EOpSubgroupMin:
6981 case glslang::EOpSubgroupMax:
6982 case glslang::EOpSubgroupAnd:
6983 case glslang::EOpSubgroupOr:
6984 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006985 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006986 break;
6987 case glslang::EOpSubgroupBallotInclusiveBitCount:
6988 case glslang::EOpSubgroupInclusiveAdd:
6989 case glslang::EOpSubgroupInclusiveMul:
6990 case glslang::EOpSubgroupInclusiveMin:
6991 case glslang::EOpSubgroupInclusiveMax:
6992 case glslang::EOpSubgroupInclusiveAnd:
6993 case glslang::EOpSubgroupInclusiveOr:
6994 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006995 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006996 break;
6997 case glslang::EOpSubgroupBallotExclusiveBitCount:
6998 case glslang::EOpSubgroupExclusiveAdd:
6999 case glslang::EOpSubgroupExclusiveMul:
7000 case glslang::EOpSubgroupExclusiveMin:
7001 case glslang::EOpSubgroupExclusiveMax:
7002 case glslang::EOpSubgroupExclusiveAnd:
7003 case glslang::EOpSubgroupExclusiveOr:
7004 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007005 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07007006 break;
7007 case glslang::EOpSubgroupClusteredAdd:
7008 case glslang::EOpSubgroupClusteredMul:
7009 case glslang::EOpSubgroupClusteredMin:
7010 case glslang::EOpSubgroupClusteredMax:
7011 case glslang::EOpSubgroupClusteredAnd:
7012 case glslang::EOpSubgroupClusteredOr:
7013 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06007014 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07007015 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007016#ifdef NV_EXTENSIONS
7017 case glslang::EOpSubgroupPartitionedAdd:
7018 case glslang::EOpSubgroupPartitionedMul:
7019 case glslang::EOpSubgroupPartitionedMin:
7020 case glslang::EOpSubgroupPartitionedMax:
7021 case glslang::EOpSubgroupPartitionedAnd:
7022 case glslang::EOpSubgroupPartitionedOr:
7023 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06007024 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007025 break;
7026 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7027 case glslang::EOpSubgroupPartitionedInclusiveMul:
7028 case glslang::EOpSubgroupPartitionedInclusiveMin:
7029 case glslang::EOpSubgroupPartitionedInclusiveMax:
7030 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7031 case glslang::EOpSubgroupPartitionedInclusiveOr:
7032 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007033 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007034 break;
7035 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7036 case glslang::EOpSubgroupPartitionedExclusiveMul:
7037 case glslang::EOpSubgroupPartitionedExclusiveMin:
7038 case glslang::EOpSubgroupPartitionedExclusiveMax:
7039 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7040 case glslang::EOpSubgroupPartitionedExclusiveOr:
7041 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06007042 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007043 break;
7044#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007045 }
7046
John Kessenich149afc32018-08-14 13:31:43 -06007047 // build the instruction
7048 std::vector<spv::IdImmediate> spvGroupOperands;
7049
7050 // Every operation begins with the Execution Scope operand.
7051 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
7052 spvGroupOperands.push_back(executionScope);
7053
7054 // Next, for all operations that use a Group Operation, push that as an operand.
7055 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06007056 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06007057 spvGroupOperands.push_back(groupOperand);
7058 }
7059
John Kessenich66011cb2018-03-06 16:12:04 -07007060 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06007061 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
7062 spv::IdImmediate operand = { true, *opIt };
7063 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07007064 }
7065
7066 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06007067 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07007068 switch (op) {
7069 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06007070 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
7071 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
7072 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
7073 }
7074 if (directionId != spv::NoResult) {
7075 spv::IdImmediate direction = { true, directionId };
7076 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07007077 }
7078
7079 return builder.createOp(opCode, typeId, spvGroupOperands);
7080}
7081
John Kessenich5e4b1242015-08-06 22:53:06 -06007082spv::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 -06007083{
John Kessenich66011cb2018-03-06 16:12:04 -07007084 bool isUnsigned = isTypeUnsignedInt(typeProxy);
7085 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06007086
John Kessenich140f3df2015-06-26 16:58:36 -06007087 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08007088 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06007089 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05007090 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07007091 spv::Id typeId0 = 0;
7092 if (consumedOperands > 0)
7093 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08007094 spv::Id typeId1 = 0;
7095 if (consumedOperands > 1)
7096 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07007097 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06007098
7099 switch (op) {
7100 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06007101 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007102 libCall = nanMinMaxClamp ? spv::GLSLstd450NMin : spv::GLSLstd450FMin;
John Kessenich5e4b1242015-08-06 22:53:06 -06007103 else if (isUnsigned)
7104 libCall = spv::GLSLstd450UMin;
7105 else
7106 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007107 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007108 break;
7109 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06007110 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06007111 break;
7112 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06007113 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007114 libCall = nanMinMaxClamp ? spv::GLSLstd450NMax : spv::GLSLstd450FMax;
John Kessenich5e4b1242015-08-06 22:53:06 -06007115 else if (isUnsigned)
7116 libCall = spv::GLSLstd450UMax;
7117 else
7118 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007119 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007120 break;
7121 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007122 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007123 break;
7124 case glslang::EOpDot:
7125 opCode = spv::OpDot;
7126 break;
7127 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007128 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007129 break;
7130
7131 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007132 if (isFloat)
John Kessenich605afc72019-06-17 23:33:09 -06007133 libCall = nanMinMaxClamp ? spv::GLSLstd450NClamp : spv::GLSLstd450FClamp;
John Kessenich5e4b1242015-08-06 22:53:06 -06007134 else if (isUnsigned)
7135 libCall = spv::GLSLstd450UClamp;
7136 else
7137 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007138 builder.promoteScalar(precision, operands.front(), operands[1]);
7139 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007140 break;
7141 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007142 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7143 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007144 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007145 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007146 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007147 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007148 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007149 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007150 break;
7151 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007152 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007153 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007154 break;
7155 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007156 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007157 builder.promoteScalar(precision, operands[0], operands[2]);
7158 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007159 break;
7160
7161 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007162 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007163 break;
7164 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007165 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007166 break;
7167 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007168 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007169 break;
7170 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007171 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007172 break;
7173 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007174 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007175 break;
Rex Xu7a26c172015-12-08 17:12:09 +08007176 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007177#ifdef AMD_EXTENSIONS
7178 if (typeProxy == glslang::EbtFloat16)
7179 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7180#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007181 libCall = spv::GLSLstd450InterpolateAtSample;
7182 break;
7183 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007184#ifdef AMD_EXTENSIONS
7185 if (typeProxy == glslang::EbtFloat16)
7186 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7187#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007188 libCall = spv::GLSLstd450InterpolateAtOffset;
7189 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007190 case glslang::EOpAddCarry:
7191 opCode = spv::OpIAddCarry;
7192 typeId = builder.makeStructResultType(typeId0, typeId0);
7193 consumedOperands = 2;
7194 break;
7195 case glslang::EOpSubBorrow:
7196 opCode = spv::OpISubBorrow;
7197 typeId = builder.makeStructResultType(typeId0, typeId0);
7198 consumedOperands = 2;
7199 break;
7200 case glslang::EOpUMulExtended:
7201 opCode = spv::OpUMulExtended;
7202 typeId = builder.makeStructResultType(typeId0, typeId0);
7203 consumedOperands = 2;
7204 break;
7205 case glslang::EOpIMulExtended:
7206 opCode = spv::OpSMulExtended;
7207 typeId = builder.makeStructResultType(typeId0, typeId0);
7208 consumedOperands = 2;
7209 break;
7210 case glslang::EOpBitfieldExtract:
7211 if (isUnsigned)
7212 opCode = spv::OpBitFieldUExtract;
7213 else
7214 opCode = spv::OpBitFieldSExtract;
7215 break;
7216 case glslang::EOpBitfieldInsert:
7217 opCode = spv::OpBitFieldInsert;
7218 break;
7219
7220 case glslang::EOpFma:
7221 libCall = spv::GLSLstd450Fma;
7222 break;
7223 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007224 {
7225 libCall = spv::GLSLstd450FrexpStruct;
7226 assert(builder.isPointerType(typeId1));
7227 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007228 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007229#ifdef AMD_EXTENSIONS
7230 if (width == 16)
7231 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7232 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
7233#endif
Rex Xu470026f2017-03-29 17:12:40 +08007234 if (builder.getNumComponents(operands[0]) == 1)
7235 frexpIntType = builder.makeIntegerType(width, true);
7236 else
7237 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7238 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7239 consumedOperands = 1;
7240 }
John Kessenich55e7d112015-11-15 21:33:39 -07007241 break;
7242 case glslang::EOpLdexp:
7243 libCall = spv::GLSLstd450Ldexp;
7244 break;
7245
Rex Xu574ab042016-04-14 16:53:07 +08007246 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007247 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007248
John Kessenich66011cb2018-03-06 16:12:04 -07007249 case glslang::EOpSubgroupBroadcast:
7250 case glslang::EOpSubgroupBallotBitExtract:
7251 case glslang::EOpSubgroupShuffle:
7252 case glslang::EOpSubgroupShuffleXor:
7253 case glslang::EOpSubgroupShuffleUp:
7254 case glslang::EOpSubgroupShuffleDown:
7255 case glslang::EOpSubgroupClusteredAdd:
7256 case glslang::EOpSubgroupClusteredMul:
7257 case glslang::EOpSubgroupClusteredMin:
7258 case glslang::EOpSubgroupClusteredMax:
7259 case glslang::EOpSubgroupClusteredAnd:
7260 case glslang::EOpSubgroupClusteredOr:
7261 case glslang::EOpSubgroupClusteredXor:
7262 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007263#ifdef NV_EXTENSIONS
7264 case glslang::EOpSubgroupPartitionedAdd:
7265 case glslang::EOpSubgroupPartitionedMul:
7266 case glslang::EOpSubgroupPartitionedMin:
7267 case glslang::EOpSubgroupPartitionedMax:
7268 case glslang::EOpSubgroupPartitionedAnd:
7269 case glslang::EOpSubgroupPartitionedOr:
7270 case glslang::EOpSubgroupPartitionedXor:
7271 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7272 case glslang::EOpSubgroupPartitionedInclusiveMul:
7273 case glslang::EOpSubgroupPartitionedInclusiveMin:
7274 case glslang::EOpSubgroupPartitionedInclusiveMax:
7275 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7276 case glslang::EOpSubgroupPartitionedInclusiveOr:
7277 case glslang::EOpSubgroupPartitionedInclusiveXor:
7278 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7279 case glslang::EOpSubgroupPartitionedExclusiveMul:
7280 case glslang::EOpSubgroupPartitionedExclusiveMin:
7281 case glslang::EOpSubgroupPartitionedExclusiveMax:
7282 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7283 case glslang::EOpSubgroupPartitionedExclusiveOr:
7284 case glslang::EOpSubgroupPartitionedExclusiveXor:
7285#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007286 return createSubgroupOperation(op, typeId, operands, typeProxy);
7287
Rex Xu9d93a232016-05-05 12:30:44 +08007288#ifdef AMD_EXTENSIONS
7289 case glslang::EOpSwizzleInvocations:
7290 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7291 libCall = spv::SwizzleInvocationsAMD;
7292 break;
7293 case glslang::EOpSwizzleInvocationsMasked:
7294 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7295 libCall = spv::SwizzleInvocationsMaskedAMD;
7296 break;
7297 case glslang::EOpWriteInvocation:
7298 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7299 libCall = spv::WriteInvocationAMD;
7300 break;
7301
7302 case glslang::EOpMin3:
7303 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7304 if (isFloat)
7305 libCall = spv::FMin3AMD;
7306 else {
7307 if (isUnsigned)
7308 libCall = spv::UMin3AMD;
7309 else
7310 libCall = spv::SMin3AMD;
7311 }
7312 break;
7313 case glslang::EOpMax3:
7314 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7315 if (isFloat)
7316 libCall = spv::FMax3AMD;
7317 else {
7318 if (isUnsigned)
7319 libCall = spv::UMax3AMD;
7320 else
7321 libCall = spv::SMax3AMD;
7322 }
7323 break;
7324 case glslang::EOpMid3:
7325 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7326 if (isFloat)
7327 libCall = spv::FMid3AMD;
7328 else {
7329 if (isUnsigned)
7330 libCall = spv::UMid3AMD;
7331 else
7332 libCall = spv::SMid3AMD;
7333 }
7334 break;
7335
7336 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007337 if (typeProxy == glslang::EbtFloat16)
7338 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007339 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7340 libCall = spv::InterpolateAtVertexAMD;
7341 break;
7342#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007343 case glslang::EOpBarrier:
7344 {
7345 // This is for the extended controlBarrier function, with four operands.
7346 // The unextended barrier() goes through createNoArgOperation.
7347 assert(operands.size() == 4);
7348 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7349 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7350 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7351 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007352 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7353 spv::MemorySemanticsMakeVisibleKHRMask |
7354 spv::MemorySemanticsOutputMemoryKHRMask |
7355 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007356 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7357 }
7358 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7359 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7360 }
7361 return 0;
7362 }
7363 break;
7364 case glslang::EOpMemoryBarrier:
7365 {
7366 // This is for the extended memoryBarrier function, with three operands.
7367 // The unextended memoryBarrier() goes through createNoArgOperation.
7368 assert(operands.size() == 3);
7369 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7370 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7371 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
Jeff Bolz38a52fc2019-06-14 09:56:28 -05007372 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask |
7373 spv::MemorySemanticsMakeVisibleKHRMask |
7374 spv::MemorySemanticsOutputMemoryKHRMask |
7375 spv::MemorySemanticsVolatileMask)) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007376 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7377 }
7378 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7379 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7380 }
7381 return 0;
7382 }
7383 break;
Chao Chen3c366992018-09-19 11:41:59 -07007384
7385#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007386 case glslang::EOpReportIntersectionNV:
7387 {
7388 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007389 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007390 }
7391 break;
7392 case glslang::EOpTraceNV:
7393 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007394 builder.createNoResultOp(spv::OpTraceNV, operands);
7395 return 0;
7396 }
7397 break;
7398 case glslang::EOpExecuteCallableNV:
7399 {
7400 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007401 return 0;
7402 }
7403 break;
Chao Chen3c366992018-09-19 11:41:59 -07007404 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7405 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7406 return 0;
7407#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007408 case glslang::EOpCooperativeMatrixMulAdd:
7409 opCode = spv::OpCooperativeMatrixMulAddNV;
7410 break;
7411
John Kessenich140f3df2015-06-26 16:58:36 -06007412 default:
7413 return 0;
7414 }
7415
7416 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007417 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007418 // Use an extended instruction from the standard library.
7419 // Construct the call arguments, without modifying the original operands vector.
7420 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7421 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007422 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007423 } else if (opCode == spv::OpDot && !isFloat) {
7424 // int dot(int, int)
7425 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7426 const int componentCount = builder.getNumComponents(operands[0]);
7427 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7428 builder.setPrecision(mulOp, precision);
7429 id = builder.createCompositeExtract(mulOp, typeId, 0);
7430 for (int i = 1; i < componentCount; ++i) {
7431 builder.setPrecision(id, precision);
7432 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7433 }
John Kessenich2359bd02015-12-06 19:29:11 -07007434 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007435 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007436 case 0:
7437 // should all be handled by visitAggregate and createNoArgOperation
7438 assert(0);
7439 return 0;
7440 case 1:
7441 // should all be handled by createUnaryOperation
7442 assert(0);
7443 return 0;
7444 case 2:
7445 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7446 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007447 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007448 // anything 3 or over doesn't have l-value operands, so all should be consumed
7449 assert(consumedOperands == operands.size());
7450 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007451 break;
7452 }
7453 }
7454
John Kessenich55e7d112015-11-15 21:33:39 -07007455 // Decode the return types that were structures
7456 switch (op) {
7457 case glslang::EOpAddCarry:
7458 case glslang::EOpSubBorrow:
7459 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7460 id = builder.createCompositeExtract(id, typeId0, 0);
7461 break;
7462 case glslang::EOpUMulExtended:
7463 case glslang::EOpIMulExtended:
7464 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7465 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7466 break;
7467 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007468 {
7469 assert(operands.size() == 2);
7470 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7471 // "exp" is floating-point type (from HLSL intrinsic)
7472 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7473 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7474 builder.createStore(member1, operands[1]);
7475 } else
7476 // "exp" is integer type (from GLSL built-in function)
7477 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7478 id = builder.createCompositeExtract(id, typeId0, 0);
7479 }
John Kessenich55e7d112015-11-15 21:33:39 -07007480 break;
7481 default:
7482 break;
7483 }
7484
John Kessenich32cfd492016-02-02 12:37:46 -07007485 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007486}
7487
Rex Xu9d93a232016-05-05 12:30:44 +08007488// Intrinsics with no arguments (or no return value, and no precision).
7489spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007490{
Jeff Bolz36831c92018-09-05 10:11:41 -05007491 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7492 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007493
7494 switch (op) {
7495 case glslang::EOpEmitVertex:
7496 builder.createNoResultOp(spv::OpEmitVertex);
7497 return 0;
7498 case glslang::EOpEndPrimitive:
7499 builder.createNoResultOp(spv::OpEndPrimitive);
7500 return 0;
7501 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007502 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007503 if (glslangIntermediate->usingVulkanMemoryModel()) {
7504 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7505 spv::MemorySemanticsOutputMemoryKHRMask |
7506 spv::MemorySemanticsAcquireReleaseMask);
7507 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7508 } else {
7509 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7510 }
John Kessenich82979362017-12-11 04:02:24 -07007511 } else {
7512 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7513 spv::MemorySemanticsWorkgroupMemoryMask |
7514 spv::MemorySemanticsAcquireReleaseMask);
7515 }
John Kessenich140f3df2015-06-26 16:58:36 -06007516 return 0;
7517 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007518 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7519 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007520 return 0;
7521 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007522 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7523 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007524 return 0;
7525 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007526 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7527 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007528 return 0;
7529 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007530 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7531 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007532 return 0;
7533 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007534 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7535 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007536 return 0;
7537 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007538 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7539 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007540 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007541 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007542 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007543 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007544 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007545 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007546 case glslang::EOpDeviceMemoryBarrier:
7547 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7548 spv::MemorySemanticsImageMemoryMask |
7549 spv::MemorySemanticsAcquireReleaseMask);
7550 return 0;
7551 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7552 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7553 spv::MemorySemanticsImageMemoryMask |
7554 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007555 return 0;
7556 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007557 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7558 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007559 return 0;
7560 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007561 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7562 spv::MemorySemanticsWorkgroupMemoryMask |
7563 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007564 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007565 case glslang::EOpSubgroupBarrier:
7566 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7567 spv::MemorySemanticsAcquireReleaseMask);
7568 return spv::NoResult;
7569 case glslang::EOpSubgroupMemoryBarrier:
7570 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7571 spv::MemorySemanticsAcquireReleaseMask);
7572 return spv::NoResult;
7573 case glslang::EOpSubgroupMemoryBarrierBuffer:
7574 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7575 spv::MemorySemanticsAcquireReleaseMask);
7576 return spv::NoResult;
7577 case glslang::EOpSubgroupMemoryBarrierImage:
7578 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7579 spv::MemorySemanticsAcquireReleaseMask);
7580 return spv::NoResult;
7581 case glslang::EOpSubgroupMemoryBarrierShared:
7582 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7583 spv::MemorySemanticsAcquireReleaseMask);
7584 return spv::NoResult;
7585 case glslang::EOpSubgroupElect: {
7586 std::vector<spv::Id> operands;
7587 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7588 }
Rex Xu9d93a232016-05-05 12:30:44 +08007589#ifdef AMD_EXTENSIONS
7590 case glslang::EOpTime:
7591 {
7592 std::vector<spv::Id> args; // Dummy arguments
7593 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7594 return builder.setPrecision(id, precision);
7595 }
7596#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007597#ifdef NV_EXTENSIONS
7598 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007599 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007600 return 0;
7601 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007602 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007603 return 0;
7604#endif
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007605
7606 case glslang::EOpBeginInvocationInterlock:
7607 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7608 return 0;
7609 case glslang::EOpEndInvocationInterlock:
7610 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7611 return 0;
7612
John Kessenich140f3df2015-06-26 16:58:36 -06007613 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007614 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007615 return 0;
7616 }
7617}
7618
7619spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7620{
John Kessenich2f273362015-07-18 22:34:27 -06007621 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007622 spv::Id id;
7623 if (symbolValues.end() != iter) {
7624 id = iter->second;
7625 return id;
7626 }
7627
7628 // it was not found, create it
John Kessenich9c14f772019-06-17 08:38:35 -06007629 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
7630 auto forcedType = getForcedType(builtIn, symbol->getType());
7631 id = createSpvVariable(symbol, forcedType.first);
John Kessenich140f3df2015-06-26 16:58:36 -06007632 symbolValues[symbol->getId()] = id;
John Kessenich9c14f772019-06-17 08:38:35 -06007633 if (forcedType.second != spv::NoType)
7634 forceType[id] = forcedType.second;
John Kessenich140f3df2015-06-26 16:58:36 -06007635
Rex Xuc884b4a2016-06-29 15:03:44 +08007636 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007637 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7638 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7639 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007640#ifdef NV_EXTENSIONS
7641 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7642#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007643 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007644 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007645 if (symbol->getQualifier().hasIndex())
7646 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7647 if (symbol->getQualifier().hasComponent())
7648 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007649 // atomic counters use this:
7650 if (symbol->getQualifier().hasOffset())
7651 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007652 }
7653
scygan2c864272016-05-18 18:09:17 +02007654 if (symbol->getQualifier().hasLocation())
7655 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007656 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007657 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007658 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007659 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007660 }
John Kessenich140f3df2015-06-26 16:58:36 -06007661 if (symbol->getQualifier().hasSet())
7662 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007663 else if (IsDescriptorResource(symbol->getType())) {
7664 // default to 0
7665 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7666 }
John Kessenich140f3df2015-06-26 16:58:36 -06007667 if (symbol->getQualifier().hasBinding())
7668 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007669 else if (IsDescriptorResource(symbol->getType())) {
7670 // default to 0
7671 builder.addDecoration(id, spv::DecorationBinding, 0);
7672 }
John Kessenich6c292d32016-02-15 20:58:50 -07007673 if (symbol->getQualifier().hasAttachment())
7674 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007675 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007676 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007677 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007678 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007679 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7680 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7681 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7682 }
7683 if (symbol->getQualifier().hasXfbOffset())
7684 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007685 }
7686
Rex Xu1da878f2016-02-21 20:59:01 +08007687 if (symbol->getType().isImage()) {
7688 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007689 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007690 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007691 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007692 }
7693
John Kessenich9c14f772019-06-17 08:38:35 -06007694 // add built-in variable decoration
7695 if (builtIn != spv::BuiltInMax) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007696 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich9c14f772019-06-17 08:38:35 -06007697 }
John Kessenich140f3df2015-06-26 16:58:36 -06007698
John Kessenich5611c6d2018-04-05 11:25:02 -06007699 // nonuniform
7700 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7701
John Kessenichecba76f2017-01-06 00:34:48 -07007702#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007703 if (builtIn == spv::BuiltInSampleMask) {
7704 spv::Decoration decoration;
7705 // GL_NV_sample_mask_override_coverage extension
7706 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007707 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007708 else
7709 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007710 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007711 if (decoration != spv::DecorationMax) {
7712 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7713 }
7714 }
chaoc771d89f2017-01-13 01:10:53 -08007715 else if (builtIn == spv::BuiltInLayer) {
7716 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007717 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007718 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007719 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7720 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7721 }
John Kessenichb41bff62017-08-11 13:07:17 -06007722 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007723 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7724 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007725 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7726 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7727 }
7728 }
7729
chaoc6e5acae2016-12-20 13:28:52 -08007730 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007731 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007732 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007733 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7734 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007735 if (symbol->getQualifier().pervertexNV) {
7736 builder.addDecoration(id, spv::DecorationPerVertexNV);
7737 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7738 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7739 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007740#endif
7741
John Kessenich5d610ee2018-03-07 18:05:55 -07007742 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7743 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7744 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7745 symbol->getType().getQualifier().semanticName);
7746 }
7747
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007748 if (symbol->getBasicType() == glslang::EbtReference) {
7749 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7750 }
7751
John Kessenich140f3df2015-06-26 16:58:36 -06007752 return id;
7753}
7754
Chao Chen3c366992018-09-19 11:41:59 -07007755#ifdef NV_EXTENSIONS
7756// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7757void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7758{
7759 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007760 if (qualifier.perPrimitiveNV) {
7761 // Need to add capability/extension for fragment shader.
7762 // Mesh shader already adds this by default.
7763 if (glslangIntermediate->getStage() == EShLangFragment) {
7764 builder.addCapability(spv::CapabilityMeshShadingNV);
7765 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7766 }
Chao Chen3c366992018-09-19 11:41:59 -07007767 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007768 }
Chao Chen3c366992018-09-19 11:41:59 -07007769 if (qualifier.perViewNV)
7770 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7771 if (qualifier.perTaskNV)
7772 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7773 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007774 if (qualifier.perPrimitiveNV) {
7775 // Need to add capability/extension for fragment shader.
7776 // Mesh shader already adds this by default.
7777 if (glslangIntermediate->getStage() == EShLangFragment) {
7778 builder.addCapability(spv::CapabilityMeshShadingNV);
7779 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7780 }
Chao Chen3c366992018-09-19 11:41:59 -07007781 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007782 }
Chao Chen3c366992018-09-19 11:41:59 -07007783 if (qualifier.perViewNV)
7784 builder.addDecoration(id, spv::DecorationPerViewNV);
7785 if (qualifier.perTaskNV)
7786 builder.addDecoration(id, spv::DecorationPerTaskNV);
7787 }
7788}
7789#endif
7790
John Kessenich55e7d112015-11-15 21:33:39 -07007791// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007792// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007793//
7794// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7795//
7796// Recursively walk the nodes. The nodes form a tree whose leaves are
7797// regular constants, which themselves are trees that createSpvConstant()
7798// recursively walks. So, this function walks the "top" of the tree:
7799// - emit specialization constant-building instructions for specConstant
7800// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007801spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007802{
John Kessenich7cc0e282016-03-20 00:46:02 -06007803 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007804
qining4f4bb812016-04-03 23:55:17 -04007805 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007806 if (! node.getQualifier().specConstant) {
7807 // hand off to the non-spec-constant path
7808 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7809 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007810 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007811 nextConst, false);
7812 }
7813
7814 // We now know we have a specialization constant to build
7815
John Kessenichd94c0032016-05-30 19:29:40 -06007816 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007817 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7818 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7819 std::vector<spv::Id> dimConstId;
7820 for (int dim = 0; dim < 3; ++dim) {
7821 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7822 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007823 if (specConst) {
7824 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7825 glslangIntermediate->getLocalSizeSpecId(dim));
7826 }
qining4f4bb812016-04-03 23:55:17 -04007827 }
7828 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7829 }
7830
7831 // An AST node labelled as specialization constant should be a symbol node.
7832 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7833 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007834 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007835 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007836 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7837 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7838 // will set the builder into spec constant op instruction generating mode.
7839 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007840 result = accessChainLoad(sub_tree->getType());
7841 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007842 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007843 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007844 } else {
7845 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007846 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007847 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007848 builder.addName(result, sn->getName().c_str());
7849 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007850 }
qining4f4bb812016-04-03 23:55:17 -04007851
7852 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7853 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007854 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007855 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007856}
7857
John Kessenich140f3df2015-06-26 16:58:36 -06007858// Use 'consts' as the flattened glslang source of scalar constants to recursively
7859// build the aggregate SPIR-V constant.
7860//
7861// If there are not enough elements present in 'consts', 0 will be substituted;
7862// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7863//
qining08408382016-03-21 09:51:37 -04007864spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007865{
7866 // vector of constants for SPIR-V
7867 std::vector<spv::Id> spvConsts;
7868
7869 // Type is used for struct and array constants
7870 spv::Id typeId = convertGlslangToSpvType(glslangType);
7871
7872 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007873 glslang::TType elementType(glslangType, 0);
7874 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007875 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007876 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007877 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007878 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007879 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007880 } else if (glslangType.isCoopMat()) {
7881 glslang::TType componentType(glslangType.getBasicType());
7882 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007883 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007884 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7885 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007886 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007887 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007888 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7889 bool zero = nextConst >= consts.size();
7890 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007891 case glslang::EbtInt8:
7892 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7893 break;
7894 case glslang::EbtUint8:
7895 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7896 break;
7897 case glslang::EbtInt16:
7898 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7899 break;
7900 case glslang::EbtUint16:
7901 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7902 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007903 case glslang::EbtInt:
7904 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7905 break;
7906 case glslang::EbtUint:
7907 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7908 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007909 case glslang::EbtInt64:
7910 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7911 break;
7912 case glslang::EbtUint64:
7913 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7914 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007915 case glslang::EbtFloat:
7916 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7917 break;
7918 case glslang::EbtDouble:
7919 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7920 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007921 case glslang::EbtFloat16:
7922 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7923 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007924 case glslang::EbtBool:
7925 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7926 break;
7927 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007928 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007929 break;
7930 }
7931 ++nextConst;
7932 }
7933 } else {
7934 // we have a non-aggregate (scalar) constant
7935 bool zero = nextConst >= consts.size();
7936 spv::Id scalar = 0;
7937 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007938 case glslang::EbtInt8:
7939 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7940 break;
7941 case glslang::EbtUint8:
7942 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7943 break;
7944 case glslang::EbtInt16:
7945 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7946 break;
7947 case glslang::EbtUint16:
7948 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7949 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007950 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007951 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007952 break;
7953 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007954 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007955 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007956 case glslang::EbtInt64:
7957 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7958 break;
7959 case glslang::EbtUint64:
7960 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7961 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007962 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007963 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007964 break;
7965 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007966 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007967 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007968 case glslang::EbtFloat16:
7969 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7970 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007971 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007972 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007973 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007974 case glslang::EbtReference:
7975 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7976 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7977 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007978 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007979 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007980 break;
7981 }
7982 ++nextConst;
7983 return scalar;
7984 }
7985
7986 return builder.makeCompositeConstant(typeId, spvConsts);
7987}
7988
John Kessenich7c1aa102015-10-15 13:29:11 -06007989// Return true if the node is a constant or symbol whose reading has no
7990// non-trivial observable cost or effect.
7991bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7992{
7993 // don't know what this is
7994 if (node == nullptr)
7995 return false;
7996
7997 // a constant is safe
7998 if (node->getAsConstantUnion() != nullptr)
7999 return true;
8000
8001 // not a symbol means non-trivial
8002 if (node->getAsSymbolNode() == nullptr)
8003 return false;
8004
8005 // a symbol, depends on what's being read
8006 switch (node->getType().getQualifier().storage) {
8007 case glslang::EvqTemporary:
8008 case glslang::EvqGlobal:
8009 case glslang::EvqIn:
8010 case glslang::EvqInOut:
8011 case glslang::EvqConst:
8012 case glslang::EvqConstReadOnly:
8013 case glslang::EvqUniform:
8014 return true;
8015 default:
8016 return false;
8017 }
qining25262b32016-05-06 17:25:16 -04008018}
John Kessenich7c1aa102015-10-15 13:29:11 -06008019
8020// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06008021// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06008022// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06008023// Return true if trivial.
8024bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
8025{
8026 if (node == nullptr)
8027 return false;
8028
John Kessenich84cc15f2017-05-24 16:44:47 -06008029 // count non scalars as trivial, as well as anything coming from HLSL
8030 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06008031 return true;
8032
John Kessenich7c1aa102015-10-15 13:29:11 -06008033 // symbols and constants are trivial
8034 if (isTrivialLeaf(node))
8035 return true;
8036
8037 // otherwise, it needs to be a simple operation or one or two leaf nodes
8038
8039 // not a simple operation
8040 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
8041 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
8042 if (binaryNode == nullptr && unaryNode == nullptr)
8043 return false;
8044
8045 // not on leaf nodes
8046 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
8047 return false;
8048
8049 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
8050 return false;
8051 }
8052
8053 switch (node->getAsOperator()->getOp()) {
8054 case glslang::EOpLogicalNot:
8055 case glslang::EOpConvIntToBool:
8056 case glslang::EOpConvUintToBool:
8057 case glslang::EOpConvFloatToBool:
8058 case glslang::EOpConvDoubleToBool:
8059 case glslang::EOpEqual:
8060 case glslang::EOpNotEqual:
8061 case glslang::EOpLessThan:
8062 case glslang::EOpGreaterThan:
8063 case glslang::EOpLessThanEqual:
8064 case glslang::EOpGreaterThanEqual:
8065 case glslang::EOpIndexDirect:
8066 case glslang::EOpIndexDirectStruct:
8067 case glslang::EOpLogicalXor:
8068 case glslang::EOpAny:
8069 case glslang::EOpAll:
8070 return true;
8071 default:
8072 return false;
8073 }
8074}
8075
8076// Emit short-circuiting code, where 'right' is never evaluated unless
8077// the left side is true (for &&) or false (for ||).
8078spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
8079{
8080 spv::Id boolTypeId = builder.makeBoolType();
8081
8082 // emit left operand
8083 builder.clearAccessChain();
8084 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008085 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008086
8087 // Operands to accumulate OpPhi operands
8088 std::vector<spv::Id> phiOperands;
8089 // accumulate left operand's phi information
8090 phiOperands.push_back(leftId);
8091 phiOperands.push_back(builder.getBuildPoint()->getId());
8092
8093 // Make the two kinds of operation symmetric with a "!"
8094 // || => emit "if (! left) result = right"
8095 // && => emit "if ( left) result = right"
8096 //
8097 // TODO: this runtime "not" for || could be avoided by adding functionality
8098 // to 'builder' to have an "else" without an "then"
8099 if (op == glslang::EOpLogicalOr)
8100 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
8101
8102 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08008103 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06008104
8105 // emit right operand as the "then" part of the "if"
8106 builder.clearAccessChain();
8107 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08008108 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06008109
8110 // accumulate left operand's phi information
8111 phiOperands.push_back(rightId);
8112 phiOperands.push_back(builder.getBuildPoint()->getId());
8113
8114 // finish the "if"
8115 ifBuilder.makeEndIf();
8116
8117 // phi together the two results
8118 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
8119}
8120
Frank Henigman541f7bb2018-01-16 00:18:26 -05008121#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08008122// Return type Id of the imported set of extended instructions corresponds to the name.
8123// Import this set if it has not been imported yet.
8124spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
8125{
8126 if (extBuiltinMap.find(name) != extBuiltinMap.end())
8127 return extBuiltinMap[name];
8128 else {
Rex Xu51596642016-09-21 18:56:12 +08008129 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008130 spv::Id extBuiltins = builder.import(name);
8131 extBuiltinMap[name] = extBuiltins;
8132 return extBuiltins;
8133 }
8134}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008135#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008136
John Kessenich140f3df2015-06-26 16:58:36 -06008137}; // end anonymous namespace
8138
8139namespace glslang {
8140
John Kessenich68d78fd2015-07-12 19:28:10 -06008141void GetSpirvVersion(std::string& version)
8142{
John Kessenich9e55f632015-07-15 10:03:39 -06008143 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008144 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008145 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008146 version = buf;
8147}
8148
John Kessenicha372a3e2017-11-02 22:32:14 -06008149// For low-order part of the generator's magic number. Bump up
8150// when there is a change in the style (e.g., if SSA form changes,
8151// or a different instruction sequence to do something gets used).
8152int GetSpirvGeneratorVersion()
8153{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008154 // return 1; // start
8155 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008156 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008157 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008158 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008159 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8160 // versions 4 and 6 each generate OpArrayLength as it has long been done
8161 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008162}
8163
John Kessenich140f3df2015-06-26 16:58:36 -06008164// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008165void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008166{
8167 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008168 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008169 if (out.fail())
8170 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008171 for (int i = 0; i < (int)spirv.size(); ++i) {
8172 unsigned int word = spirv[i];
8173 out.write((const char*)&word, 4);
8174 }
8175 out.close();
8176}
8177
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008178// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008179void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008180{
8181 std::ofstream out;
8182 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008183 if (out.fail())
8184 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008185 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008186 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008187 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008188 if (varName != nullptr) {
8189 out << "\t #pragma once" << std::endl;
8190 out << "const uint32_t " << varName << "[] = {" << std::endl;
8191 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008192 const int WORDS_PER_LINE = 8;
8193 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8194 out << "\t";
8195 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8196 const unsigned int word = spirv[i + j];
8197 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8198 if (i + j + 1 < (int)spirv.size()) {
8199 out << ",";
8200 }
8201 }
8202 out << std::endl;
8203 }
Flavio15017db2017-02-15 14:29:33 -08008204 if (varName != nullptr) {
8205 out << "};";
8206 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008207 out.close();
8208}
8209
John Kessenich140f3df2015-06-26 16:58:36 -06008210//
8211// Set up the glslang traversal
8212//
John Kessenich4e11b612018-08-30 16:56:59 -06008213void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008214{
Lei Zhang17535f72016-05-04 15:55:59 -04008215 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008216 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008217}
8218
John Kessenich4e11b612018-08-30 16:56:59 -06008219void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008220 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008221{
John Kessenich140f3df2015-06-26 16:58:36 -06008222 TIntermNode* root = intermediate.getTreeRoot();
8223
8224 if (root == 0)
8225 return;
8226
John Kessenich4e11b612018-08-30 16:56:59 -06008227 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008228 if (options == nullptr)
8229 options = &defaultOptions;
8230
John Kessenich4e11b612018-08-30 16:56:59 -06008231 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008232
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008233 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008234 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008235 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008236 it.dumpSpv(spirv);
8237
GregFfb03a552018-03-29 11:49:14 -06008238#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008239 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8240 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008241 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8242 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008243 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008244 prelegalization = false;
8245 }
John Kessenich717c80a2018-08-23 15:17:10 -06008246
John Kessenich4e11b612018-08-30 16:56:59 -06008247 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008248 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008249
John Kessenich717c80a2018-08-23 15:17:10 -06008250 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008251 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008252
GregFcd1f1692017-09-21 18:40:22 -06008253#endif
8254
John Kessenich4e11b612018-08-30 16:56:59 -06008255 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008256}
8257
8258}; // end namespace glslang