blob: 5b753ce19572e128d544fa414f7e7b9d07f02cc0 [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 Kessenicha2858d92018-01-31 08:11:18 -0700138 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, unsigned int& dependencyLength) 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 Kessenich140f3df2015-06-26 16:58:36 -0600141 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
142 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);
Rex Xu04db3f52015-09-16 11:44:02 +0800172 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
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,
181 glslang::TBasicType typeProxy);
182 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);
Rex Xu04db3f52015-09-16 11:44:02 +0800188 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
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 Kessenich140f3df2015-06-26 16:58:36 -0600211
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600212 unsigned int getBufferReferenceAlignment(const glslang::TType &type) const {
213 if (type.getBasicType() == glslang::EbtReference) {
214 return type.getReferentType()->getQualifier().hasBufferReferenceAlign() ?
215 (1u << type.getReferentType()->getQualifier().layoutBufferReferenceAlign) : 16u;
216 } else {
217 return 0;
218 }
219 }
220
John Kessenich121853f2017-05-31 17:11:16 -0600221 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600222 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600223 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700224 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600225 int sequenceDepth;
226
Lei Zhang17535f72016-05-04 15:55:59 -0400227 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400228
John Kessenich140f3df2015-06-26 16:58:36 -0600229 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
230 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700231 bool inEntryPoint;
232 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700233 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 -0700234 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600235 const glslang::TIntermediate* glslangIntermediate;
236 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800237 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600238
John Kessenich2f273362015-07-18 22:34:27 -0600239 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600240 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600241 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700242 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700243 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
244 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600245 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700246 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600247 // Map pointee types for EbtReference to their forward pointers
248 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich140f3df2015-06-26 16:58:36 -0600249};
250
251//
252// Helper functions for translating glslang representations to SPIR-V enumerants.
253//
254
255// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700256spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600257{
John Kessenich66e2faf2016-03-12 18:34:36 -0700258 switch (source) {
259 case glslang::EShSourceGlsl:
260 switch (profile) {
261 case ENoProfile:
262 case ECoreProfile:
263 case ECompatibilityProfile:
264 return spv::SourceLanguageGLSL;
265 case EEsProfile:
266 return spv::SourceLanguageESSL;
267 default:
268 return spv::SourceLanguageUnknown;
269 }
270 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600271 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600272 default:
273 return spv::SourceLanguageUnknown;
274 }
275}
276
277// Translate glslang language (stage) to SPIR-V execution model.
278spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
279{
280 switch (stage) {
281 case EShLangVertex: return spv::ExecutionModelVertex;
282 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
283 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
284 case EShLangGeometry: return spv::ExecutionModelGeometry;
285 case EShLangFragment: return spv::ExecutionModelFragment;
286 case EShLangCompute: return spv::ExecutionModelGLCompute;
Chao Chen3c366992018-09-19 11:41:59 -0700287#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -0700288 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
289 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
290 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
291 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
292 case EShLangMissNV: return spv::ExecutionModelMissNV;
293 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700294 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
295 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
296#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600297 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700298 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600299 return spv::ExecutionModelFragment;
300 }
301}
302
John Kessenich140f3df2015-06-26 16:58:36 -0600303// Translate glslang sampler type to SPIR-V dimensionality.
304spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
305{
306 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700307 case glslang::Esd1D: return spv::Dim1D;
308 case glslang::Esd2D: return spv::Dim2D;
309 case glslang::Esd3D: return spv::Dim3D;
310 case glslang::EsdCube: return spv::DimCube;
311 case glslang::EsdRect: return spv::DimRect;
312 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700313 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600314 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700315 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600316 return spv::Dim2D;
317 }
318}
319
John Kessenichf6640762016-08-01 19:44:00 -0600320// Translate glslang precision to SPIR-V precision decorations.
321spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600322{
John Kessenichf6640762016-08-01 19:44:00 -0600323 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700324 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600325 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600326 default:
327 return spv::NoPrecision;
328 }
329}
330
John Kessenichf6640762016-08-01 19:44:00 -0600331// Translate glslang type to SPIR-V precision decorations.
332spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
333{
334 return TranslatePrecisionDecoration(type.getQualifier().precision);
335}
336
John Kessenich140f3df2015-06-26 16:58:36 -0600337// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600338spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600339{
340 if (type.getBasicType() == glslang::EbtBlock) {
341 switch (type.getQualifier().storage) {
342 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600343 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600344 case glslang::EvqVaryingIn: return spv::DecorationBlock;
345 case glslang::EvqVaryingOut: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700346#ifdef NV_EXTENSIONS
347 case glslang::EvqPayloadNV: return spv::DecorationBlock;
348 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
349 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700350 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
351 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700352#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600353 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700354 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600355 break;
356 }
357 }
358
John Kessenich4016e382016-07-15 11:53:56 -0600359 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600360}
361
Rex Xu1da878f2016-02-21 20:59:01 +0800362// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500363void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800364{
Jeff Bolz36831c92018-09-05 10:11:41 -0500365 if (!useVulkanMemoryModel) {
366 if (qualifier.coherent)
367 memory.push_back(spv::DecorationCoherent);
368 if (qualifier.volatil) {
369 memory.push_back(spv::DecorationVolatile);
370 memory.push_back(spv::DecorationCoherent);
371 }
John Kessenich14b85d32018-06-04 15:36:03 -0600372 }
Rex Xu1da878f2016-02-21 20:59:01 +0800373 if (qualifier.restrict)
374 memory.push_back(spv::DecorationRestrict);
375 if (qualifier.readonly)
376 memory.push_back(spv::DecorationNonWritable);
377 if (qualifier.writeonly)
378 memory.push_back(spv::DecorationNonReadable);
379}
380
John Kessenich140f3df2015-06-26 16:58:36 -0600381// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700382spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600383{
384 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700385 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600386 case glslang::ElmRowMajor:
387 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700388 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600389 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700390 default:
391 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600392 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600393 }
394 } else {
395 switch (type.getBasicType()) {
396 default:
John Kessenich4016e382016-07-15 11:53:56 -0600397 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600398 break;
399 case glslang::EbtBlock:
400 switch (type.getQualifier().storage) {
401 case glslang::EvqUniform:
402 case glslang::EvqBuffer:
403 switch (type.getQualifier().layoutPacking) {
404 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600405 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
406 default:
John Kessenich4016e382016-07-15 11:53:56 -0600407 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600408 }
409 case glslang::EvqVaryingIn:
410 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700411 if (type.getQualifier().isTaskMemory()) {
412 switch (type.getQualifier().layoutPacking) {
413 case glslang::ElpShared: return spv::DecorationGLSLShared;
414 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
415 default: break;
416 }
417 } else {
418 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
419 }
John Kessenich4016e382016-07-15 11:53:56 -0600420 return spv::DecorationMax;
Chao Chenb50c02e2018-09-19 11:42:24 -0700421#ifdef NV_EXTENSIONS
422 case glslang::EvqPayloadNV:
423 case glslang::EvqPayloadInNV:
424 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700425 case glslang::EvqCallableDataNV:
426 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700427 return spv::DecorationMax;
428#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600429 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700430 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600431 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600432 }
433 }
434 }
435}
436
437// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600438// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700439// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800440spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600441{
Rex Xubbceed72016-05-21 09:40:44 +0800442 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700443 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600444 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800445 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700446 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700447 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600448 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800449#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800450 else if (qualifier.explicitInterp) {
451 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800452 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800453 }
Rex Xu9d93a232016-05-05 12:30:44 +0800454#endif
Rex Xubbceed72016-05-21 09:40:44 +0800455 else
John Kessenich4016e382016-07-15 11:53:56 -0600456 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800457}
458
459// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600460// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800461// should be applied.
462spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
463{
464 if (qualifier.patch)
465 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700466 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600467 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700468 else if (qualifier.sample) {
469 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600470 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700471 } else
John Kessenich4016e382016-07-15 11:53:56 -0600472 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600473}
474
John Kessenich92187592016-02-01 13:45:25 -0700475// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700476spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600477{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700478 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600479 return spv::DecorationInvariant;
480 else
John Kessenich4016e382016-07-15 11:53:56 -0600481 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600482}
483
qining9220dbb2016-05-04 17:34:38 -0400484// If glslang type is noContraction, return SPIR-V NoContraction decoration.
485spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
486{
487 if (qualifier.noContraction)
488 return spv::DecorationNoContraction;
489 else
John Kessenich4016e382016-07-15 11:53:56 -0600490 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400491}
492
John Kessenich5611c6d2018-04-05 11:25:02 -0600493// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
494spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
495{
496 if (qualifier.isNonUniform()) {
497 builder.addExtension("SPV_EXT_descriptor_indexing");
498 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
499 return spv::DecorationNonUniformEXT;
500 } else
501 return spv::DecorationMax;
502}
503
Jeff Bolz36831c92018-09-05 10:11:41 -0500504spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
505{
506 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
507 return spv::MemoryAccessMaskNone;
508 }
509 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
510 if (coherentFlags.volatil ||
511 coherentFlags.coherent ||
512 coherentFlags.devicecoherent ||
513 coherentFlags.queuefamilycoherent ||
514 coherentFlags.workgroupcoherent ||
515 coherentFlags.subgroupcoherent) {
516 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
517 spv::MemoryAccessMakePointerVisibleKHRMask;
518 }
519 if (coherentFlags.nonprivate) {
520 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
521 }
522 if (coherentFlags.volatil) {
523 mask = mask | spv::MemoryAccessVolatileMask;
524 }
525 if (mask != spv::MemoryAccessMaskNone) {
526 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
527 }
528 return mask;
529}
530
531spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
532{
533 if (!glslangIntermediate->usingVulkanMemoryModel()) {
534 return spv::ImageOperandsMaskNone;
535 }
536 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
537 if (coherentFlags.volatil ||
538 coherentFlags.coherent ||
539 coherentFlags.devicecoherent ||
540 coherentFlags.queuefamilycoherent ||
541 coherentFlags.workgroupcoherent ||
542 coherentFlags.subgroupcoherent) {
543 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
544 spv::ImageOperandsMakeTexelVisibleKHRMask;
545 }
546 if (coherentFlags.nonprivate) {
547 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
548 }
549 if (coherentFlags.volatil) {
550 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
551 }
552 if (mask != spv::ImageOperandsMaskNone) {
553 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
554 }
555 return mask;
556}
557
558spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
559{
560 spv::Builder::AccessChain::CoherentFlags flags;
561 flags.coherent = type.getQualifier().coherent;
562 flags.devicecoherent = type.getQualifier().devicecoherent;
563 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
564 // shared variables are implicitly workgroupcoherent in GLSL.
565 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
566 type.getQualifier().storage == glslang::EvqShared;
567 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600568 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500569 // *coherent variables are implicitly nonprivate in GLSL
570 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500571 flags.subgroupcoherent ||
572 flags.workgroupcoherent ||
573 flags.queuefamilycoherent ||
574 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600575 flags.coherent ||
576 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500577 flags.isImage = type.getBasicType() == glslang::EbtSampler;
578 return flags;
579}
580
581spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
582{
583 spv::Scope scope;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600584 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500585 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
586 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
587 } else if (coherentFlags.devicecoherent) {
588 scope = spv::ScopeDevice;
589 } else if (coherentFlags.queuefamilycoherent) {
590 scope = spv::ScopeQueueFamilyKHR;
591 } else if (coherentFlags.workgroupcoherent) {
592 scope = spv::ScopeWorkgroup;
593 } else if (coherentFlags.subgroupcoherent) {
594 scope = spv::ScopeSubgroup;
595 } else {
596 scope = spv::ScopeMax;
597 }
598 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
599 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
600 }
601 return scope;
602}
603
David Netoa901ffe2016-06-08 14:11:40 +0100604// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
605// associated capabilities when required. For some built-in variables, a capability
606// is generated only when using the variable in an executable instruction, but not when
607// just declaring a struct member variable with it. This is true for PointSize,
608// ClipDistance, and CullDistance.
609spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600610{
611 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700612 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600613 // Defer adding the capability until the built-in is actually used.
614 if (! memberDeclaration) {
615 switch (glslangIntermediate->getStage()) {
616 case EShLangGeometry:
617 builder.addCapability(spv::CapabilityGeometryPointSize);
618 break;
619 case EShLangTessControl:
620 case EShLangTessEvaluation:
621 builder.addCapability(spv::CapabilityTessellationPointSize);
622 break;
623 default:
624 break;
625 }
John Kessenich92187592016-02-01 13:45:25 -0700626 }
627 return spv::BuiltInPointSize;
628
John Kessenichebb50532016-05-16 19:22:05 -0600629 // These *Distance capabilities logically belong here, but if the member is declared and
630 // then never used, consumers of SPIR-V prefer the capability not be declared.
631 // They are now generated when used, rather than here when declared.
632 // Potentially, the specification should be more clear what the minimum
633 // use needed is to trigger the capability.
634 //
John Kessenich92187592016-02-01 13:45:25 -0700635 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100636 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800637 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700638 return spv::BuiltInClipDistance;
639
640 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100641 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800642 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700643 return spv::BuiltInCullDistance;
644
645 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600646 builder.addCapability(spv::CapabilityMultiViewport);
647 if (glslangIntermediate->getStage() == EShLangVertex ||
648 glslangIntermediate->getStage() == EShLangTessControl ||
649 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800650
John Kessenichba6a3c22017-09-13 13:22:50 -0600651 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
652 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800653 }
John Kessenich92187592016-02-01 13:45:25 -0700654 return spv::BuiltInViewportIndex;
655
John Kessenich5e801132016-02-15 11:09:46 -0700656 case glslang::EbvSampleId:
657 builder.addCapability(spv::CapabilitySampleRateShading);
658 return spv::BuiltInSampleId;
659
660 case glslang::EbvSamplePosition:
661 builder.addCapability(spv::CapabilitySampleRateShading);
662 return spv::BuiltInSamplePosition;
663
664 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700665 return spv::BuiltInSampleMask;
666
John Kessenich78a45572016-07-08 14:05:15 -0600667 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700668#ifdef NV_EXTENSIONS
669 if (glslangIntermediate->getStage() == EShLangMeshNV) {
670 return spv::BuiltInLayer;
671 }
672#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600673 builder.addCapability(spv::CapabilityGeometry);
674 if (glslangIntermediate->getStage() == EShLangVertex ||
675 glslangIntermediate->getStage() == EShLangTessControl ||
676 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800677
John Kessenichba6a3c22017-09-13 13:22:50 -0600678 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
679 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800680 }
John Kessenich78a45572016-07-08 14:05:15 -0600681 return spv::BuiltInLayer;
682
John Kessenich140f3df2015-06-26 16:58:36 -0600683 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600684 case glslang::EbvVertexId: return spv::BuiltInVertexId;
685 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700686 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
687 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800688
John Kessenichda581a22015-10-14 14:10:30 -0600689 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700690 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800691 builder.addCapability(spv::CapabilityDrawParameters);
692 return spv::BuiltInBaseVertex;
693
John Kessenichda581a22015-10-14 14:10:30 -0600694 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700695 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800696 builder.addCapability(spv::CapabilityDrawParameters);
697 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200698
John Kessenichda581a22015-10-14 14:10:30 -0600699 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700700 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800701 builder.addCapability(spv::CapabilityDrawParameters);
702 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200703
704 case glslang::EbvPrimitiveId:
705 if (glslangIntermediate->getStage() == EShLangFragment)
706 builder.addCapability(spv::CapabilityGeometry);
707 return spv::BuiltInPrimitiveId;
708
Rex Xu37cdcee2017-06-29 17:46:34 +0800709 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800710 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
711 builder.addCapability(spv::CapabilityStencilExportEXT);
712 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800713
John Kessenich140f3df2015-06-26 16:58:36 -0600714 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600715 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
716 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
717 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
718 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
719 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
720 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
721 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600722 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
723 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
724 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
725 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
726 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
727 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
728 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
729 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800730
Rex Xu574ab042016-04-14 16:53:07 +0800731 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800732 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800733 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
734 return spv::BuiltInSubgroupSize;
735
Rex Xu574ab042016-04-14 16:53:07 +0800736 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800737 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800738 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
739 return spv::BuiltInSubgroupLocalInvocationId;
740
Rex Xu574ab042016-04-14 16:53:07 +0800741 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800742 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
743 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
744 return spv::BuiltInSubgroupEqMaskKHR;
745
Rex Xu574ab042016-04-14 16:53:07 +0800746 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800747 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
748 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
749 return spv::BuiltInSubgroupGeMaskKHR;
750
Rex Xu574ab042016-04-14 16:53:07 +0800751 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800752 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
753 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
754 return spv::BuiltInSubgroupGtMaskKHR;
755
Rex Xu574ab042016-04-14 16:53:07 +0800756 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800757 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
758 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
759 return spv::BuiltInSubgroupLeMaskKHR;
760
Rex Xu574ab042016-04-14 16:53:07 +0800761 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800762 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
763 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
764 return spv::BuiltInSubgroupLtMaskKHR;
765
John Kessenich66011cb2018-03-06 16:12:04 -0700766 case glslang::EbvNumSubgroups:
767 builder.addCapability(spv::CapabilityGroupNonUniform);
768 return spv::BuiltInNumSubgroups;
769
770 case glslang::EbvSubgroupID:
771 builder.addCapability(spv::CapabilityGroupNonUniform);
772 return spv::BuiltInSubgroupId;
773
774 case glslang::EbvSubgroupSize2:
775 builder.addCapability(spv::CapabilityGroupNonUniform);
776 return spv::BuiltInSubgroupSize;
777
778 case glslang::EbvSubgroupInvocation2:
779 builder.addCapability(spv::CapabilityGroupNonUniform);
780 return spv::BuiltInSubgroupLocalInvocationId;
781
782 case glslang::EbvSubgroupEqMask2:
783 builder.addCapability(spv::CapabilityGroupNonUniform);
784 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
785 return spv::BuiltInSubgroupEqMask;
786
787 case glslang::EbvSubgroupGeMask2:
788 builder.addCapability(spv::CapabilityGroupNonUniform);
789 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
790 return spv::BuiltInSubgroupGeMask;
791
792 case glslang::EbvSubgroupGtMask2:
793 builder.addCapability(spv::CapabilityGroupNonUniform);
794 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
795 return spv::BuiltInSubgroupGtMask;
796
797 case glslang::EbvSubgroupLeMask2:
798 builder.addCapability(spv::CapabilityGroupNonUniform);
799 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
800 return spv::BuiltInSubgroupLeMask;
801
802 case glslang::EbvSubgroupLtMask2:
803 builder.addCapability(spv::CapabilityGroupNonUniform);
804 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
805 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800806#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800807 case glslang::EbvBaryCoordNoPersp:
808 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
809 return spv::BuiltInBaryCoordNoPerspAMD;
810
811 case glslang::EbvBaryCoordNoPerspCentroid:
812 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
813 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
814
815 case glslang::EbvBaryCoordNoPerspSample:
816 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
817 return spv::BuiltInBaryCoordNoPerspSampleAMD;
818
819 case glslang::EbvBaryCoordSmooth:
820 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
821 return spv::BuiltInBaryCoordSmoothAMD;
822
823 case glslang::EbvBaryCoordSmoothCentroid:
824 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
825 return spv::BuiltInBaryCoordSmoothCentroidAMD;
826
827 case glslang::EbvBaryCoordSmoothSample:
828 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
829 return spv::BuiltInBaryCoordSmoothSampleAMD;
830
831 case glslang::EbvBaryCoordPullModel:
832 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
833 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800834#endif
chaoc771d89f2017-01-13 01:10:53 -0800835
John Kessenich6c8aaac2017-02-27 01:20:51 -0700836 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700837 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700838 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700839 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700840
841 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700842 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700843 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700844 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700845
Daniel Koch5154db52018-11-26 10:01:58 -0500846 case glslang::EbvFragSizeEXT:
847 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
848 builder.addCapability(spv::CapabilityFragmentDensityEXT);
849 return spv::BuiltInFragSizeEXT;
850
851 case glslang::EbvFragInvocationCountEXT:
852 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
853 builder.addCapability(spv::CapabilityFragmentDensityEXT);
854 return spv::BuiltInFragInvocationCountEXT;
855
chaoc771d89f2017-01-13 01:10:53 -0800856#ifdef NV_EXTENSIONS
857 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800858 if (!memberDeclaration) {
859 builder.addExtension(spv::E_SPV_NV_viewport_array2);
860 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
861 }
chaoc771d89f2017-01-13 01:10:53 -0800862 return spv::BuiltInViewportMaskNV;
863 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800864 if (!memberDeclaration) {
865 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
866 builder.addCapability(spv::CapabilityShaderStereoViewNV);
867 }
chaoc771d89f2017-01-13 01:10:53 -0800868 return spv::BuiltInSecondaryPositionNV;
869 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800870 if (!memberDeclaration) {
871 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
872 builder.addCapability(spv::CapabilityShaderStereoViewNV);
873 }
chaoc771d89f2017-01-13 01:10:53 -0800874 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800875 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800876 if (!memberDeclaration) {
877 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
878 builder.addCapability(spv::CapabilityPerViewAttributesNV);
879 }
chaocdf3956c2017-02-14 14:52:34 -0800880 return spv::BuiltInPositionPerViewNV;
881 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800882 if (!memberDeclaration) {
883 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
884 builder.addCapability(spv::CapabilityPerViewAttributesNV);
885 }
chaocdf3956c2017-02-14 14:52:34 -0800886 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700887 case glslang::EbvFragFullyCoveredNV:
888 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
889 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
890 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700891 case glslang::EbvFragmentSizeNV:
892 builder.addExtension(spv::E_SPV_NV_shading_rate);
893 builder.addCapability(spv::CapabilityShadingRateNV);
894 return spv::BuiltInFragmentSizeNV;
895 case glslang::EbvInvocationsPerPixelNV:
896 builder.addExtension(spv::E_SPV_NV_shading_rate);
897 builder.addCapability(spv::CapabilityShadingRateNV);
898 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700899
900 // raytracing
901 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700902 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700903 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700904 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700905 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700906 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700907 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700908 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700909 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700910 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700911 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700912 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700913 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700914 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700915 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700916 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700917 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700918 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700919 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700920 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700921 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700922 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700923 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700924 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700925 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700926 return spv::BuiltInWorldToObjectNV;
927 case glslang::EbvIncomingRayFlagsNV:
928 return spv::BuiltInIncomingRayFlagsNV;
Chao Chen9eada4b2018-09-19 11:39:56 -0700929 case glslang::EbvBaryCoordNV:
930 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
931 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
932 return spv::BuiltInBaryCoordNV;
933 case glslang::EbvBaryCoordNoPerspNV:
934 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
935 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
936 return spv::BuiltInBaryCoordNoPerspNV;
Chao Chen3c366992018-09-19 11:41:59 -0700937 case glslang::EbvTaskCountNV:
938 return spv::BuiltInTaskCountNV;
939 case glslang::EbvPrimitiveCountNV:
940 return spv::BuiltInPrimitiveCountNV;
941 case glslang::EbvPrimitiveIndicesNV:
942 return spv::BuiltInPrimitiveIndicesNV;
943 case glslang::EbvClipDistancePerViewNV:
944 return spv::BuiltInClipDistancePerViewNV;
945 case glslang::EbvCullDistancePerViewNV:
946 return spv::BuiltInCullDistancePerViewNV;
947 case glslang::EbvLayerPerViewNV:
948 return spv::BuiltInLayerPerViewNV;
949 case glslang::EbvMeshViewCountNV:
950 return spv::BuiltInMeshViewCountNV;
951 case glslang::EbvMeshViewIndicesNV:
952 return spv::BuiltInMeshViewIndicesNV;
chaoc771d89f2017-01-13 01:10:53 -0800953#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800954 default:
955 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600956 }
957}
958
Rex Xufc618912015-09-09 16:42:49 +0800959// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700960spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800961{
962 assert(type.getBasicType() == glslang::EbtSampler);
963
John Kessenich5d0fa972016-02-15 11:57:00 -0700964 // Check for capabilities
965 switch (type.getQualifier().layoutFormat) {
966 case glslang::ElfRg32f:
967 case glslang::ElfRg16f:
968 case glslang::ElfR11fG11fB10f:
969 case glslang::ElfR16f:
970 case glslang::ElfRgba16:
971 case glslang::ElfRgb10A2:
972 case glslang::ElfRg16:
973 case glslang::ElfRg8:
974 case glslang::ElfR16:
975 case glslang::ElfR8:
976 case glslang::ElfRgba16Snorm:
977 case glslang::ElfRg16Snorm:
978 case glslang::ElfRg8Snorm:
979 case glslang::ElfR16Snorm:
980 case glslang::ElfR8Snorm:
981
982 case glslang::ElfRg32i:
983 case glslang::ElfRg16i:
984 case glslang::ElfRg8i:
985 case glslang::ElfR16i:
986 case glslang::ElfR8i:
987
988 case glslang::ElfRgb10a2ui:
989 case glslang::ElfRg32ui:
990 case glslang::ElfRg16ui:
991 case glslang::ElfRg8ui:
992 case glslang::ElfR16ui:
993 case glslang::ElfR8ui:
994 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
995 break;
996
997 default:
998 break;
999 }
1000
1001 // do the translation
Rex Xufc618912015-09-09 16:42:49 +08001002 switch (type.getQualifier().layoutFormat) {
1003 case glslang::ElfNone: return spv::ImageFormatUnknown;
1004 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1005 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1006 case glslang::ElfR32f: return spv::ImageFormatR32f;
1007 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1008 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1009 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1010 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1011 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1012 case glslang::ElfR16f: return spv::ImageFormatR16f;
1013 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1014 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1015 case glslang::ElfRg16: return spv::ImageFormatRg16;
1016 case glslang::ElfRg8: return spv::ImageFormatRg8;
1017 case glslang::ElfR16: return spv::ImageFormatR16;
1018 case glslang::ElfR8: return spv::ImageFormatR8;
1019 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1020 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1021 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1022 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1023 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1024 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1025 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1026 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1027 case glslang::ElfR32i: return spv::ImageFormatR32i;
1028 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1029 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1030 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1031 case glslang::ElfR16i: return spv::ImageFormatR16i;
1032 case glslang::ElfR8i: return spv::ImageFormatR8i;
1033 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1034 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1035 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1036 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1037 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1038 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1039 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1040 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1041 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1042 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001043 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001044 }
1045}
1046
John Kesseniche18fd202018-01-30 11:01:39 -07001047spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001048{
John Kesseniche18fd202018-01-30 11:01:39 -07001049 if (selectionNode.getFlatten())
1050 return spv::SelectionControlFlattenMask;
1051 if (selectionNode.getDontFlatten())
1052 return spv::SelectionControlDontFlattenMask;
1053 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001054}
1055
John Kesseniche18fd202018-01-30 11:01:39 -07001056spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001057{
John Kesseniche18fd202018-01-30 11:01:39 -07001058 if (switchNode.getFlatten())
1059 return spv::SelectionControlFlattenMask;
1060 if (switchNode.getDontFlatten())
1061 return spv::SelectionControlDontFlattenMask;
1062 return spv::SelectionControlMaskNone;
1063}
1064
John Kessenicha2858d92018-01-31 08:11:18 -07001065// return a non-0 dependency if the dependency argument must be set
1066spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
1067 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -07001068{
1069 spv::LoopControlMask control = spv::LoopControlMaskNone;
1070
1071 if (loopNode.getDontUnroll())
1072 control = control | spv::LoopControlDontUnrollMask;
1073 if (loopNode.getUnroll())
1074 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001075 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001076 control = control | spv::LoopControlDependencyInfiniteMask;
1077 else if (loopNode.getLoopDependency() > 0) {
1078 control = control | spv::LoopControlDependencyLengthMask;
1079 dependencyLength = loopNode.getLoopDependency();
1080 }
John Kesseniche18fd202018-01-30 11:01:39 -07001081
1082 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001083}
1084
John Kessenicha5c5fb62017-05-05 05:09:58 -06001085// Translate glslang type to SPIR-V storage class.
1086spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1087{
1088 if (type.getQualifier().isPipeInput())
1089 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001090 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001091 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001092
1093 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1094 type.getQualifier().storage == glslang::EvqUniform) {
1095 if (type.getBasicType() == glslang::EbtAtomicUint)
1096 return spv::StorageClassAtomicCounter;
1097 if (type.containsOpaque())
1098 return spv::StorageClassUniformConstant;
1099 }
1100
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001101#ifdef NV_EXTENSIONS
1102 if (type.getQualifier().isUniformOrBuffer() &&
1103 type.getQualifier().layoutShaderRecordNV) {
1104 return spv::StorageClassShaderRecordBufferNV;
1105 }
1106#endif
1107
John Kessenichbed4e4f2017-09-08 02:38:07 -06001108 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001109 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001110 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001111 }
1112
1113 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001114 if (type.getQualifier().layoutPushConstant)
1115 return spv::StorageClassPushConstant;
1116 if (type.getBasicType() == glslang::EbtBlock)
1117 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001118 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001119 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001120
1121 switch (type.getQualifier().storage) {
1122 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1123 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1124 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1125 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001126#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001127 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1128 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1129 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1130 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1131 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001132#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001133 default:
1134 assert(0);
1135 break;
1136 }
1137
1138 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001139}
1140
John Kessenich5611c6d2018-04-05 11:25:02 -06001141// Add capabilities pertaining to how an array is indexed.
1142void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1143 const glslang::TType& indexType)
1144{
1145 if (indexType.getQualifier().isNonUniform()) {
1146 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001147 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001148 if (baseType.getBasicType() == glslang::EbtSampler) {
1149 if (baseType.getQualifier().hasAttachment())
1150 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1151 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1152 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1153 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1154 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1155 else if (baseType.isImage())
1156 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1157 else if (baseType.isTexture())
1158 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1159 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1160 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1161 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1162 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1163 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1164 }
1165 } else {
1166 // assume a dynamically uniform index
1167 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001168 if (baseType.getQualifier().hasAttachment()) {
1169 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001170 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001171 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1172 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001173 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001174 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1175 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001176 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001177 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001178 }
1179 }
1180}
1181
qining25262b32016-05-06 17:25:16 -04001182// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001183// descriptor set.
1184bool IsDescriptorResource(const glslang::TType& type)
1185{
John Kessenichf7497e22016-03-08 21:36:22 -07001186 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001187 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001188 return type.getQualifier().isUniformOrBuffer() &&
1189#ifdef NV_EXTENSIONS
1190 ! type.getQualifier().layoutShaderRecordNV &&
1191#endif
1192 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001193
1194 // non block...
1195 // basically samplerXXX/subpass/sampler/texture are all included
1196 // if they are the global-scope-class, not the function parameter
1197 // (or local, if they ever exist) class.
1198 if (type.getBasicType() == glslang::EbtSampler)
1199 return type.getQualifier().isUniformOrBuffer();
1200
1201 // None of the above.
1202 return false;
1203}
1204
John Kesseniche0b6cad2015-12-24 10:30:13 -07001205void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1206{
1207 if (child.layoutMatrix == glslang::ElmNone)
1208 child.layoutMatrix = parent.layoutMatrix;
1209
1210 if (parent.invariant)
1211 child.invariant = true;
1212 if (parent.nopersp)
1213 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001214#ifdef AMD_EXTENSIONS
1215 if (parent.explicitInterp)
1216 child.explicitInterp = true;
1217#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001218 if (parent.flat)
1219 child.flat = true;
1220 if (parent.centroid)
1221 child.centroid = true;
1222 if (parent.patch)
1223 child.patch = true;
1224 if (parent.sample)
1225 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001226 if (parent.coherent)
1227 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001228 if (parent.devicecoherent)
1229 child.devicecoherent = true;
1230 if (parent.queuefamilycoherent)
1231 child.queuefamilycoherent = true;
1232 if (parent.workgroupcoherent)
1233 child.workgroupcoherent = true;
1234 if (parent.subgroupcoherent)
1235 child.subgroupcoherent = true;
1236 if (parent.nonprivate)
1237 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001238 if (parent.volatil)
1239 child.volatil = true;
1240 if (parent.restrict)
1241 child.restrict = true;
1242 if (parent.readonly)
1243 child.readonly = true;
1244 if (parent.writeonly)
1245 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001246#ifdef NV_EXTENSIONS
1247 if (parent.perPrimitiveNV)
1248 child.perPrimitiveNV = true;
1249 if (parent.perViewNV)
1250 child.perViewNV = true;
1251 if (parent.perTaskNV)
1252 child.perTaskNV = true;
1253#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001254}
1255
John Kessenichf2b7f332016-09-01 17:05:23 -06001256bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001257{
John Kessenich7b9fa252016-01-21 18:56:57 -07001258 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001259 // - struct members might inherit from a struct declaration
1260 // (note that non-block structs don't explicitly inherit,
1261 // only implicitly, meaning no decoration involved)
1262 // - affect decorations on the struct members
1263 // (note smooth does not, and expecting something like volatile
1264 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001265 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001266 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001267}
1268
John Kessenich140f3df2015-06-26 16:58:36 -06001269//
1270// Implement the TGlslangToSpvTraverser class.
1271//
1272
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001273TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001274 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1275 : TIntermTraverser(true, false, true),
1276 options(options),
1277 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001278 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001279 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001280 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001281 glslangIntermediate(glslangIntermediate)
1282{
1283 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1284
1285 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001286 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1287 glslangIntermediate->getVersion());
1288
John Kessenich121853f2017-05-31 17:11:16 -06001289 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001290 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001291 builder.setSourceFile(glslangIntermediate->getSourceFile());
1292
1293 // Set the source shader's text. If for SPV version 1.0, include
1294 // a preamble in comments stating the OpModuleProcessed instructions.
1295 // Otherwise, emit those as actual instructions.
1296 std::string text;
1297 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1298 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001299 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001300 text.append("// OpModuleProcessed ");
1301 text.append(processes[p]);
1302 text.append("\n");
1303 } else
1304 builder.addModuleProcessed(processes[p]);
1305 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001306 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001307 text.append("#line 1\n");
1308 text.append(glslangIntermediate->getSourceText());
1309 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001310 // Pass name and text for all included files
1311 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1312 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1313 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001314 }
John Kessenich140f3df2015-06-26 16:58:36 -06001315 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001316
1317 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1318 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1319
1320 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1321 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1322 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1323 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1324 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001325 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001326 memoryModel = spv::MemoryModelVulkanKHR;
1327 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001328 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001329 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001330 builder.setMemoryModel(addressingModel, memoryModel);
1331
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001332 if (glslangIntermediate->usingVariablePointers()) {
1333 builder.addCapability(spv::CapabilityVariablePointers);
1334 }
1335
John Kessenicheee9d532016-09-19 18:09:30 -06001336 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1337 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001338
1339 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001340 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1341 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001342 builder.addSourceExtension(it->c_str());
1343
1344 // Add the top-level modes for this shader.
1345
John Kessenich92187592016-02-01 13:45:25 -07001346 if (glslangIntermediate->getXfbMode()) {
1347 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001348 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001349 }
John Kessenich140f3df2015-06-26 16:58:36 -06001350
1351 unsigned int mode;
1352 switch (glslangIntermediate->getStage()) {
1353 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001354 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001355 break;
1356
steve-lunarge7412492017-03-23 11:56:07 -06001357 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001358 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001359 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001360
steve-lunarge7412492017-03-23 11:56:07 -06001361 glslang::TLayoutGeometry primitive;
1362
1363 if (glslangIntermediate->getStage() == EShLangTessControl) {
1364 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1365 primitive = glslangIntermediate->getOutputPrimitive();
1366 } else {
1367 primitive = glslangIntermediate->getInputPrimitive();
1368 }
1369
1370 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001371 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1372 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1373 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001374 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001375 }
John Kessenich4016e382016-07-15 11:53:56 -06001376 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001377 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1378
John Kesseniche6903322015-10-13 16:29:02 -06001379 switch (glslangIntermediate->getVertexSpacing()) {
1380 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1381 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1382 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001383 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001384 }
John Kessenich4016e382016-07-15 11:53:56 -06001385 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001386 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1387
1388 switch (glslangIntermediate->getVertexOrder()) {
1389 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1390 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001391 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001392 }
John Kessenich4016e382016-07-15 11:53:56 -06001393 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001394 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1395
1396 if (glslangIntermediate->getPointMode())
1397 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001398 break;
1399
1400 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001401 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001402 switch (glslangIntermediate->getInputPrimitive()) {
1403 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1404 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1405 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001406 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001407 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001408 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001409 }
John Kessenich4016e382016-07-15 11:53:56 -06001410 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001411 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001412
John Kessenich140f3df2015-06-26 16:58:36 -06001413 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1414
1415 switch (glslangIntermediate->getOutputPrimitive()) {
1416 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1417 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1418 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001419 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001420 }
John Kessenich4016e382016-07-15 11:53:56 -06001421 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001422 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1423 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1424 break;
1425
1426 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001427 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001428 if (glslangIntermediate->getPixelCenterInteger())
1429 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001430
John Kessenich140f3df2015-06-26 16:58:36 -06001431 if (glslangIntermediate->getOriginUpperLeft())
1432 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001433 else
1434 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001435
1436 if (glslangIntermediate->getEarlyFragmentTests())
1437 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1438
chaocc1204522017-06-30 17:14:30 -07001439 if (glslangIntermediate->getPostDepthCoverage()) {
1440 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1441 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1442 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1443 }
1444
John Kesseniche6903322015-10-13 16:29:02 -06001445 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001446 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1447 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001448 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001449 }
John Kessenich4016e382016-07-15 11:53:56 -06001450 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001451 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1452
1453 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1454 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001455 break;
1456
1457 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001458 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001459 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1460 glslangIntermediate->getLocalSize(1),
1461 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001462#ifdef NV_EXTENSIONS
1463 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1464 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1465 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1466 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1467 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1468 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1469 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1470 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1471 }
1472#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001473 break;
1474
Chao Chen3c366992018-09-19 11:41:59 -07001475#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001476 case EShLangRayGenNV:
1477 case EShLangIntersectNV:
1478 case EShLangAnyHitNV:
1479 case EShLangClosestHitNV:
1480 case EShLangMissNV:
1481 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001482 builder.addCapability(spv::CapabilityRayTracingNV);
1483 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001484 break;
Chao Chen3c366992018-09-19 11:41:59 -07001485 case EShLangTaskNV:
1486 case EShLangMeshNV:
1487 builder.addCapability(spv::CapabilityMeshShadingNV);
1488 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1489 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1490 glslangIntermediate->getLocalSize(1),
1491 glslangIntermediate->getLocalSize(2));
1492 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1493 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1494 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1495
1496 switch (glslangIntermediate->getOutputPrimitive()) {
1497 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1498 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1499 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1500 default: mode = spv::ExecutionModeMax; break;
1501 }
1502 if (mode != spv::ExecutionModeMax)
1503 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1504 }
1505 break;
1506#endif
1507
John Kessenich140f3df2015-06-26 16:58:36 -06001508 default:
1509 break;
1510 }
John Kessenich140f3df2015-06-26 16:58:36 -06001511}
1512
John Kessenichfca82622016-11-26 13:23:20 -07001513// Finish creating SPV, after the traversal is complete.
1514void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001515{
John Kessenichf04c51b2018-08-03 15:56:12 -06001516 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001517 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001518 builder.setBuildPoint(shaderEntry->getLastBlock());
1519 builder.leaveFunction();
1520 }
1521
John Kessenich7ba63412015-12-20 17:37:07 -07001522 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001523 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1524 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001525
John Kessenichf04c51b2018-08-03 15:56:12 -06001526 // Add capabilities, extensions, remove unneeded decorations, etc.,
1527 // based on the resulting SPIR-V.
1528 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001529}
1530
John Kessenichfca82622016-11-26 13:23:20 -07001531// Write the SPV into 'out'.
1532void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001533{
John Kessenichfca82622016-11-26 13:23:20 -07001534 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001535}
1536
1537//
1538// Implement the traversal functions.
1539//
1540// Return true from interior nodes to have the external traversal
1541// continue on to children. Return false if children were
1542// already processed.
1543//
1544
1545//
qining25262b32016-05-06 17:25:16 -04001546// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001547// - uniform/input reads
1548// - output writes
1549// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1550// - something simple that degenerates into the last bullet
1551//
1552void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1553{
qining75d1d802016-04-06 14:42:01 -04001554 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1555 if (symbol->getType().getQualifier().isSpecConstant())
1556 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1557
John Kessenich140f3df2015-06-26 16:58:36 -06001558 // getSymbolId() will set up all the IO decorations on the first call.
1559 // Formal function parameters were mapped during makeFunctions().
1560 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001561
1562 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1563 if (builder.isPointer(id)) {
1564 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001565 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1566 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1567 iOSet.insert(id);
1568 }
John Kessenich7ba63412015-12-20 17:37:07 -07001569 }
1570
1571 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001572 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001573 // Prepare to generate code for the access
1574
1575 // L-value chains will be computed left to right. We're on the symbol now,
1576 // which is the left-most part of the access chain, so now is "clear" time,
1577 // followed by setting the base.
1578 builder.clearAccessChain();
1579
1580 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001581 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001582 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001583 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001584 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001585 // These are also pure R-values.
1586 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001587 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001588 builder.setAccessChainRValue(id);
1589 else
1590 builder.setAccessChainLValue(id);
1591 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001592
1593 // Process linkage-only nodes for any special additional interface work.
1594 if (linkageOnly) {
1595 if (glslangIntermediate->getHlslFunctionality1()) {
1596 // Map implicit counter buffers to their originating buffers, which should have been
1597 // seen by now, given earlier pruning of unused counters, and preservation of order
1598 // of declaration.
1599 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1600 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1601 // Save possible originating buffers for counter buffers, keyed by
1602 // making the potential counter-buffer name.
1603 std::string keyName = symbol->getName().c_str();
1604 keyName = glslangIntermediate->addCounterBufferName(keyName);
1605 counterOriginator[keyName] = symbol;
1606 } else {
1607 // Handle a counter buffer, by finding the saved originating buffer.
1608 std::string keyName = symbol->getName().c_str();
1609 auto it = counterOriginator.find(keyName);
1610 if (it != counterOriginator.end()) {
1611 id = getSymbolId(it->second);
1612 if (id != spv::NoResult) {
1613 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001614 if (counterId != spv::NoResult) {
1615 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001616 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001617 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001618 }
1619 }
1620 }
1621 }
1622 }
1623 }
John Kessenich140f3df2015-06-26 16:58:36 -06001624}
1625
1626bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1627{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001628 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001629
qining40887662016-04-03 22:20:42 -04001630 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1631 if (node->getType().getQualifier().isSpecConstant())
1632 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1633
John Kessenich140f3df2015-06-26 16:58:36 -06001634 // First, handle special cases
1635 switch (node->getOp()) {
1636 case glslang::EOpAssign:
1637 case glslang::EOpAddAssign:
1638 case glslang::EOpSubAssign:
1639 case glslang::EOpMulAssign:
1640 case glslang::EOpVectorTimesMatrixAssign:
1641 case glslang::EOpVectorTimesScalarAssign:
1642 case glslang::EOpMatrixTimesScalarAssign:
1643 case glslang::EOpMatrixTimesMatrixAssign:
1644 case glslang::EOpDivAssign:
1645 case glslang::EOpModAssign:
1646 case glslang::EOpAndAssign:
1647 case glslang::EOpInclusiveOrAssign:
1648 case glslang::EOpExclusiveOrAssign:
1649 case glslang::EOpLeftShiftAssign:
1650 case glslang::EOpRightShiftAssign:
1651 // A bin-op assign "a += b" means the same thing as "a = a + b"
1652 // where a is evaluated before b. For a simple assignment, GLSL
1653 // says to evaluate the left before the right. So, always, left
1654 // node then right node.
1655 {
1656 // get the left l-value, save it away
1657 builder.clearAccessChain();
1658 node->getLeft()->traverse(this);
1659 spv::Builder::AccessChain lValue = builder.getAccessChain();
1660
1661 // evaluate the right
1662 builder.clearAccessChain();
1663 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001664 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001665
1666 if (node->getOp() != glslang::EOpAssign) {
1667 // the left is also an r-value
1668 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001669 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001670
1671 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001672 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001673 TranslateNoContractionDecoration(node->getType().getQualifier()),
1674 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001675 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001676 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1677 node->getType().getBasicType());
1678
1679 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001680 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001681 }
1682
1683 // store the result
1684 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001685 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001686
1687 // assignments are expressions having an rValue after they are evaluated...
1688 builder.clearAccessChain();
1689 builder.setAccessChainRValue(rValue);
1690 }
1691 return false;
1692 case glslang::EOpIndexDirect:
1693 case glslang::EOpIndexDirectStruct:
1694 {
1695 // Get the left part of the access chain.
1696 node->getLeft()->traverse(this);
1697
1698 // Add the next element in the chain
1699
David Netoa901ffe2016-06-08 14:11:40 +01001700 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001701 if (! node->getLeft()->getType().isArray() &&
1702 node->getLeft()->getType().isVector() &&
1703 node->getOp() == glslang::EOpIndexDirect) {
1704 // This is essentially a hard-coded vector swizzle of size 1,
1705 // so short circuit the access-chain stuff with a swizzle.
1706 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001707 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001708 int dummySize;
1709 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1710 TranslateCoherent(node->getLeft()->getType()),
1711 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001712 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001713
1714 // Load through a block reference is performed with a dot operator that
1715 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1716 // do a load and reset the access chain.
1717 if (node->getLeft()->getBasicType() == glslang::EbtReference &&
1718 !node->getLeft()->getType().isArray() &&
1719 node->getOp() == glslang::EOpIndexDirectStruct)
1720 {
1721 spv::Id left = accessChainLoad(node->getLeft()->getType());
1722 builder.clearAccessChain();
1723 builder.setAccessChainLValue(left);
1724 }
1725
David Netoa901ffe2016-06-08 14:11:40 +01001726 int spvIndex = glslangIndex;
1727 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1728 node->getOp() == glslang::EOpIndexDirectStruct)
1729 {
1730 // This may be, e.g., an anonymous block-member selection, which generally need
1731 // index remapping due to hidden members in anonymous blocks.
1732 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1733 assert(remapper.size() > 0);
1734 spvIndex = remapper[glslangIndex];
1735 }
John Kessenichebb50532016-05-16 19:22:05 -06001736
David Netoa901ffe2016-06-08 14:11:40 +01001737 // normal case for indexing array or structure or block
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001738 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), getBufferReferenceAlignment(node->getLeft()->getType()));
David Netoa901ffe2016-06-08 14:11:40 +01001739
1740 // Add capabilities here for accessing PointSize and clip/cull distance.
1741 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001742 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001743 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001744 }
1745 }
1746 return false;
1747 case glslang::EOpIndexIndirect:
1748 {
1749 // Structure or array or vector indirection.
1750 // Will use native SPIR-V access-chain for struct and array indirection;
1751 // matrices are arrays of vectors, so will also work for a matrix.
1752 // Will use the access chain's 'component' for variable index into a vector.
1753
1754 // This adapter is building access chains left to right.
1755 // Set up the access chain to the left.
1756 node->getLeft()->traverse(this);
1757
1758 // save it so that computing the right side doesn't trash it
1759 spv::Builder::AccessChain partial = builder.getAccessChain();
1760
1761 // compute the next index in the chain
1762 builder.clearAccessChain();
1763 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001764 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001765
John Kessenich5611c6d2018-04-05 11:25:02 -06001766 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1767
John Kessenich140f3df2015-06-26 16:58:36 -06001768 // restore the saved access chain
1769 builder.setAccessChain(partial);
1770
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001771 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1772 int dummySize;
1773 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1774 TranslateCoherent(node->getLeft()->getType()),
1775 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1776 } else
1777 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), getBufferReferenceAlignment(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001778 }
1779 return false;
1780 case glslang::EOpVectorSwizzle:
1781 {
1782 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001783 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001784 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001785 int dummySize;
1786 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1787 TranslateCoherent(node->getLeft()->getType()),
1788 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001789 }
1790 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001791 case glslang::EOpMatrixSwizzle:
1792 logger->missingFunctionality("matrix swizzle");
1793 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001794 case glslang::EOpLogicalOr:
1795 case glslang::EOpLogicalAnd:
1796 {
1797
1798 // These may require short circuiting, but can sometimes be done as straight
1799 // binary operations. The right operand must be short circuited if it has
1800 // side effects, and should probably be if it is complex.
1801 if (isTrivial(node->getRight()->getAsTyped()))
1802 break; // handle below as a normal binary operation
1803 // otherwise, we need to do dynamic short circuiting on the right operand
1804 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1805 builder.clearAccessChain();
1806 builder.setAccessChainRValue(result);
1807 }
1808 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001809 default:
1810 break;
1811 }
1812
1813 // Assume generic binary op...
1814
John Kessenich32cfd492016-02-02 12:37:46 -07001815 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001816 builder.clearAccessChain();
1817 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001818 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001819
John Kessenich32cfd492016-02-02 12:37:46 -07001820 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001821 builder.clearAccessChain();
1822 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001823 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001824
John Kessenich32cfd492016-02-02 12:37:46 -07001825 // get result
John Kessenichead86222018-03-28 18:01:20 -06001826 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001827 TranslateNoContractionDecoration(node->getType().getQualifier()),
1828 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001829 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001830 convertGlslangToSpvType(node->getType()), left, right,
1831 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001832
John Kessenich50e57562015-12-21 21:21:11 -07001833 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001834 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001835 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001836 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001837 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001838 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001839 return false;
1840 }
John Kessenich140f3df2015-06-26 16:58:36 -06001841}
1842
1843bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1844{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001845 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001846
qining40887662016-04-03 22:20:42 -04001847 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1848 if (node->getType().getQualifier().isSpecConstant())
1849 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1850
John Kessenichfc51d282015-08-19 13:34:18 -06001851 spv::Id result = spv::NoResult;
1852
1853 // try texturing first
1854 result = createImageTextureFunctionCall(node);
1855 if (result != spv::NoResult) {
1856 builder.clearAccessChain();
1857 builder.setAccessChainRValue(result);
1858
1859 return false; // done with this node
1860 }
1861
1862 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001863
1864 if (node->getOp() == glslang::EOpArrayLength) {
1865 // Quite special; won't want to evaluate the operand.
1866
John Kessenich5611c6d2018-04-05 11:25:02 -06001867 // Currently, the front-end does not allow .length() on an array until it is sized,
1868 // except for the last block membeor of an SSBO.
1869 // TODO: If this changes, link-time sized arrays might show up here, and need their
1870 // size extracted.
1871
John Kessenichc9a80832015-09-12 12:17:44 -06001872 // Normal .length() would have been constant folded by the front-end.
1873 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001874 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001875
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001876 spv::Id length;
1877 if (node->getOperand()->getType().isCoopMat()) {
1878 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1879
1880 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
1881 assert(builder.isCooperativeMatrixType(typeId));
1882
1883 length = builder.createCooperativeMatrixLength(typeId);
1884 } else {
1885 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1886 block->traverse(this);
1887 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1888 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
1889 }
John Kessenichc9a80832015-09-12 12:17:44 -06001890
John Kessenich8c869672018-11-28 07:01:37 -07001891 // GLSL semantics say the result of .length() is an int, while SPIR-V says
1892 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
1893 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001894 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
1895 if (builder.isInSpecConstCodeGenMode()) {
1896 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
1897 } else {
1898 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
1899 }
1900 }
John Kessenich8c869672018-11-28 07:01:37 -07001901
John Kessenichc9a80832015-09-12 12:17:44 -06001902 builder.clearAccessChain();
1903 builder.setAccessChainRValue(length);
1904
1905 return false;
1906 }
1907
John Kessenichfc51d282015-08-19 13:34:18 -06001908 // Start by evaluating the operand
1909
John Kessenich8c8505c2016-07-26 12:50:38 -06001910 // Does it need a swizzle inversion? If so, evaluation is inverted;
1911 // operate first on the swizzle base, then apply the swizzle.
1912 spv::Id invertedType = spv::NoType;
1913 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1914 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1915 invertedType = getInvertedSwizzleType(*node->getOperand());
1916
John Kessenich140f3df2015-06-26 16:58:36 -06001917 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001918 if (invertedType != spv::NoType)
1919 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1920 else
1921 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001922
Rex Xufc618912015-09-09 16:42:49 +08001923 spv::Id operand = spv::NoResult;
1924
1925 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1926 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001927 node->getOp() == glslang::EOpAtomicCounter ||
1928 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001929 operand = builder.accessChainGetLValue(); // Special case l-value operands
1930 else
John Kessenich32cfd492016-02-02 12:37:46 -07001931 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001932
John Kessenichead86222018-03-28 18:01:20 -06001933 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001934 TranslateNoContractionDecoration(node->getType().getQualifier()),
1935 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001936
1937 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001938 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001939 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001940
1941 // if not, then possibly an operation
1942 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001943 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001944
1945 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001946 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001947 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001948 builder.addDecoration(result, decorations.nonUniform);
1949 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001950
John Kessenich140f3df2015-06-26 16:58:36 -06001951 builder.clearAccessChain();
1952 builder.setAccessChainRValue(result);
1953
1954 return false; // done with this node
1955 }
1956
1957 // it must be a special case, check...
1958 switch (node->getOp()) {
1959 case glslang::EOpPostIncrement:
1960 case glslang::EOpPostDecrement:
1961 case glslang::EOpPreIncrement:
1962 case glslang::EOpPreDecrement:
1963 {
1964 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001965 spv::Id one = 0;
1966 if (node->getBasicType() == glslang::EbtFloat)
1967 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001968 else if (node->getBasicType() == glslang::EbtDouble)
1969 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001970 else if (node->getBasicType() == glslang::EbtFloat16)
1971 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001972 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1973 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001974 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1975 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001976 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1977 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001978 else
1979 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001980 glslang::TOperator op;
1981 if (node->getOp() == glslang::EOpPreIncrement ||
1982 node->getOp() == glslang::EOpPostIncrement)
1983 op = glslang::EOpAdd;
1984 else
1985 op = glslang::EOpSub;
1986
John Kessenichead86222018-03-28 18:01:20 -06001987 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001988 convertGlslangToSpvType(node->getType()), operand, one,
1989 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001990 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001991
1992 // The result of operation is always stored, but conditionally the
1993 // consumed result. The consumed result is always an r-value.
1994 builder.accessChainStore(result);
1995 builder.clearAccessChain();
1996 if (node->getOp() == glslang::EOpPreIncrement ||
1997 node->getOp() == glslang::EOpPreDecrement)
1998 builder.setAccessChainRValue(result);
1999 else
2000 builder.setAccessChainRValue(operand);
2001 }
2002
2003 return false;
2004
2005 case glslang::EOpEmitStreamVertex:
2006 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2007 return false;
2008 case glslang::EOpEndStreamPrimitive:
2009 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2010 return false;
2011
2012 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002013 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002014 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002015 }
John Kessenich140f3df2015-06-26 16:58:36 -06002016}
2017
2018bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2019{
qining27e04a02016-04-14 16:40:20 -04002020 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2021 if (node->getType().getQualifier().isSpecConstant())
2022 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2023
John Kessenichfc51d282015-08-19 13:34:18 -06002024 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002025 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2026 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002027
2028 // try texturing
2029 result = createImageTextureFunctionCall(node);
2030 if (result != spv::NoResult) {
2031 builder.clearAccessChain();
2032 builder.setAccessChainRValue(result);
2033
2034 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05002035 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08002036#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05002037 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08002038#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05002039 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002040 // "imageStore" is a special case, which has no result
2041 return false;
2042 }
John Kessenichfc51d282015-08-19 13:34:18 -06002043
John Kessenich140f3df2015-06-26 16:58:36 -06002044 glslang::TOperator binOp = glslang::EOpNull;
2045 bool reduceComparison = true;
2046 bool isMatrix = false;
2047 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002048 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002049
2050 assert(node->getOp());
2051
John Kessenichf6640762016-08-01 19:44:00 -06002052 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002053
2054 switch (node->getOp()) {
2055 case glslang::EOpSequence:
2056 {
2057 if (preVisit)
2058 ++sequenceDepth;
2059 else
2060 --sequenceDepth;
2061
2062 if (sequenceDepth == 1) {
2063 // If this is the parent node of all the functions, we want to see them
2064 // early, so all call points have actual SPIR-V functions to reference.
2065 // In all cases, still let the traverser visit the children for us.
2066 makeFunctions(node->getAsAggregate()->getSequence());
2067
John Kessenich6fccb3c2016-09-19 16:01:41 -06002068 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002069 // anything else gets there, so visit out of order, doing them all now.
2070 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2071
John Kessenich6a60c2f2016-12-08 21:01:59 -07002072 // 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 -06002073 // so do them manually.
2074 visitFunctions(node->getAsAggregate()->getSequence());
2075
2076 return false;
2077 }
2078
2079 return true;
2080 }
2081 case glslang::EOpLinkerObjects:
2082 {
2083 if (visit == glslang::EvPreVisit)
2084 linkageOnly = true;
2085 else
2086 linkageOnly = false;
2087
2088 return true;
2089 }
2090 case glslang::EOpComma:
2091 {
2092 // processing from left to right naturally leaves the right-most
2093 // lying around in the access chain
2094 glslang::TIntermSequence& glslangOperands = node->getSequence();
2095 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2096 glslangOperands[i]->traverse(this);
2097
2098 return false;
2099 }
2100 case glslang::EOpFunction:
2101 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002102 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002103 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002104 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002105 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002106 } else {
2107 handleFunctionEntry(node);
2108 }
2109 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002110 if (inEntryPoint)
2111 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002112 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002113 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002114 }
2115
2116 return true;
2117 case glslang::EOpParameters:
2118 // Parameters will have been consumed by EOpFunction processing, but not
2119 // the body, so we still visited the function node's children, making this
2120 // child redundant.
2121 return false;
2122 case glslang::EOpFunctionCall:
2123 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002124 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002125 if (node->isUserDefined())
2126 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002127 // 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 -07002128 if (result) {
2129 builder.clearAccessChain();
2130 builder.setAccessChainRValue(result);
2131 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002132 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002133
2134 return false;
2135 }
2136 case glslang::EOpConstructMat2x2:
2137 case glslang::EOpConstructMat2x3:
2138 case glslang::EOpConstructMat2x4:
2139 case glslang::EOpConstructMat3x2:
2140 case glslang::EOpConstructMat3x3:
2141 case glslang::EOpConstructMat3x4:
2142 case glslang::EOpConstructMat4x2:
2143 case glslang::EOpConstructMat4x3:
2144 case glslang::EOpConstructMat4x4:
2145 case glslang::EOpConstructDMat2x2:
2146 case glslang::EOpConstructDMat2x3:
2147 case glslang::EOpConstructDMat2x4:
2148 case glslang::EOpConstructDMat3x2:
2149 case glslang::EOpConstructDMat3x3:
2150 case glslang::EOpConstructDMat3x4:
2151 case glslang::EOpConstructDMat4x2:
2152 case glslang::EOpConstructDMat4x3:
2153 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002154 case glslang::EOpConstructIMat2x2:
2155 case glslang::EOpConstructIMat2x3:
2156 case glslang::EOpConstructIMat2x4:
2157 case glslang::EOpConstructIMat3x2:
2158 case glslang::EOpConstructIMat3x3:
2159 case glslang::EOpConstructIMat3x4:
2160 case glslang::EOpConstructIMat4x2:
2161 case glslang::EOpConstructIMat4x3:
2162 case glslang::EOpConstructIMat4x4:
2163 case glslang::EOpConstructUMat2x2:
2164 case glslang::EOpConstructUMat2x3:
2165 case glslang::EOpConstructUMat2x4:
2166 case glslang::EOpConstructUMat3x2:
2167 case glslang::EOpConstructUMat3x3:
2168 case glslang::EOpConstructUMat3x4:
2169 case glslang::EOpConstructUMat4x2:
2170 case glslang::EOpConstructUMat4x3:
2171 case glslang::EOpConstructUMat4x4:
2172 case glslang::EOpConstructBMat2x2:
2173 case glslang::EOpConstructBMat2x3:
2174 case glslang::EOpConstructBMat2x4:
2175 case glslang::EOpConstructBMat3x2:
2176 case glslang::EOpConstructBMat3x3:
2177 case glslang::EOpConstructBMat3x4:
2178 case glslang::EOpConstructBMat4x2:
2179 case glslang::EOpConstructBMat4x3:
2180 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002181 case glslang::EOpConstructF16Mat2x2:
2182 case glslang::EOpConstructF16Mat2x3:
2183 case glslang::EOpConstructF16Mat2x4:
2184 case glslang::EOpConstructF16Mat3x2:
2185 case glslang::EOpConstructF16Mat3x3:
2186 case glslang::EOpConstructF16Mat3x4:
2187 case glslang::EOpConstructF16Mat4x2:
2188 case glslang::EOpConstructF16Mat4x3:
2189 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002190 isMatrix = true;
2191 // fall through
2192 case glslang::EOpConstructFloat:
2193 case glslang::EOpConstructVec2:
2194 case glslang::EOpConstructVec3:
2195 case glslang::EOpConstructVec4:
2196 case glslang::EOpConstructDouble:
2197 case glslang::EOpConstructDVec2:
2198 case glslang::EOpConstructDVec3:
2199 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002200 case glslang::EOpConstructFloat16:
2201 case glslang::EOpConstructF16Vec2:
2202 case glslang::EOpConstructF16Vec3:
2203 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002204 case glslang::EOpConstructBool:
2205 case glslang::EOpConstructBVec2:
2206 case glslang::EOpConstructBVec3:
2207 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002208 case glslang::EOpConstructInt8:
2209 case glslang::EOpConstructI8Vec2:
2210 case glslang::EOpConstructI8Vec3:
2211 case glslang::EOpConstructI8Vec4:
2212 case glslang::EOpConstructUint8:
2213 case glslang::EOpConstructU8Vec2:
2214 case glslang::EOpConstructU8Vec3:
2215 case glslang::EOpConstructU8Vec4:
2216 case glslang::EOpConstructInt16:
2217 case glslang::EOpConstructI16Vec2:
2218 case glslang::EOpConstructI16Vec3:
2219 case glslang::EOpConstructI16Vec4:
2220 case glslang::EOpConstructUint16:
2221 case glslang::EOpConstructU16Vec2:
2222 case glslang::EOpConstructU16Vec3:
2223 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002224 case glslang::EOpConstructInt:
2225 case glslang::EOpConstructIVec2:
2226 case glslang::EOpConstructIVec3:
2227 case glslang::EOpConstructIVec4:
2228 case glslang::EOpConstructUint:
2229 case glslang::EOpConstructUVec2:
2230 case glslang::EOpConstructUVec3:
2231 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002232 case glslang::EOpConstructInt64:
2233 case glslang::EOpConstructI64Vec2:
2234 case glslang::EOpConstructI64Vec3:
2235 case glslang::EOpConstructI64Vec4:
2236 case glslang::EOpConstructUint64:
2237 case glslang::EOpConstructU64Vec2:
2238 case glslang::EOpConstructU64Vec3:
2239 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002240 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002241 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002242 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002243 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002244 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002245 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002246 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002247 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002248 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002249 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002250 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002251 else if (node->getOp() == glslang::EOpConstructStruct ||
2252 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2253 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002254 std::vector<spv::Id> constituents;
2255 for (int c = 0; c < (int)arguments.size(); ++c)
2256 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002257 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002258 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002259 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002260 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002261 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002262
2263 builder.clearAccessChain();
2264 builder.setAccessChainRValue(constructed);
2265
2266 return false;
2267 }
2268
2269 // These six are component-wise compares with component-wise results.
2270 // Forward on to createBinaryOperation(), requesting a vector result.
2271 case glslang::EOpLessThan:
2272 case glslang::EOpGreaterThan:
2273 case glslang::EOpLessThanEqual:
2274 case glslang::EOpGreaterThanEqual:
2275 case glslang::EOpVectorEqual:
2276 case glslang::EOpVectorNotEqual:
2277 {
2278 // Map the operation to a binary
2279 binOp = node->getOp();
2280 reduceComparison = false;
2281 switch (node->getOp()) {
2282 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2283 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2284 default: binOp = node->getOp(); break;
2285 }
2286
2287 break;
2288 }
2289 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002290 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002291 binOp = glslang::EOpMul;
2292 break;
2293 case glslang::EOpOuterProduct:
2294 // two vectors multiplied to make a matrix
2295 binOp = glslang::EOpOuterProduct;
2296 break;
2297 case glslang::EOpDot:
2298 {
qining25262b32016-05-06 17:25:16 -04002299 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002300 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002301 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002302 binOp = glslang::EOpMul;
2303 break;
2304 }
2305 case glslang::EOpMod:
2306 // when an aggregate, this is the floating-point mod built-in function,
2307 // which can be emitted by the one in createBinaryOperation()
2308 binOp = glslang::EOpMod;
2309 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002310 case glslang::EOpEmitVertex:
2311 case glslang::EOpEndPrimitive:
2312 case glslang::EOpBarrier:
2313 case glslang::EOpMemoryBarrier:
2314 case glslang::EOpMemoryBarrierAtomicCounter:
2315 case glslang::EOpMemoryBarrierBuffer:
2316 case glslang::EOpMemoryBarrierImage:
2317 case glslang::EOpMemoryBarrierShared:
2318 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002319 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002320 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002321 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002322 case glslang::EOpWorkgroupMemoryBarrier:
2323 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002324 case glslang::EOpSubgroupBarrier:
2325 case glslang::EOpSubgroupMemoryBarrier:
2326 case glslang::EOpSubgroupMemoryBarrierBuffer:
2327 case glslang::EOpSubgroupMemoryBarrierImage:
2328 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002329 noReturnValue = true;
2330 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2331 break;
2332
Jeff Bolz36831c92018-09-05 10:11:41 -05002333 case glslang::EOpAtomicStore:
2334 noReturnValue = true;
2335 // fallthrough
2336 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002337 case glslang::EOpAtomicAdd:
2338 case glslang::EOpAtomicMin:
2339 case glslang::EOpAtomicMax:
2340 case glslang::EOpAtomicAnd:
2341 case glslang::EOpAtomicOr:
2342 case glslang::EOpAtomicXor:
2343 case glslang::EOpAtomicExchange:
2344 case glslang::EOpAtomicCompSwap:
2345 atomic = true;
2346 break;
2347
John Kessenich0d0c6d32017-07-23 16:08:26 -06002348 case glslang::EOpAtomicCounterAdd:
2349 case glslang::EOpAtomicCounterSubtract:
2350 case glslang::EOpAtomicCounterMin:
2351 case glslang::EOpAtomicCounterMax:
2352 case glslang::EOpAtomicCounterAnd:
2353 case glslang::EOpAtomicCounterOr:
2354 case glslang::EOpAtomicCounterXor:
2355 case glslang::EOpAtomicCounterExchange:
2356 case glslang::EOpAtomicCounterCompSwap:
2357 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2358 builder.addCapability(spv::CapabilityAtomicStorageOps);
2359 atomic = true;
2360 break;
2361
Chao Chen3c366992018-09-19 11:41:59 -07002362#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002363 case glslang::EOpIgnoreIntersectionNV:
2364 case glslang::EOpTerminateRayNV:
2365 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002366 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002367 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2368 noReturnValue = true;
2369 break;
2370#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002371 case glslang::EOpCooperativeMatrixLoad:
2372 case glslang::EOpCooperativeMatrixStore:
2373 noReturnValue = true;
2374 break;
Chao Chen3c366992018-09-19 11:41:59 -07002375
John Kessenich140f3df2015-06-26 16:58:36 -06002376 default:
2377 break;
2378 }
2379
2380 //
2381 // See if it maps to a regular operation.
2382 //
John Kessenich140f3df2015-06-26 16:58:36 -06002383 if (binOp != glslang::EOpNull) {
2384 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2385 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2386 assert(left && right);
2387
2388 builder.clearAccessChain();
2389 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002390 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002391
2392 builder.clearAccessChain();
2393 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002394 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002395
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002396 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002397 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002398 TranslateNoContractionDecoration(node->getType().getQualifier()),
2399 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002400 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002401 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002402 left->getType().getBasicType(), reduceComparison);
2403
2404 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002405 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002406 builder.clearAccessChain();
2407 builder.setAccessChainRValue(result);
2408
2409 return false;
2410 }
2411
John Kessenich426394d2015-07-23 10:22:48 -06002412 //
2413 // Create the list of operands.
2414 //
John Kessenich140f3df2015-06-26 16:58:36 -06002415 glslang::TIntermSequence& glslangOperands = node->getSequence();
2416 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002417 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002418 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002419 // special case l-value operands; there are just a few
2420 bool lvalue = false;
2421 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002422 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002423 case glslang::EOpModf:
2424 if (arg == 1)
2425 lvalue = true;
2426 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002427 case glslang::EOpInterpolateAtSample:
2428 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002429#ifdef AMD_EXTENSIONS
2430 case glslang::EOpInterpolateAtVertex:
2431#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002432 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002433 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002434
2435 // Does it need a swizzle inversion? If so, evaluation is inverted;
2436 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002437 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002438 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2439 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2440 }
Rex Xu7a26c172015-12-08 17:12:09 +08002441 break;
Rex Xud4782c12015-09-06 16:30:11 +08002442 case glslang::EOpAtomicAdd:
2443 case glslang::EOpAtomicMin:
2444 case glslang::EOpAtomicMax:
2445 case glslang::EOpAtomicAnd:
2446 case glslang::EOpAtomicOr:
2447 case glslang::EOpAtomicXor:
2448 case glslang::EOpAtomicExchange:
2449 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002450 case glslang::EOpAtomicLoad:
2451 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002452 case glslang::EOpAtomicCounterAdd:
2453 case glslang::EOpAtomicCounterSubtract:
2454 case glslang::EOpAtomicCounterMin:
2455 case glslang::EOpAtomicCounterMax:
2456 case glslang::EOpAtomicCounterAnd:
2457 case glslang::EOpAtomicCounterOr:
2458 case glslang::EOpAtomicCounterXor:
2459 case glslang::EOpAtomicCounterExchange:
2460 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002461 if (arg == 0)
2462 lvalue = true;
2463 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002464 case glslang::EOpAddCarry:
2465 case glslang::EOpSubBorrow:
2466 if (arg == 2)
2467 lvalue = true;
2468 break;
2469 case glslang::EOpUMulExtended:
2470 case glslang::EOpIMulExtended:
2471 if (arg >= 2)
2472 lvalue = true;
2473 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002474 case glslang::EOpCooperativeMatrixLoad:
2475 if (arg == 0 || arg == 1)
2476 lvalue = true;
2477 break;
2478 case glslang::EOpCooperativeMatrixStore:
2479 if (arg == 1)
2480 lvalue = true;
2481 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002482 default:
2483 break;
2484 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002485 builder.clearAccessChain();
2486 if (invertedType != spv::NoType && arg == 0)
2487 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2488 else
2489 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002490
2491 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2492 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2493
2494 if (arg == 1) {
2495 // fold "element" parameter into the access chain
2496 spv::Builder::AccessChain save = builder.getAccessChain();
2497 builder.clearAccessChain();
2498 glslangOperands[2]->traverse(this);
2499
2500 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2501
2502 builder.setAccessChain(save);
2503
2504 // Point to the first element of the array.
2505 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2506 getBufferReferenceAlignment(glslangOperands[arg]->getAsTyped()->getType()));
2507
2508 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2509 unsigned int alignment = builder.getAccessChain().alignment;
2510
2511 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2512 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2513 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2514 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2515 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2516 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2517 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2518 }
2519
2520 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2521
2522 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2523 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2524 }
2525
2526 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2527 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2528 }
2529 } else if (arg == 2) {
2530 continue;
2531 }
2532 }
2533
John Kessenich140f3df2015-06-26 16:58:36 -06002534 if (lvalue)
2535 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002536 else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002537 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002538 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002539 }
John Kessenich140f3df2015-06-26 16:58:36 -06002540 }
John Kessenich426394d2015-07-23 10:22:48 -06002541
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002542 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002543 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2544 std::vector<spv::IdImmediate> idImmOps;
2545
2546 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2547 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2548 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2549 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2550 // get the pointee type
2551 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2552 assert(builder.isCooperativeMatrixType(typeId));
2553 // do the op
2554 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2555 // store the result to the pointer (out param 'm')
2556 builder.createStore(result, operands[0]);
2557 result = 0;
2558 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2559 std::vector<spv::IdImmediate> idImmOps;
2560
2561 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2562 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2563 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2564 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2565 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2566
2567 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2568 result = 0;
2569 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002570 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002571 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002572 } else {
2573 // Pass through to generic operations.
2574 switch (glslangOperands.size()) {
2575 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002576 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002577 break;
2578 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002579 {
2580 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002581 TranslateNoContractionDecoration(node->getType().getQualifier()),
2582 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002583 result = createUnaryOperation(
2584 node->getOp(), decorations,
2585 resultType(), operands.front(),
2586 glslangOperands[0]->getAsTyped()->getBasicType());
2587 }
John Kessenich426394d2015-07-23 10:22:48 -06002588 break;
2589 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002590 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002591 break;
2592 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002593 if (invertedType)
2594 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002595 }
2596
2597 if (noReturnValue)
2598 return false;
2599
2600 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002601 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002602 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002603 } else {
2604 builder.clearAccessChain();
2605 builder.setAccessChainRValue(result);
2606 return false;
2607 }
2608}
2609
John Kessenich433e9ff2017-01-26 20:31:11 -07002610// This path handles both if-then-else and ?:
2611// The if-then-else has a node type of void, while
2612// ?: has either a void or a non-void node type
2613//
2614// Leaving the result, when not void:
2615// GLSL only has r-values as the result of a :?, but
2616// if we have an l-value, that can be more efficient if it will
2617// become the base of a complex r-value expression, because the
2618// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002619bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2620{
John Kessenich4bee5312018-02-20 21:29:05 -07002621 // See if it simple and safe, or required, to execute both sides.
2622 // Crucially, side effects must be either semantically required or avoided,
2623 // and there are performance trade-offs.
2624 // Return true if required or a good idea (and safe) to execute both sides,
2625 // false otherwise.
2626 const auto bothSidesPolicy = [&]() -> bool {
2627 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002628 if (node->getTrueBlock() == nullptr ||
2629 node->getFalseBlock() == nullptr)
2630 return false;
2631
John Kessenich4bee5312018-02-20 21:29:05 -07002632 // required? (unless we write additional code to look for side effects
2633 // and make performance trade-offs if none are present)
2634 if (!node->getShortCircuit())
2635 return true;
2636
2637 // if not required to execute both, decide based on performance/practicality...
2638
2639 // see if OpSelect can handle it
2640 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2641 node->getBasicType() == glslang::EbtVoid)
2642 return false;
2643
John Kessenich433e9ff2017-01-26 20:31:11 -07002644 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2645 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2646
2647 // return true if a single operand to ? : is okay for OpSelect
2648 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002649 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002650 };
2651
2652 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2653 operandOkay(node->getFalseBlock()->getAsTyped());
2654 };
2655
John Kessenich4bee5312018-02-20 21:29:05 -07002656 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2657 // emit the condition before doing anything with selection
2658 node->getCondition()->traverse(this);
2659 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2660
2661 // Find a way of executing both sides and selecting the right result.
2662 const auto executeBothSides = [&]() -> void {
2663 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002664 node->getTrueBlock()->traverse(this);
2665 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2666 node->getFalseBlock()->traverse(this);
2667 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2668
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002669 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002670
John Kessenich4bee5312018-02-20 21:29:05 -07002671 // done if void
2672 if (node->getBasicType() == glslang::EbtVoid)
2673 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002674
John Kessenich4bee5312018-02-20 21:29:05 -07002675 // emit code to select between trueValue and falseValue
2676
2677 // see if OpSelect can handle it
2678 if (node->getType().isScalar() || node->getType().isVector()) {
2679 // Emit OpSelect for this selection.
2680
2681 // smear condition to vector, if necessary (AST is always scalar)
2682 if (builder.isVector(trueValue))
2683 condition = builder.smearScalar(spv::NoPrecision, condition,
2684 builder.makeVectorType(builder.makeBoolType(),
2685 builder.getNumComponents(trueValue)));
2686
2687 // OpSelect
2688 result = builder.createTriOp(spv::OpSelect,
2689 convertGlslangToSpvType(node->getType()), condition,
2690 trueValue, falseValue);
2691
2692 builder.clearAccessChain();
2693 builder.setAccessChainRValue(result);
2694 } else {
2695 // We need control flow to select the result.
2696 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2697 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2698
2699 // Selection control:
2700 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2701
2702 // make an "if" based on the value created by the condition
2703 spv::Builder::If ifBuilder(condition, control, builder);
2704
2705 // emit the "then" statement
2706 builder.createStore(trueValue, result);
2707 ifBuilder.makeBeginElse();
2708 // emit the "else" statement
2709 builder.createStore(falseValue, result);
2710
2711 // finish off the control flow
2712 ifBuilder.makeEndIf();
2713
2714 builder.clearAccessChain();
2715 builder.setAccessChainLValue(result);
2716 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002717 };
2718
John Kessenich4bee5312018-02-20 21:29:05 -07002719 // Execute the one side needed, as per the condition
2720 const auto executeOneSide = [&]() {
2721 // Always emit control flow.
2722 if (node->getBasicType() != glslang::EbtVoid)
2723 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002724
John Kessenich4bee5312018-02-20 21:29:05 -07002725 // Selection control:
2726 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2727
2728 // make an "if" based on the value created by the condition
2729 spv::Builder::If ifBuilder(condition, control, builder);
2730
2731 // emit the "then" statement
2732 if (node->getTrueBlock() != nullptr) {
2733 node->getTrueBlock()->traverse(this);
2734 if (result != spv::NoResult)
2735 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2736 }
2737
2738 if (node->getFalseBlock() != nullptr) {
2739 ifBuilder.makeBeginElse();
2740 // emit the "else" statement
2741 node->getFalseBlock()->traverse(this);
2742 if (result != spv::NoResult)
2743 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2744 }
2745
2746 // finish off the control flow
2747 ifBuilder.makeEndIf();
2748
2749 if (result != spv::NoResult) {
2750 builder.clearAccessChain();
2751 builder.setAccessChainLValue(result);
2752 }
2753 };
2754
2755 // Try for OpSelect (or a requirement to execute both sides)
2756 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002757 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2758 if (node->getType().getQualifier().isSpecConstant())
2759 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002760 executeBothSides();
2761 } else
2762 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002763
2764 return false;
2765}
2766
2767bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2768{
2769 // emit and get the condition before doing anything with switch
2770 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002771 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002772
Rex Xu57e65922017-07-04 23:23:40 +08002773 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002774 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002775
John Kessenich140f3df2015-06-26 16:58:36 -06002776 // browse the children to sort out code segments
2777 int defaultSegment = -1;
2778 std::vector<TIntermNode*> codeSegments;
2779 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2780 std::vector<int> caseValues;
2781 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2782 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2783 TIntermNode* child = *c;
2784 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002785 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002786 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002787 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002788 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2789 } else
2790 codeSegments.push_back(child);
2791 }
2792
qining25262b32016-05-06 17:25:16 -04002793 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002794 // statements between the last case and the end of the switch statement
2795 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2796 (int)codeSegments.size() == defaultSegment)
2797 codeSegments.push_back(nullptr);
2798
2799 // make the switch statement
2800 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002801 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002802
2803 // emit all the code in the segments
2804 breakForLoop.push(false);
2805 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2806 builder.nextSwitchSegment(segmentBlocks, s);
2807 if (codeSegments[s])
2808 codeSegments[s]->traverse(this);
2809 else
2810 builder.addSwitchBreak();
2811 }
2812 breakForLoop.pop();
2813
2814 builder.endSwitch(segmentBlocks);
2815
2816 return false;
2817}
2818
2819void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2820{
2821 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002822 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002823
2824 builder.clearAccessChain();
2825 builder.setAccessChainRValue(constant);
2826}
2827
2828bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2829{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002830 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002831 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002832
2833 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002834 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2835 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002836
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002837 // Spec requires back edges to target header blocks, and every header block
2838 // must dominate its merge block. Make a header block first to ensure these
2839 // conditions are met. By definition, it will contain OpLoopMerge, followed
2840 // by a block-ending branch. But we don't want to put any other body/test
2841 // instructions in it, since the body/test may have arbitrary instructions,
2842 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002843 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002844 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002845 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002846 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002847 spv::Block& test = builder.makeNewBlock();
2848 builder.createBranch(&test);
2849
2850 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002851 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002852 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002853 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2854
2855 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002856 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002857 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002858 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002859 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002860 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002861
2862 builder.setBuildPoint(&blocks.continue_target);
2863 if (node->getTerminal())
2864 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002865 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002866 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002867 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002868 builder.createBranch(&blocks.body);
2869
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002870 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002871 builder.setBuildPoint(&blocks.body);
2872 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002873 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002874 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002875 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002876
2877 builder.setBuildPoint(&blocks.continue_target);
2878 if (node->getTerminal())
2879 node->getTerminal()->traverse(this);
2880 if (node->getTest()) {
2881 node->getTest()->traverse(this);
2882 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002883 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002884 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002885 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002886 // TODO: unless there was a break/return/discard instruction
2887 // somewhere in the body, this is an infinite loop, so we should
2888 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002889 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002890 }
John Kessenich140f3df2015-06-26 16:58:36 -06002891 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002892 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002893 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002894 return false;
2895}
2896
2897bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2898{
2899 if (node->getExpression())
2900 node->getExpression()->traverse(this);
2901
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002902 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002903
John Kessenich140f3df2015-06-26 16:58:36 -06002904 switch (node->getFlowOp()) {
2905 case glslang::EOpKill:
2906 builder.makeDiscard();
2907 break;
2908 case glslang::EOpBreak:
2909 if (breakForLoop.top())
2910 builder.createLoopExit();
2911 else
2912 builder.addSwitchBreak();
2913 break;
2914 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002915 builder.createLoopContinue();
2916 break;
2917 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002918 if (node->getExpression()) {
2919 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2920 spv::Id returnId = accessChainLoad(glslangReturnType);
2921 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2922 builder.clearAccessChain();
2923 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2924 builder.setAccessChainLValue(copyId);
2925 multiTypeStore(glslangReturnType, returnId);
2926 returnId = builder.createLoad(copyId);
2927 }
2928 builder.makeReturn(false, returnId);
2929 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002930 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002931
2932 builder.clearAccessChain();
2933 break;
2934
2935 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002936 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002937 break;
2938 }
2939
2940 return false;
2941}
2942
2943spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2944{
qining25262b32016-05-06 17:25:16 -04002945 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002946 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002947 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002948 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05002949 spv::Id result = createSpvConstant(*node);
2950 if (result != spv::NoResult)
2951 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06002952 }
2953
2954 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002955 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002956 spv::Id spvType = convertGlslangToSpvType(node->getType());
2957
Rex Xucabbb782017-03-24 13:41:14 +08002958 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2959 node->getType().containsBasicType(glslang::EbtInt16) ||
2960 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002961 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002962 switch (storageClass) {
2963 case spv::StorageClassInput:
2964 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002965 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002966 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002967 break;
2968 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002969 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002970 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002971 break;
2972 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002973 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002974 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2975 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002976 else
2977 builder.addCapability(spv::CapabilityStorageUniform16);
2978 break;
2979 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002980 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06002981 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2982 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2983 break;
2984 default:
2985 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002986 }
2987 }
Rex Xuf89ad982017-04-07 23:22:33 +08002988
John Kessenich312dcfb2018-07-03 13:19:51 -06002989 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2990 node->getType().containsBasicType(glslang::EbtUint8);
2991 if (contains8BitType) {
2992 if (storageClass == spv::StorageClassPushConstant) {
2993 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2994 builder.addCapability(spv::CapabilityStoragePushConstant8);
2995 } else if (storageClass == spv::StorageClassUniform) {
2996 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2997 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01002998 } else if (storageClass == spv::StorageClassStorageBuffer) {
2999 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3000 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
John Kessenich312dcfb2018-07-03 13:19:51 -06003001 }
3002 }
3003
John Kessenich140f3df2015-06-26 16:58:36 -06003004 const char* name = node->getName().c_str();
3005 if (glslang::IsAnonymous(name))
3006 name = "";
3007
3008 return builder.createVariable(storageClass, spvType, name);
3009}
3010
3011// Return type Id of the sampled type.
3012spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3013{
3014 switch (sampler.type) {
3015 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003016#ifdef AMD_EXTENSIONS
3017 case glslang::EbtFloat16:
3018 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3019 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3020 return builder.makeFloatType(16);
3021#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003022 case glslang::EbtInt: return builder.makeIntType(32);
3023 case glslang::EbtUint: return builder.makeUintType(32);
3024 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003025 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003026 return builder.makeFloatType(32);
3027 }
3028}
3029
John Kessenich8c8505c2016-07-26 12:50:38 -06003030// If node is a swizzle operation, return the type that should be used if
3031// the swizzle base is first consumed by another operation, before the swizzle
3032// is applied.
3033spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3034{
John Kessenichecba76f2017-01-06 00:34:48 -07003035 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003036 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3037 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3038 else
3039 return spv::NoType;
3040}
3041
3042// When inverting a swizzle with a parent op, this function
3043// will apply the swizzle operation to a completed parent operation.
3044spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3045{
3046 std::vector<unsigned> swizzle;
3047 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3048 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3049}
3050
John Kessenich8c8505c2016-07-26 12:50:38 -06003051// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3052void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3053{
3054 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3055 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3056 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3057}
3058
John Kessenich3ac051e2015-12-20 11:29:16 -07003059// Convert from a glslang type to an SPV type, by calling into a
3060// recursive version of this function. This establishes the inherited
3061// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003062spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003063{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003064 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003065}
3066
3067// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003068// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003069// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003070spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003071 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3072 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003073{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003074 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003075
3076 switch (type.getBasicType()) {
3077 case glslang::EbtVoid:
3078 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003079 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003080 break;
3081 case glslang::EbtFloat:
3082 spvType = builder.makeFloatType(32);
3083 break;
3084 case glslang::EbtDouble:
3085 spvType = builder.makeFloatType(64);
3086 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003087 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003088 spvType = builder.makeFloatType(16);
3089 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003090 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003091 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3092 // a 32-bit int where non-0 means true.
3093 if (explicitLayout != glslang::ElpNone)
3094 spvType = builder.makeUintType(32);
3095 else
3096 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003097 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003098 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003099 spvType = builder.makeIntType(8);
3100 break;
3101 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003102 spvType = builder.makeUintType(8);
3103 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003104 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003105 spvType = builder.makeIntType(16);
3106 break;
3107 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003108 spvType = builder.makeUintType(16);
3109 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003110 case glslang::EbtInt:
3111 spvType = builder.makeIntType(32);
3112 break;
3113 case glslang::EbtUint:
3114 spvType = builder.makeUintType(32);
3115 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003116 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003117 spvType = builder.makeIntType(64);
3118 break;
3119 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003120 spvType = builder.makeUintType(64);
3121 break;
John Kessenich426394d2015-07-23 10:22:48 -06003122 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003123 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003124 spvType = builder.makeUintType(32);
3125 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003126#ifdef NV_EXTENSIONS
3127 case glslang::EbtAccStructNV:
3128 spvType = builder.makeAccelerationStructureNVType();
3129 break;
3130#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003131 case glslang::EbtSampler:
3132 {
3133 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003134 if (sampler.sampler) {
3135 // pure sampler
3136 spvType = builder.makeSamplerType();
3137 } else {
3138 // an image is present, make its type
3139 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3140 sampler.image ? 2 : 1, TranslateImageFormat(type));
3141 if (sampler.combined) {
3142 // already has both image and sampler, make the combined type
3143 spvType = builder.makeSampledImageType(spvType);
3144 }
John Kessenich55e7d112015-11-15 21:33:39 -07003145 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003146 }
John Kessenich140f3df2015-06-26 16:58:36 -06003147 break;
3148 case glslang::EbtStruct:
3149 case glslang::EbtBlock:
3150 {
3151 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003152 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003153
3154 // Try to share structs for different layouts, but not yet for other
3155 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003156 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003157 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003158 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003159 break;
3160
3161 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003162 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003163 memberRemapper[glslangMembers].resize(glslangMembers->size());
3164 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003165 }
3166 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003167 case glslang::EbtReference:
3168 {
3169 // Make the forward pointer, then recurse to convert the structure type, then
3170 // patch up the forward pointer with a real pointer type.
3171 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3172 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3173 forwardPointers[type.getReferentType()] = forwardId;
3174 }
3175 spvType = forwardPointers[type.getReferentType()];
3176 if (!forwardReferenceOnly) {
3177 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3178 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3179 forwardPointers[type.getReferentType()],
3180 referentType);
3181 }
3182 }
3183 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003184 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003185 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003186 break;
3187 }
3188
3189 if (type.isMatrix())
3190 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3191 else {
3192 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3193 if (type.getVectorSize() > 1)
3194 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3195 }
3196
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003197 if (type.isCoopMat()) {
3198 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3199 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3200 if (type.getBasicType() == glslang::EbtFloat16)
3201 builder.addCapability(spv::CapabilityFloat16);
3202
3203 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3204 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3205 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3206
3207 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3208 }
3209
John Kessenich140f3df2015-06-26 16:58:36 -06003210 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003211 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3212
John Kessenichc9a80832015-09-12 12:17:44 -06003213 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003214 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003215 // We need to decorate array strides for types needing explicit layout, except blocks.
3216 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003217 // Use a dummy glslang type for querying internal strides of
3218 // arrays of arrays, but using just a one-dimensional array.
3219 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003220 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3221 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003222
3223 // Will compute the higher-order strides here, rather than making a whole
3224 // pile of types and doing repetitive recursion on their contents.
3225 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3226 }
John Kessenichf8842e52016-01-04 19:22:56 -07003227
3228 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003229 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003230 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003231 if (stride > 0)
3232 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003233 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003234 }
3235 } else {
3236 // single-dimensional array, and don't yet have stride
3237
John Kessenichf8842e52016-01-04 19:22:56 -07003238 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003239 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3240 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003241 }
John Kessenich31ed4832015-09-09 17:51:38 -06003242
John Kessenichead86222018-03-28 18:01:20 -06003243 // Do the outer dimension, which might not be known for a runtime-sized array.
3244 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3245 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003246 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003247 else {
3248 if (!lastBufferBlockMember) {
3249 builder.addExtension("SPV_EXT_descriptor_indexing");
3250 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3251 }
John Kessenichead86222018-03-28 18:01:20 -06003252 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003253 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003254 if (stride > 0)
3255 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003256 }
3257
3258 return spvType;
3259}
3260
John Kessenich0e737842017-03-24 18:38:16 -06003261// TODO: this functionality should exist at a higher level, in creating the AST
3262//
3263// Identify interface members that don't have their required extension turned on.
3264//
3265bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3266{
Chao Chen3c366992018-09-19 11:41:59 -07003267#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003268 auto& extensions = glslangIntermediate->getRequestedExtensions();
3269
Rex Xubcf291a2017-03-29 23:01:36 +08003270 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3271 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3272 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003273 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3274 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3275 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003276
3277 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3278 if (member.getFieldName() == "gl_ViewportMask" &&
3279 extensions.find("GL_NV_viewport_array2") == extensions.end())
3280 return true;
3281 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3282 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3283 return true;
3284 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3285 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3286 return true;
3287 }
3288#endif
John Kessenich0e737842017-03-24 18:38:16 -06003289
3290 return false;
3291};
3292
John Kessenich6090df02016-06-30 21:18:02 -06003293// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3294// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3295// Mutually recursive with convertGlslangToSpvType().
3296spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3297 const glslang::TTypeList* glslangMembers,
3298 glslang::TLayoutPacking explicitLayout,
3299 const glslang::TQualifier& qualifier)
3300{
3301 // Create a vector of struct types for SPIR-V to consume
3302 std::vector<spv::Id> spvMembers;
3303 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 -06003304 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003305 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3306 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3307 if (glslangMember.hiddenMember()) {
3308 ++memberDelta;
3309 if (type.getBasicType() == glslang::EbtBlock)
3310 memberRemapper[glslangMembers][i] = -1;
3311 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003312 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003313 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003314 if (filterMember(glslangMember))
3315 continue;
3316 }
John Kessenich6090df02016-06-30 21:18:02 -06003317 // modify just this child's view of the qualifier
3318 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3319 InheritQualifiers(memberQualifier, qualifier);
3320
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003321 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003322 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003323 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003324
3325 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003326 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3327 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003328
3329 // Make forward pointers for any pointer members, and create a list of members to
3330 // convert to spirv types after creating the struct.
3331 if (glslangMember.getBasicType() == glslang::EbtReference) {
3332 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3333 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3334 }
3335 spvMembers.push_back(
3336 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3337 } else {
3338 spvMembers.push_back(
3339 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3340 }
John Kessenich6090df02016-06-30 21:18:02 -06003341 }
3342 }
3343
3344 // Make the SPIR-V type
3345 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003346 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003347 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3348
3349 // Decorate it
3350 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3351
John Kessenichd72f4882019-01-16 14:55:37 +07003352 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003353 auto it = deferredForwardPointers[i];
3354 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3355 }
3356
John Kessenich6090df02016-06-30 21:18:02 -06003357 return spvType;
3358}
3359
3360void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3361 const glslang::TTypeList* glslangMembers,
3362 glslang::TLayoutPacking explicitLayout,
3363 const glslang::TQualifier& qualifier,
3364 spv::Id spvType)
3365{
3366 // Name and decorate the non-hidden members
3367 int offset = -1;
3368 int locationOffset = 0; // for use within the members of this struct
3369 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3370 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3371 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003372 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003373 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003374 if (filterMember(glslangMember))
3375 continue;
3376 }
John Kessenich6090df02016-06-30 21:18:02 -06003377
3378 // modify just this child's view of the qualifier
3379 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3380 InheritQualifiers(memberQualifier, qualifier);
3381
3382 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003383 if (member < 0)
3384 continue;
3385
3386 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3387 builder.addMemberDecoration(spvType, member,
3388 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3389 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3390 // Add interpolation and auxiliary storage decorations only to
3391 // top-level members of Input and Output storage classes
3392 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3393 type.getQualifier().storage == glslang::EvqVaryingOut) {
3394 if (type.getBasicType() == glslang::EbtBlock ||
3395 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3396 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3397 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003398#ifdef NV_EXTENSIONS
3399 addMeshNVDecoration(spvType, member, memberQualifier);
3400#endif
John Kessenich6090df02016-06-30 21:18:02 -06003401 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003402 }
3403 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003404
John Kessenich5d610ee2018-03-07 18:05:55 -07003405 if (type.getBasicType() == glslang::EbtBlock &&
3406 qualifier.storage == glslang::EvqBuffer) {
3407 // Add memory decorations only to top-level members of shader storage block
3408 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003409 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003410 for (unsigned int i = 0; i < memory.size(); ++i)
3411 builder.addMemberDecoration(spvType, member, memory[i]);
3412 }
John Kessenich6090df02016-06-30 21:18:02 -06003413
John Kessenich5d610ee2018-03-07 18:05:55 -07003414 // Location assignment was already completed correctly by the front end,
3415 // just track whether a member needs to be decorated.
3416 // Ignore member locations if the container is an array, as that's
3417 // ill-specified and decisions have been made to not allow this.
3418 if (! type.isArray() && memberQualifier.hasLocation())
3419 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003420
John Kessenich5d610ee2018-03-07 18:05:55 -07003421 if (qualifier.hasLocation()) // track for upcoming inheritance
3422 locationOffset += glslangIntermediate->computeTypeLocationSize(
3423 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003424
John Kessenich5d610ee2018-03-07 18:05:55 -07003425 // component, XFB, others
3426 if (glslangMember.getQualifier().hasComponent())
3427 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3428 glslangMember.getQualifier().layoutComponent);
3429 if (glslangMember.getQualifier().hasXfbOffset())
3430 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3431 glslangMember.getQualifier().layoutXfbOffset);
3432 else if (explicitLayout != glslang::ElpNone) {
3433 // figure out what to do with offset, which is accumulating
3434 int nextOffset;
3435 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3436 if (offset >= 0)
3437 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3438 offset = nextOffset;
3439 }
John Kessenich6090df02016-06-30 21:18:02 -06003440
John Kessenich5d610ee2018-03-07 18:05:55 -07003441 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3442 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3443 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003444
John Kessenich5d610ee2018-03-07 18:05:55 -07003445 // built-in variable decorations
3446 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3447 if (builtIn != spv::BuiltInMax)
3448 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003449
John Kessenich5611c6d2018-04-05 11:25:02 -06003450 // nonuniform
3451 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3452
John Kessenichead86222018-03-28 18:01:20 -06003453 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3454 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3455 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3456 memberQualifier.semanticName);
3457 }
3458
chaoc771d89f2017-01-13 01:10:53 -08003459#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003460 if (builtIn == spv::BuiltInLayer) {
3461 // SPV_NV_viewport_array2 extension
3462 if (glslangMember.getQualifier().layoutViewportRelative){
3463 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3464 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3465 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003466 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003467 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3468 builder.addMemberDecoration(spvType, member,
3469 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3470 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3471 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3472 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003473 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003474 }
3475 if (glslangMember.getQualifier().layoutPassthrough) {
3476 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3477 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3478 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3479 }
chaoc771d89f2017-01-13 01:10:53 -08003480#endif
John Kessenich6090df02016-06-30 21:18:02 -06003481 }
3482
3483 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003484 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3485 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003486}
3487
John Kessenich6c292d32016-02-15 20:58:50 -07003488// Turn the expression forming the array size into an id.
3489// This is not quite trivial, because of specialization constants.
3490// Sometimes, a raw constant is turned into an Id, and sometimes
3491// a specialization constant expression is.
3492spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3493{
3494 // First, see if this is sized with a node, meaning a specialization constant:
3495 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3496 if (specNode != nullptr) {
3497 builder.clearAccessChain();
3498 specNode->traverse(this);
3499 return accessChainLoad(specNode->getAsTyped()->getType());
3500 }
qining25262b32016-05-06 17:25:16 -04003501
John Kessenich6c292d32016-02-15 20:58:50 -07003502 // Otherwise, need a compile-time (front end) size, get it:
3503 int size = arraySizes.getDimSize(dim);
3504 assert(size > 0);
3505 return builder.makeUintConstant(size);
3506}
3507
John Kessenich103bef92016-02-08 21:38:15 -07003508// Wrap the builder's accessChainLoad to:
3509// - localize handling of RelaxedPrecision
3510// - use the SPIR-V inferred type instead of another conversion of the glslang type
3511// (avoids unnecessary work and possible type punning for structures)
3512// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003513spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3514{
John Kessenich103bef92016-02-08 21:38:15 -07003515 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003516
3517 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3518 coherentFlags |= TranslateCoherent(type);
3519
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003520 unsigned int alignment = builder.getAccessChain().alignment;
3521 alignment |= getBufferReferenceAlignment(type);
3522
John Kessenich5611c6d2018-04-05 11:25:02 -06003523 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003524 TranslateNonUniformDecoration(type.getQualifier()),
3525 nominalTypeId,
3526 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003527 TranslateMemoryScope(coherentFlags),
3528 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003529
3530 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003531 if (type.getBasicType() == glslang::EbtBool) {
3532 if (builder.isScalarType(nominalTypeId)) {
3533 // Conversion for bool
3534 spv::Id boolType = builder.makeBoolType();
3535 if (nominalTypeId != boolType)
3536 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3537 } else if (builder.isVectorType(nominalTypeId)) {
3538 // Conversion for bvec
3539 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3540 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3541 if (nominalTypeId != bvecType)
3542 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3543 }
3544 }
John Kessenich103bef92016-02-08 21:38:15 -07003545
3546 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003547}
3548
Rex Xu27253232016-02-23 17:51:09 +08003549// Wrap the builder's accessChainStore to:
3550// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003551//
3552// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003553void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3554{
3555 // Need to convert to abstract types when necessary
3556 if (type.getBasicType() == glslang::EbtBool) {
3557 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3558
3559 if (builder.isScalarType(nominalTypeId)) {
3560 // Conversion for bool
3561 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003562 if (nominalTypeId != boolType) {
3563 // keep these outside arguments, for determinant order-of-evaluation
3564 spv::Id one = builder.makeUintConstant(1);
3565 spv::Id zero = builder.makeUintConstant(0);
3566 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3567 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003568 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003569 } else if (builder.isVectorType(nominalTypeId)) {
3570 // Conversion for bvec
3571 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3572 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003573 if (nominalTypeId != bvecType) {
3574 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003575 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3576 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3577 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003578 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003579 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3580 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003581 }
3582 }
3583
Jeff Bolz36831c92018-09-05 10:11:41 -05003584 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3585 coherentFlags |= TranslateCoherent(type);
3586
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003587 unsigned int alignment = builder.getAccessChain().alignment;
3588 alignment |= getBufferReferenceAlignment(type);
3589
Jeff Bolz36831c92018-09-05 10:11:41 -05003590 builder.accessChainStore(rvalue,
3591 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003592 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003593}
3594
John Kessenich4bf71552016-09-02 11:20:21 -06003595// For storing when types match at the glslang level, but not might match at the
3596// SPIR-V level.
3597//
3598// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003599// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003600// as in a member-decorated way.
3601//
3602// NOTE: This function can handle any store request; if it's not special it
3603// simplifies to a simple OpStore.
3604//
3605// Implicitly uses the existing builder.accessChain as the storage target.
3606void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3607{
John Kessenichb3e24e42016-09-11 12:33:43 -06003608 // we only do the complex path here if it's an aggregate
3609 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003610 accessChainStore(type, rValue);
3611 return;
3612 }
3613
John Kessenichb3e24e42016-09-11 12:33:43 -06003614 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003615 spv::Id rType = builder.getTypeId(rValue);
3616 spv::Id lValue = builder.accessChainGetLValue();
3617 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3618 if (lType == rType) {
3619 accessChainStore(type, rValue);
3620 return;
3621 }
3622
John Kessenichb3e24e42016-09-11 12:33:43 -06003623 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003624 // where the two types were the same type in GLSL. This requires member
3625 // by member copy, recursively.
3626
John Kessenichb3e24e42016-09-11 12:33:43 -06003627 // If an array, copy element by element.
3628 if (type.isArray()) {
3629 glslang::TType glslangElementType(type, 0);
3630 spv::Id elementRType = builder.getContainedTypeId(rType);
3631 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3632 // get the source member
3633 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003634
John Kessenichb3e24e42016-09-11 12:33:43 -06003635 // set up the target storage
3636 builder.clearAccessChain();
3637 builder.setAccessChainLValue(lValue);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003638 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), getBufferReferenceAlignment(type));
John Kessenich4bf71552016-09-02 11:20:21 -06003639
John Kessenichb3e24e42016-09-11 12:33:43 -06003640 // store the member
3641 multiTypeStore(glslangElementType, elementRValue);
3642 }
3643 } else {
3644 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003645
John Kessenichb3e24e42016-09-11 12:33:43 -06003646 // loop over structure members
3647 const glslang::TTypeList& members = *type.getStruct();
3648 for (int m = 0; m < (int)members.size(); ++m) {
3649 const glslang::TType& glslangMemberType = *members[m].type;
3650
3651 // get the source member
3652 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3653 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3654
3655 // set up the target storage
3656 builder.clearAccessChain();
3657 builder.setAccessChainLValue(lValue);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003658 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), getBufferReferenceAlignment(type));
John Kessenichb3e24e42016-09-11 12:33:43 -06003659
3660 // store the member
3661 multiTypeStore(glslangMemberType, memberRValue);
3662 }
John Kessenich4bf71552016-09-02 11:20:21 -06003663 }
3664}
3665
John Kessenichf85e8062015-12-19 13:57:10 -07003666// Decide whether or not this type should be
3667// decorated with offsets and strides, and if so
3668// whether std140 or std430 rules should be applied.
3669glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003670{
John Kessenichf85e8062015-12-19 13:57:10 -07003671 // has to be a block
3672 if (type.getBasicType() != glslang::EbtBlock)
3673 return glslang::ElpNone;
3674
Chao Chen3c366992018-09-19 11:41:59 -07003675 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003676 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003677 type.getQualifier().storage != glslang::EvqBuffer &&
3678 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003679 return glslang::ElpNone;
3680
3681 // return the layout to use
3682 switch (type.getQualifier().layoutPacking) {
3683 case glslang::ElpStd140:
3684 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003685 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003686 return type.getQualifier().layoutPacking;
3687 default:
3688 return glslang::ElpNone;
3689 }
John Kessenich31ed4832015-09-09 17:51:38 -06003690}
3691
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003692// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003693int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003694{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003695 int size;
John Kessenich49987892015-12-29 17:11:44 -07003696 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003697 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003698
3699 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003700}
3701
John Kessenich49987892015-12-29 17:11:44 -07003702// 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 -07003703// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003704int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003705{
John Kessenich49987892015-12-29 17:11:44 -07003706 glslang::TType elementType;
3707 elementType.shallowCopy(matrixType);
3708 elementType.clearArraySizes();
3709
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003710 int size;
John Kessenich49987892015-12-29 17:11:44 -07003711 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003712 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003713
3714 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003715}
3716
John Kessenich5e4b1242015-08-06 22:53:06 -06003717// Given a member type of a struct, realign the current offset for it, and compute
3718// the next (not yet aligned) offset for the next member, which will get aligned
3719// on the next call.
3720// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3721// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3722// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003723void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003724 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003725{
3726 // this will get a positive value when deemed necessary
3727 nextOffset = -1;
3728
John Kessenich5e4b1242015-08-06 22:53:06 -06003729 // override anything in currentOffset with user-set offset
3730 if (memberType.getQualifier().hasOffset())
3731 currentOffset = memberType.getQualifier().layoutOffset;
3732
3733 // It could be that current linker usage in glslang updated all the layoutOffset,
3734 // in which case the following code does not matter. But, that's not quite right
3735 // once cross-compilation unit GLSL validation is done, as the original user
3736 // settings are needed in layoutOffset, and then the following will come into play.
3737
John Kessenichf85e8062015-12-19 13:57:10 -07003738 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003739 if (! memberType.getQualifier().hasOffset())
3740 currentOffset = -1;
3741
3742 return;
3743 }
3744
John Kessenichf85e8062015-12-19 13:57:10 -07003745 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003746 if (currentOffset < 0)
3747 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003748
John Kessenich5e4b1242015-08-06 22:53:06 -06003749 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3750 // but possibly not yet correctly aligned.
3751
3752 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003753 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003754 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003755
3756 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003757 // TODO: make this consistent in early phases of code:
3758 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3759 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3760 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003761 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003762 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003763 int dummySize;
3764 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3765 if (componentAlignment <= 4)
3766 memberAlignment = componentAlignment;
3767 }
3768
3769 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003770 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003771
3772 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003773 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003774 glslang::RoundToPow2(currentOffset, 16);
3775
John Kessenich5e4b1242015-08-06 22:53:06 -06003776 nextOffset = currentOffset + memberSize;
3777}
3778
David Netoa901ffe2016-06-08 14:11:40 +01003779void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003780{
David Netoa901ffe2016-06-08 14:11:40 +01003781 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3782 switch (glslangBuiltIn)
3783 {
3784 case glslang::EbvClipDistance:
3785 case glslang::EbvCullDistance:
3786 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003787#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003788 case glslang::EbvViewportMaskNV:
3789 case glslang::EbvSecondaryPositionNV:
3790 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003791 case glslang::EbvPositionPerViewNV:
3792 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003793 case glslang::EbvTaskCountNV:
3794 case glslang::EbvPrimitiveCountNV:
3795 case glslang::EbvPrimitiveIndicesNV:
3796 case glslang::EbvClipDistancePerViewNV:
3797 case glslang::EbvCullDistancePerViewNV:
3798 case glslang::EbvLayerPerViewNV:
3799 case glslang::EbvMeshViewCountNV:
3800 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003801#endif
David Netoa901ffe2016-06-08 14:11:40 +01003802 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3803 // Alternately, we could just call this for any glslang built-in, since the
3804 // capability already guards against duplicates.
3805 TranslateBuiltInDecoration(glslangBuiltIn, false);
3806 break;
3807 default:
3808 // Capabilities were already generated when the struct was declared.
3809 break;
3810 }
John Kessenichebb50532016-05-16 19:22:05 -06003811}
3812
John Kessenich6fccb3c2016-09-19 16:01:41 -06003813bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003814{
John Kessenicheee9d532016-09-19 18:09:30 -06003815 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003816}
3817
John Kessenichd41993d2017-09-10 15:21:05 -06003818// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003819// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3820// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003821bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003822{
John Kessenich6a14f782017-12-04 02:48:10 -07003823 assert(qualifier == glslang::EvqIn ||
3824 qualifier == glslang::EvqOut ||
3825 qualifier == glslang::EvqInOut ||
3826 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003827 return qualifier != glslang::EvqConstReadOnly;
3828}
3829
3830// Is parameter pass-by-original?
3831bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3832 bool implicitThisParam)
3833{
3834 if (implicitThisParam) // implicit this
3835 return true;
3836 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003837 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003838 return paramType.containsOpaque() || // sampler, etc.
3839 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3840}
3841
John Kessenich140f3df2015-06-26 16:58:36 -06003842// Make all the functions, skeletally, without actually visiting their bodies.
3843void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3844{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003845 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003846 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3847 if (paramPrecision != spv::NoPrecision)
3848 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003849 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003850 if (type.getBasicType() == glslang::EbtReference) {
3851 // Original and non-writable params pass the pointer directly and
3852 // use restrict/aliased, others are stored to a pointer in Function
3853 // memory and use RestrictPointer/AliasedPointer.
3854 if (originalParam(type.getQualifier().storage, type, false) ||
3855 !writableParam(type.getQualifier().storage)) {
3856 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
3857 } else {
3858 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
3859 }
3860 }
John Kessenichfad62972017-07-18 02:35:46 -06003861 };
3862
John Kessenich140f3df2015-06-26 16:58:36 -06003863 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3864 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003865 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003866 continue;
3867
3868 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003869 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003870 //
qining25262b32016-05-06 17:25:16 -04003871 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003872 // function. What it is an address of varies:
3873 //
John Kessenich4bf71552016-09-02 11:20:21 -06003874 // - "in" parameters not marked as "const" can be written to without modifying the calling
3875 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003876 //
3877 // - "const in" parameters can just be the r-value, as no writes need occur.
3878 //
John Kessenich4bf71552016-09-02 11:20:21 -06003879 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3880 // 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 -06003881
3882 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003883 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003884 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3885
John Kessenichfad62972017-07-18 02:35:46 -06003886 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3887 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003888
John Kessenichfad62972017-07-18 02:35:46 -06003889 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003890 for (int p = 0; p < (int)parameters.size(); ++p) {
3891 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3892 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003893 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003894 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003895 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003896 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3897 else
John Kessenich4bf71552016-09-02 11:20:21 -06003898 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003899 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003900 paramTypes.push_back(typeId);
3901 }
3902
3903 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003904 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3905 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003906 glslFunction->getName().c_str(), paramTypes,
3907 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003908 if (implicitThis)
3909 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003910
3911 // Track function to emit/call later
3912 functionMap[glslFunction->getName().c_str()] = function;
3913
3914 // Set the parameter id's
3915 for (int p = 0; p < (int)parameters.size(); ++p) {
3916 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3917 // give a name too
3918 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3919 }
3920 }
3921}
3922
3923// Process all the initializers, while skipping the functions and link objects
3924void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3925{
3926 builder.setBuildPoint(shaderEntry->getLastBlock());
3927 for (int i = 0; i < (int)initializers.size(); ++i) {
3928 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3929 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3930
3931 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003932 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003933 initializer->traverse(this);
3934 }
3935 }
3936}
3937
3938// Process all the functions, while skipping initializers.
3939void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3940{
3941 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3942 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003943 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003944 node->traverse(this);
3945 }
3946}
3947
3948void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3949{
qining25262b32016-05-06 17:25:16 -04003950 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003951 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003952 currentFunction = functionMap[node->getName().c_str()];
3953 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003954 builder.setBuildPoint(functionBlock);
3955}
3956
Rex Xu04db3f52015-09-16 11:44:02 +08003957void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003958{
Rex Xufc618912015-09-09 16:42:49 +08003959 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003960
3961 glslang::TSampler sampler = {};
3962 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003963#ifdef AMD_EXTENSIONS
3964 bool f16ShadowCompare = false;
3965#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003966 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003967 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3968 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003969#ifdef AMD_EXTENSIONS
3970 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3971#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003972 }
3973
John Kessenich140f3df2015-06-26 16:58:36 -06003974 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3975 builder.clearAccessChain();
3976 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003977
3978 // Special case l-value operands
3979 bool lvalue = false;
3980 switch (node.getOp()) {
3981 case glslang::EOpImageAtomicAdd:
3982 case glslang::EOpImageAtomicMin:
3983 case glslang::EOpImageAtomicMax:
3984 case glslang::EOpImageAtomicAnd:
3985 case glslang::EOpImageAtomicOr:
3986 case glslang::EOpImageAtomicXor:
3987 case glslang::EOpImageAtomicExchange:
3988 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05003989 case glslang::EOpImageAtomicLoad:
3990 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08003991 if (i == 0)
3992 lvalue = true;
3993 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003994 case glslang::EOpSparseImageLoad:
3995 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3996 lvalue = true;
3997 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003998#ifdef AMD_EXTENSIONS
3999 case glslang::EOpSparseTexture:
4000 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4001 lvalue = true;
4002 break;
4003 case glslang::EOpSparseTextureClamp:
4004 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4005 lvalue = true;
4006 break;
4007 case glslang::EOpSparseTextureLod:
4008 case glslang::EOpSparseTextureOffset:
4009 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4010 lvalue = true;
4011 break;
4012#else
Rex Xu48edadf2015-12-31 16:11:41 +08004013 case glslang::EOpSparseTexture:
4014 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4015 lvalue = true;
4016 break;
4017 case glslang::EOpSparseTextureClamp:
4018 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4019 lvalue = true;
4020 break;
4021 case glslang::EOpSparseTextureLod:
4022 case glslang::EOpSparseTextureOffset:
4023 if (i == 3)
4024 lvalue = true;
4025 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004026#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004027 case glslang::EOpSparseTextureFetch:
4028 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4029 lvalue = true;
4030 break;
4031 case glslang::EOpSparseTextureFetchOffset:
4032 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4033 lvalue = true;
4034 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004035#ifdef AMD_EXTENSIONS
4036 case glslang::EOpSparseTextureLodOffset:
4037 case glslang::EOpSparseTextureGrad:
4038 case glslang::EOpSparseTextureOffsetClamp:
4039 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4040 lvalue = true;
4041 break;
4042 case glslang::EOpSparseTextureGradOffset:
4043 case glslang::EOpSparseTextureGradClamp:
4044 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4045 lvalue = true;
4046 break;
4047 case glslang::EOpSparseTextureGradOffsetClamp:
4048 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4049 lvalue = true;
4050 break;
4051#else
Rex Xu48edadf2015-12-31 16:11:41 +08004052 case glslang::EOpSparseTextureLodOffset:
4053 case glslang::EOpSparseTextureGrad:
4054 case glslang::EOpSparseTextureOffsetClamp:
4055 if (i == 4)
4056 lvalue = true;
4057 break;
4058 case glslang::EOpSparseTextureGradOffset:
4059 case glslang::EOpSparseTextureGradClamp:
4060 if (i == 5)
4061 lvalue = true;
4062 break;
4063 case glslang::EOpSparseTextureGradOffsetClamp:
4064 if (i == 6)
4065 lvalue = true;
4066 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004067#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004068 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004069 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4070 lvalue = true;
4071 break;
4072 case glslang::EOpSparseTextureGatherOffset:
4073 case glslang::EOpSparseTextureGatherOffsets:
4074 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4075 lvalue = true;
4076 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004077#ifdef AMD_EXTENSIONS
4078 case glslang::EOpSparseTextureGatherLod:
4079 if (i == 3)
4080 lvalue = true;
4081 break;
4082 case glslang::EOpSparseTextureGatherLodOffset:
4083 case glslang::EOpSparseTextureGatherLodOffsets:
4084 if (i == 4)
4085 lvalue = true;
4086 break;
Rex Xu129799a2017-07-05 17:23:28 +08004087 case glslang::EOpSparseImageLoadLod:
4088 if (i == 3)
4089 lvalue = true;
4090 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004091#endif
Chao Chen3a137962018-09-19 11:41:27 -07004092#ifdef NV_EXTENSIONS
4093 case glslang::EOpImageSampleFootprintNV:
4094 if (i == 4)
4095 lvalue = true;
4096 break;
4097 case glslang::EOpImageSampleFootprintClampNV:
4098 case glslang::EOpImageSampleFootprintLodNV:
4099 if (i == 5)
4100 lvalue = true;
4101 break;
4102 case glslang::EOpImageSampleFootprintGradNV:
4103 if (i == 6)
4104 lvalue = true;
4105 break;
4106 case glslang::EOpImageSampleFootprintGradClampNV:
4107 if (i == 7)
4108 lvalue = true;
4109 break;
4110#endif
Rex Xufc618912015-09-09 16:42:49 +08004111 default:
4112 break;
4113 }
4114
Rex Xu6b86d492015-09-16 17:48:22 +08004115 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08004116 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08004117 else
John Kessenich32cfd492016-02-02 12:37:46 -07004118 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004119 }
4120}
4121
John Kessenichfc51d282015-08-19 13:34:18 -06004122void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004123{
John Kessenichfc51d282015-08-19 13:34:18 -06004124 builder.clearAccessChain();
4125 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004126 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004127}
John Kessenich140f3df2015-06-26 16:58:36 -06004128
John Kessenichfc51d282015-08-19 13:34:18 -06004129spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4130{
John Kesseniche485c7a2017-05-31 18:50:53 -06004131 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004132 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004133
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004134 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004135
John Kessenichfc51d282015-08-19 13:34:18 -06004136 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004137
4138 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4139 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
4140 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004141#ifdef AMD_EXTENSIONS
4142 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
4143 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4144 : false;
4145#endif
4146
John Kessenichfc51d282015-08-19 13:34:18 -06004147 std::vector<spv::Id> arguments;
4148 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08004149 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06004150 else
4151 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004152 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004153
4154 spv::Builder::TextureParameters params = { };
4155 params.sampler = arguments[0];
4156
Rex Xu04db3f52015-09-16 11:44:02 +08004157 glslang::TCrackedTextureOp cracked;
4158 node->crackTexture(sampler, cracked);
4159
amhagan05506bb2017-06-13 16:53:02 -04004160 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004161
John Kessenichfc51d282015-08-19 13:34:18 -06004162 // Check for queries
4163 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004164 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4165 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004166 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004167
John Kessenichfc51d282015-08-19 13:34:18 -06004168 switch (node->getOp()) {
4169 case glslang::EOpImageQuerySize:
4170 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004171 if (arguments.size() > 1) {
4172 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004173 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004174 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004175 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004176 case glslang::EOpImageQuerySamples:
4177 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004178 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004179 case glslang::EOpTextureQueryLod:
4180 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004181 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004182 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004183 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004184 case glslang::EOpSparseTexelsResident:
4185 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004186 default:
4187 assert(0);
4188 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004189 }
John Kessenich140f3df2015-06-26 16:58:36 -06004190 }
4191
LoopDawg4425f242018-02-18 11:40:01 -07004192 int components = node->getType().getVectorSize();
4193
4194 if (node->getOp() == glslang::EOpTextureFetch) {
4195 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4196 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4197 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4198 // here around e.g. which ones return scalars or other types.
4199 components = 4;
4200 }
4201
4202 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4203
4204 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4205
Rex Xufc618912015-09-09 16:42:49 +08004206 // Check for image functions other than queries
4207 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004208 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004209 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004210 spv::IdImmediate image = { true, *(opIt++) };
4211 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004212
4213 // Handle subpass operations
4214 // TODO: GLSL should change to have the "MS" only on the type rather than the
4215 // built-in function.
4216 if (cracked.subpass) {
4217 // add on the (0,0) coordinate
4218 spv::Id zero = builder.makeIntConstant(0);
4219 std::vector<spv::Id> comps;
4220 comps.push_back(zero);
4221 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004222 spv::IdImmediate coord = { true,
4223 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4224 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07004225 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06004226 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
4227 operands.push_back(imageOperands);
4228 spv::IdImmediate imageOperand = { true, *(opIt++) };
4229 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07004230 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004231 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4232 builder.setPrecision(result, precision);
4233 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004234 }
4235
John Kessenich149afc32018-08-14 13:31:43 -06004236 spv::IdImmediate coord = { true, *(opIt++) };
4237 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004238#ifdef AMD_EXTENSIONS
4239 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4240#else
John Kessenich56bab042015-09-16 10:54:31 -06004241 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004242#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004243 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004244 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004245 mask = mask | spv::ImageOperandsSampleMask;
4246 }
Rex Xu129799a2017-07-05 17:23:28 +08004247#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004248 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004249 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4250 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004251 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004252 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004253#endif
4254 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4255 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4256 if (mask) {
4257 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4258 operands.push_back(imageOperands);
4259 }
4260 if (mask & spv::ImageOperandsSampleMask) {
4261 spv::IdImmediate imageOperand = { true, *opIt++ };
4262 operands.push_back(imageOperand);
4263 }
4264#ifdef AMD_EXTENSIONS
4265 if (mask & spv::ImageOperandsLodMask) {
4266 spv::IdImmediate imageOperand = { true, *opIt++ };
4267 operands.push_back(imageOperand);
4268 }
4269#endif
4270 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4271 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4272 operands.push_back(imageOperand);
4273 }
4274
John Kessenich149afc32018-08-14 13:31:43 -06004275 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004276 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004277
John Kessenich149afc32018-08-14 13:31:43 -06004278 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004279 builder.setPrecision(result[0], precision);
4280
4281 // If needed, add a conversion constructor to the proper size.
4282 if (components != node->getType().getVectorSize())
4283 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4284
4285 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004286#ifdef AMD_EXTENSIONS
4287 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4288#else
John Kessenich56bab042015-09-16 10:54:31 -06004289 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004290#endif
Rex Xu129799a2017-07-05 17:23:28 +08004291
Jeff Bolz36831c92018-09-05 10:11:41 -05004292 // Push the texel value before the operands
4293#ifdef AMD_EXTENSIONS
4294 if (sampler.ms || cracked.lod) {
4295#else
4296 if (sampler.ms) {
4297#endif
John Kessenich149afc32018-08-14 13:31:43 -06004298 spv::IdImmediate texel = { true, *(opIt + 1) };
4299 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004300 } else {
4301 spv::IdImmediate texel = { true, *opIt };
4302 operands.push_back(texel);
4303 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004304
4305 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4306 if (sampler.ms) {
4307 mask = mask | spv::ImageOperandsSampleMask;
4308 }
4309#ifdef AMD_EXTENSIONS
4310 if (cracked.lod) {
4311 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4312 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4313 mask = mask | spv::ImageOperandsLodMask;
4314 }
4315#endif
4316 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4317 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
4318 if (mask) {
4319 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4320 operands.push_back(imageOperands);
4321 }
4322 if (mask & spv::ImageOperandsSampleMask) {
4323 spv::IdImmediate imageOperand = { true, *opIt++ };
4324 operands.push_back(imageOperand);
4325 }
4326#ifdef AMD_EXTENSIONS
4327 if (mask & spv::ImageOperandsLodMask) {
4328 spv::IdImmediate imageOperand = { true, *opIt++ };
4329 operands.push_back(imageOperand);
4330 }
4331#endif
4332 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
4333 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4334 operands.push_back(imageOperand);
4335 }
4336
John Kessenich56bab042015-09-16 10:54:31 -06004337 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004338 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004339 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004340 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004341#ifdef AMD_EXTENSIONS
4342 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
4343#else
Rex Xu5eafa472016-02-19 22:24:03 +08004344 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004345#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004346 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004347 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004348 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4349
Jeff Bolz36831c92018-09-05 10:11:41 -05004350 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004351 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004352 mask = mask | spv::ImageOperandsSampleMask;
4353 }
Rex Xu129799a2017-07-05 17:23:28 +08004354#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004355 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004356 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4357 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4358
Jeff Bolz36831c92018-09-05 10:11:41 -05004359 mask = mask | spv::ImageOperandsLodMask;
4360 }
4361#endif
4362 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4363 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4364 if (mask) {
4365 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004366 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004367 }
4368 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004369 spv::IdImmediate imageOperand = { true, *opIt++ };
4370 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004371 }
4372#ifdef AMD_EXTENSIONS
4373 if (mask & spv::ImageOperandsLodMask) {
4374 spv::IdImmediate imageOperand = { true, *opIt++ };
4375 operands.push_back(imageOperand);
4376 }
Rex Xu129799a2017-07-05 17:23:28 +08004377#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004378 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4379 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4380 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004381 }
4382
4383 // Create the return type that was a special structure
4384 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004385 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004386 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4387 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4388
4389 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4390
4391 // Decode the return type
4392 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4393 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004394 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004395 // Process image atomic operations
4396
4397 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4398 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004399 // For non-MS, the sample value should be 0
4400 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4401 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004402
Jeff Bolz36831c92018-09-05 10:11:41 -05004403 spv::Id resultTypeId;
4404 // imageAtomicStore has a void return type so base the pointer type on
4405 // the type of the value operand.
4406 if (node->getOp() == glslang::EOpImageAtomicStore) {
4407 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4408 } else {
4409 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4410 }
John Kessenich56bab042015-09-16 10:54:31 -06004411 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004412
4413 std::vector<spv::Id> operands;
4414 operands.push_back(pointer);
4415 for (; opIt != arguments.end(); ++opIt)
4416 operands.push_back(*opIt);
4417
John Kessenich8c8505c2016-07-26 12:50:38 -06004418 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004419 }
4420 }
4421
amhagan05506bb2017-06-13 16:53:02 -04004422#ifdef AMD_EXTENSIONS
4423 // Check for fragment mask functions other than queries
4424 if (cracked.fragMask) {
4425 assert(sampler.ms);
4426
4427 auto opIt = arguments.begin();
4428 std::vector<spv::Id> operands;
4429
4430 // Extract the image if necessary
4431 if (builder.isSampledImage(params.sampler))
4432 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4433
4434 operands.push_back(params.sampler);
4435 ++opIt;
4436
4437 if (sampler.isSubpass()) {
4438 // add on the (0,0) coordinate
4439 spv::Id zero = builder.makeIntConstant(0);
4440 std::vector<spv::Id> comps;
4441 comps.push_back(zero);
4442 comps.push_back(zero);
4443 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4444 }
4445
4446 for (; opIt != arguments.end(); ++opIt)
4447 operands.push_back(*opIt);
4448
4449 spv::Op fragMaskOp = spv::OpNop;
4450 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4451 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4452 else if (node->getOp() == glslang::EOpFragmentFetch)
4453 fragMaskOp = spv::OpFragmentFetchAMD;
4454
4455 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4456 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4457 return builder.createOp(fragMaskOp, resultType(), operands);
4458 }
4459#endif
4460
Rex Xufc618912015-09-09 16:42:49 +08004461 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004462 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004463#ifdef NV_EXTENSIONS
4464 bool imageFootprint = node->isImageFootprint();
4465#endif
4466
Rex Xu71519fe2015-11-11 15:35:47 +08004467 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4468
John Kessenichfc51d282015-08-19 13:34:18 -06004469 // check for bias argument
4470 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004471#ifdef AMD_EXTENSIONS
4472 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4473#else
Rex Xu71519fe2015-11-11 15:35:47 +08004474 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004475#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004476 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004477#ifdef AMD_EXTENSIONS
4478 if (cracked.gather)
4479 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004480
4481 if (f16ShadowCompare)
4482 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004483#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004484 if (cracked.offset)
4485 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004486#ifdef AMD_EXTENSIONS
4487 else if (cracked.offsets)
4488 ++nonBiasArgCount;
4489#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004490 if (cracked.grad)
4491 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004492 if (cracked.lodClamp)
4493 ++nonBiasArgCount;
4494 if (sparse)
4495 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004496#ifdef NV_EXTENSIONS
4497 if (imageFootprint)
4498 //Following three extra arguments
4499 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4500 nonBiasArgCount += 3;
4501#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004502 if ((int)arguments.size() > nonBiasArgCount)
4503 bias = true;
4504 }
4505
John Kessenicha5c33d62016-06-02 23:45:21 -06004506 // See if the sampler param should really be just the SPV image part
4507 if (cracked.fetch) {
4508 // a fetch needs to have the image extracted first
4509 if (builder.isSampledImage(params.sampler))
4510 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4511 }
4512
Rex Xu225e0fc2016-11-17 17:47:59 +08004513#ifdef AMD_EXTENSIONS
4514 if (cracked.gather) {
4515 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4516 if (bias || cracked.lod ||
4517 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4518 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004519 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004520 }
4521 }
4522#endif
4523
John Kessenichfc51d282015-08-19 13:34:18 -06004524 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004525
John Kessenichfc51d282015-08-19 13:34:18 -06004526 params.coords = arguments[1];
4527 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004528 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004529
4530 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004531#ifdef AMD_EXTENSIONS
4532 if (cubeCompare || f16ShadowCompare) {
4533#else
Rex Xu48edadf2015-12-31 16:11:41 +08004534 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004535#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004536 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004537 ++extraArgs;
4538 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004539 params.Dref = arguments[2];
4540 ++extraArgs;
4541 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004542 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004543 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004544 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004545 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004546 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004547 dRefComp = builder.getNumComponents(params.coords) - 1;
4548 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004549 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4550 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004551
4552 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004553 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004554 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004555 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004556 } else if (glslangIntermediate->getStage() != EShLangFragment
4557#ifdef NV_EXTENSIONS
4558 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4559 && !(glslangIntermediate->getStage() == EShLangCompute &&
4560 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4561#endif
4562 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004563 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4564 noImplicitLod = true;
4565 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004566
4567 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004568 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004569 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004570 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004571 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004572
4573 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004574 if (cracked.grad) {
4575 params.gradX = arguments[2 + extraArgs];
4576 params.gradY = arguments[3 + extraArgs];
4577 extraArgs += 2;
4578 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004579
4580 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004581 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004582 params.offset = arguments[2 + extraArgs];
4583 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004584 } else if (cracked.offsets) {
4585 params.offsets = arguments[2 + extraArgs];
4586 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004587 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004588
4589 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004590 if (cracked.lodClamp) {
4591 params.lodClamp = arguments[2 + extraArgs];
4592 ++extraArgs;
4593 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004594 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004595 if (sparse) {
4596 params.texelOut = arguments[2 + extraArgs];
4597 ++extraArgs;
4598 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004599
John Kessenich76d4dfc2016-06-16 12:43:23 -06004600 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004601 if (cracked.gather && ! sampler.shadow) {
4602 // default component is 0, if missing, otherwise an argument
4603 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004604 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004605 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004606 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004607 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004608 }
Chao Chen3a137962018-09-19 11:41:27 -07004609#ifdef NV_EXTENSIONS
4610 spv::Id resultStruct = spv::NoResult;
4611 if (imageFootprint) {
4612 //Following three extra arguments
4613 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4614 params.granularity = arguments[2 + extraArgs];
4615 params.coarse = arguments[3 + extraArgs];
4616 resultStruct = arguments[4 + extraArgs];
4617 extraArgs += 3;
4618 }
4619#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004620 // bias
4621 if (bias) {
4622 params.bias = arguments[2 + extraArgs];
4623 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004624 }
John Kessenichfc51d282015-08-19 13:34:18 -06004625
Chao Chen3a137962018-09-19 11:41:27 -07004626#ifdef NV_EXTENSIONS
4627 if (imageFootprint) {
4628 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4629 builder.addCapability(spv::CapabilityImageFootprintNV);
4630
4631
4632 //resultStructType(OpenGL type) contains 5 elements:
4633 //struct gl_TextureFootprint2DNV {
4634 // uvec2 anchor;
4635 // uvec2 offset;
4636 // uvec2 mask;
4637 // uint lod;
4638 // uint granularity;
4639 //};
4640 //or
4641 //struct gl_TextureFootprint3DNV {
4642 // uvec3 anchor;
4643 // uvec3 offset;
4644 // uvec2 mask;
4645 // uint lod;
4646 // uint granularity;
4647 //};
4648 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4649 assert(builder.isStructType(resultStructType));
4650
4651 //resType (SPIR-V type) contains 6 elements:
4652 //Member 0 must be a Boolean type scalar(LOD),
4653 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4654 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4655 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4656 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4657 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4658 std::vector<spv::Id> members;
4659 members.push_back(resultType());
4660 for (int i = 0; i < 5; i++) {
4661 members.push_back(builder.getContainedTypeId(resultStructType, i));
4662 }
4663 spv::Id resType = builder.makeStructType(members, "ResType");
4664
4665 //call ImageFootprintNV
4666 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
4667
4668 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4669 for (int i = 0; i < 5; i++) {
4670 builder.clearAccessChain();
4671 builder.setAccessChainLValue(resultStruct);
4672
4673 //Accessing to a struct we created, no coherent flag is set
4674 spv::Builder::AccessChain::CoherentFlags flags;
4675 flags.clear();
4676
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004677 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004678 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4679 }
4680 return builder.createCompositeExtract(res, resultType(), 0);
4681 }
4682#endif
4683
John Kessenich65336482016-06-16 14:06:26 -06004684 // projective component (might not to move)
4685 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4686 // are divided by the last component of P."
4687 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4688 // unused components will appear after all used components."
4689 if (cracked.proj) {
4690 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4691 int projTargetComp;
4692 switch (sampler.dim) {
4693 case glslang::Esd1D: projTargetComp = 1; break;
4694 case glslang::Esd2D: projTargetComp = 2; break;
4695 case glslang::EsdRect: projTargetComp = 2; break;
4696 default: projTargetComp = projSourceComp; break;
4697 }
4698 // copy the projective coordinate if we have to
4699 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004700 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004701 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4702 projSourceComp);
4703 params.coords = builder.createCompositeInsert(projComp, params.coords,
4704 builder.getTypeId(params.coords), projTargetComp);
4705 }
4706 }
4707
Jeff Bolz36831c92018-09-05 10:11:41 -05004708 // nonprivate
4709 if (imageType.getQualifier().nonprivate) {
4710 params.nonprivate = true;
4711 }
4712
4713 // volatile
4714 if (imageType.getQualifier().volatil) {
4715 params.volatil = true;
4716 }
4717
St0fFa1184dd2018-04-09 21:08:14 +02004718 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004719 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004720 );
LoopDawg4425f242018-02-18 11:40:01 -07004721
4722 if (components != node->getType().getVectorSize())
4723 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4724
4725 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004726}
4727
4728spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4729{
4730 // Grab the function's pointer from the previously created function
4731 spv::Function* function = functionMap[node->getName().c_str()];
4732 if (! function)
4733 return 0;
4734
4735 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4736 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4737
4738 // See comments in makeFunctions() for details about the semantics for parameter passing.
4739 //
4740 // These imply we need a four step process:
4741 // 1. Evaluate the arguments
4742 // 2. Allocate and make copies of in, out, and inout arguments
4743 // 3. Make the call
4744 // 4. Copy back the results
4745
John Kessenichd3ed90b2018-05-04 11:43:03 -06004746 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004747 std::vector<spv::Builder::AccessChain> lValues;
4748 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004749 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004750 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004751 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004752 // build l-value
4753 builder.clearAccessChain();
4754 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004755 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004756 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004757 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004758 // save l-value
4759 lValues.push_back(builder.getAccessChain());
4760 } else {
4761 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004762 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004763 }
4764 }
4765
4766 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4767 // copy the original into that space.
4768 //
4769 // Also, build up the list of actual arguments to pass in for the call
4770 int lValueCount = 0;
4771 int rValueCount = 0;
4772 std::vector<spv::Id> spvArgs;
4773 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4774 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004775 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004776 builder.setAccessChain(lValues[lValueCount]);
4777 arg = builder.accessChainGetLValue();
4778 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004779 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004780 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004781 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004782 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4783 // need to copy the input into output space
4784 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004785 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004786 builder.clearAccessChain();
4787 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004788 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004789 }
4790 ++lValueCount;
4791 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004792 // process r-value, which involves a copy for a type mismatch
4793 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4794 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4795 builder.clearAccessChain();
4796 builder.setAccessChainLValue(argCopy);
4797 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4798 arg = builder.createLoad(argCopy);
4799 } else
4800 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004801 ++rValueCount;
4802 }
4803 spvArgs.push_back(arg);
4804 }
4805
4806 // 3. Make the call.
4807 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004808 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004809
4810 // 4. Copy back out an "out" arguments.
4811 lValueCount = 0;
4812 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004813 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004814 ++lValueCount;
4815 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004816 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4817 spv::Id copy = builder.createLoad(spvArgs[a]);
4818 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004819 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004820 }
4821 ++lValueCount;
4822 }
4823 }
4824
4825 return result;
4826}
4827
4828// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004829spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004830 spv::Id typeId, spv::Id left, spv::Id right,
4831 glslang::TBasicType typeProxy, bool reduceComparison)
4832{
John Kessenich66011cb2018-03-06 16:12:04 -07004833 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4834 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004835 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004836
4837 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004838 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004839 bool comparison = false;
4840
4841 switch (op) {
4842 case glslang::EOpAdd:
4843 case glslang::EOpAddAssign:
4844 if (isFloat)
4845 binOp = spv::OpFAdd;
4846 else
4847 binOp = spv::OpIAdd;
4848 break;
4849 case glslang::EOpSub:
4850 case glslang::EOpSubAssign:
4851 if (isFloat)
4852 binOp = spv::OpFSub;
4853 else
4854 binOp = spv::OpISub;
4855 break;
4856 case glslang::EOpMul:
4857 case glslang::EOpMulAssign:
4858 if (isFloat)
4859 binOp = spv::OpFMul;
4860 else
4861 binOp = spv::OpIMul;
4862 break;
4863 case glslang::EOpVectorTimesScalar:
4864 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004865 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004866 if (builder.isVector(right))
4867 std::swap(left, right);
4868 assert(builder.isScalar(right));
4869 needMatchingVectors = false;
4870 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01004871 } else if (isFloat)
4872 binOp = spv::OpFMul;
4873 else
John Kessenichec43d0a2015-07-04 17:17:31 -06004874 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004875 break;
4876 case glslang::EOpVectorTimesMatrix:
4877 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004878 binOp = spv::OpVectorTimesMatrix;
4879 break;
4880 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004881 binOp = spv::OpMatrixTimesVector;
4882 break;
4883 case glslang::EOpMatrixTimesScalar:
4884 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004885 binOp = spv::OpMatrixTimesScalar;
4886 break;
4887 case glslang::EOpMatrixTimesMatrix:
4888 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004889 binOp = spv::OpMatrixTimesMatrix;
4890 break;
4891 case glslang::EOpOuterProduct:
4892 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004893 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004894 break;
4895
4896 case glslang::EOpDiv:
4897 case glslang::EOpDivAssign:
4898 if (isFloat)
4899 binOp = spv::OpFDiv;
4900 else if (isUnsigned)
4901 binOp = spv::OpUDiv;
4902 else
4903 binOp = spv::OpSDiv;
4904 break;
4905 case glslang::EOpMod:
4906 case glslang::EOpModAssign:
4907 if (isFloat)
4908 binOp = spv::OpFMod;
4909 else if (isUnsigned)
4910 binOp = spv::OpUMod;
4911 else
4912 binOp = spv::OpSMod;
4913 break;
4914 case glslang::EOpRightShift:
4915 case glslang::EOpRightShiftAssign:
4916 if (isUnsigned)
4917 binOp = spv::OpShiftRightLogical;
4918 else
4919 binOp = spv::OpShiftRightArithmetic;
4920 break;
4921 case glslang::EOpLeftShift:
4922 case glslang::EOpLeftShiftAssign:
4923 binOp = spv::OpShiftLeftLogical;
4924 break;
4925 case glslang::EOpAnd:
4926 case glslang::EOpAndAssign:
4927 binOp = spv::OpBitwiseAnd;
4928 break;
4929 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004930 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004931 binOp = spv::OpLogicalAnd;
4932 break;
4933 case glslang::EOpInclusiveOr:
4934 case glslang::EOpInclusiveOrAssign:
4935 binOp = spv::OpBitwiseOr;
4936 break;
4937 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004938 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004939 binOp = spv::OpLogicalOr;
4940 break;
4941 case glslang::EOpExclusiveOr:
4942 case glslang::EOpExclusiveOrAssign:
4943 binOp = spv::OpBitwiseXor;
4944 break;
4945 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004946 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004947 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004948 break;
4949
4950 case glslang::EOpLessThan:
4951 case glslang::EOpGreaterThan:
4952 case glslang::EOpLessThanEqual:
4953 case glslang::EOpGreaterThanEqual:
4954 case glslang::EOpEqual:
4955 case glslang::EOpNotEqual:
4956 case glslang::EOpVectorEqual:
4957 case glslang::EOpVectorNotEqual:
4958 comparison = true;
4959 break;
4960 default:
4961 break;
4962 }
4963
John Kessenich7c1aa102015-10-15 13:29:11 -06004964 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004965 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004966 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06004967 if (builder.isMatrix(left) || builder.isMatrix(right) ||
4968 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004969 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004970
4971 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004972 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004973 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004974
qining25262b32016-05-06 17:25:16 -04004975 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004976 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004977 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004978 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004979 }
4980
4981 if (! comparison)
4982 return 0;
4983
John Kessenich7c1aa102015-10-15 13:29:11 -06004984 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004985
John Kessenich4583b612016-08-07 19:14:22 -06004986 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004987 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4988 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004989 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004990 return result;
4991 }
John Kessenich140f3df2015-06-26 16:58:36 -06004992
4993 switch (op) {
4994 case glslang::EOpLessThan:
4995 if (isFloat)
4996 binOp = spv::OpFOrdLessThan;
4997 else if (isUnsigned)
4998 binOp = spv::OpULessThan;
4999 else
5000 binOp = spv::OpSLessThan;
5001 break;
5002 case glslang::EOpGreaterThan:
5003 if (isFloat)
5004 binOp = spv::OpFOrdGreaterThan;
5005 else if (isUnsigned)
5006 binOp = spv::OpUGreaterThan;
5007 else
5008 binOp = spv::OpSGreaterThan;
5009 break;
5010 case glslang::EOpLessThanEqual:
5011 if (isFloat)
5012 binOp = spv::OpFOrdLessThanEqual;
5013 else if (isUnsigned)
5014 binOp = spv::OpULessThanEqual;
5015 else
5016 binOp = spv::OpSLessThanEqual;
5017 break;
5018 case glslang::EOpGreaterThanEqual:
5019 if (isFloat)
5020 binOp = spv::OpFOrdGreaterThanEqual;
5021 else if (isUnsigned)
5022 binOp = spv::OpUGreaterThanEqual;
5023 else
5024 binOp = spv::OpSGreaterThanEqual;
5025 break;
5026 case glslang::EOpEqual:
5027 case glslang::EOpVectorEqual:
5028 if (isFloat)
5029 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005030 else if (isBool)
5031 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005032 else
5033 binOp = spv::OpIEqual;
5034 break;
5035 case glslang::EOpNotEqual:
5036 case glslang::EOpVectorNotEqual:
5037 if (isFloat)
5038 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005039 else if (isBool)
5040 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005041 else
5042 binOp = spv::OpINotEqual;
5043 break;
5044 default:
5045 break;
5046 }
5047
qining25262b32016-05-06 17:25:16 -04005048 if (binOp != spv::OpNop) {
5049 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005050 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005051 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005052 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005053 }
John Kessenich140f3df2015-06-26 16:58:36 -06005054
5055 return 0;
5056}
5057
John Kessenich04bb8a02015-12-12 12:28:14 -07005058//
5059// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5060// These can be any of:
5061//
5062// matrix * scalar
5063// scalar * matrix
5064// matrix * matrix linear algebraic
5065// matrix * vector
5066// vector * matrix
5067// matrix * matrix componentwise
5068// matrix op matrix op in {+, -, /}
5069// matrix op scalar op in {+, -, /}
5070// scalar op matrix op in {+, -, /}
5071//
John Kessenichead86222018-03-28 18:01:20 -06005072spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5073 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005074{
5075 bool firstClass = true;
5076
5077 // First, handle first-class matrix operations (* and matrix/scalar)
5078 switch (op) {
5079 case spv::OpFDiv:
5080 if (builder.isMatrix(left) && builder.isScalar(right)) {
5081 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005082 spv::Id resultType = builder.getTypeId(right);
5083 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005084 op = spv::OpMatrixTimesScalar;
5085 } else
5086 firstClass = false;
5087 break;
5088 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005089 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005090 std::swap(left, right);
5091 assert(builder.isScalar(right));
5092 break;
5093 case spv::OpVectorTimesMatrix:
5094 assert(builder.isVector(left));
5095 assert(builder.isMatrix(right));
5096 break;
5097 case spv::OpMatrixTimesVector:
5098 assert(builder.isMatrix(left));
5099 assert(builder.isVector(right));
5100 break;
5101 case spv::OpMatrixTimesMatrix:
5102 assert(builder.isMatrix(left));
5103 assert(builder.isMatrix(right));
5104 break;
5105 default:
5106 firstClass = false;
5107 break;
5108 }
5109
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005110 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5111 firstClass = true;
5112
qining25262b32016-05-06 17:25:16 -04005113 if (firstClass) {
5114 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005115 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005116 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005117 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005118 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005119
LoopDawg592860c2016-06-09 08:57:35 -06005120 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005121 // The result type of all of them is the same type as the (a) matrix operand.
5122 // The algorithm is to:
5123 // - break the matrix(es) into vectors
5124 // - smear any scalar to a vector
5125 // - do vector operations
5126 // - make a matrix out the vector results
5127 switch (op) {
5128 case spv::OpFAdd:
5129 case spv::OpFSub:
5130 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005131 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005132 case spv::OpFMul:
5133 {
5134 // one time set up...
5135 bool leftMat = builder.isMatrix(left);
5136 bool rightMat = builder.isMatrix(right);
5137 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5138 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5139 spv::Id scalarType = builder.getScalarTypeId(typeId);
5140 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5141 std::vector<spv::Id> results;
5142 spv::Id smearVec = spv::NoResult;
5143 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005144 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005145 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005146 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005147
5148 // do each vector op
5149 for (unsigned int c = 0; c < numCols; ++c) {
5150 std::vector<unsigned int> indexes;
5151 indexes.push_back(c);
5152 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5153 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005154 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005155 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005156 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005157 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005158 }
5159
5160 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005161 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005162 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005163 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005164 }
5165 default:
5166 assert(0);
5167 return spv::NoResult;
5168 }
5169}
5170
John Kessenichead86222018-03-28 18:01:20 -06005171spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
5172 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005173{
5174 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005175 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005176 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005177 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5178 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005179
5180 switch (op) {
5181 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005182 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005183 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005184 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005185 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005186 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005187 unaryOp = spv::OpSNegate;
5188 break;
5189
5190 case glslang::EOpLogicalNot:
5191 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005192 unaryOp = spv::OpLogicalNot;
5193 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005194 case glslang::EOpBitwiseNot:
5195 unaryOp = spv::OpNot;
5196 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005197
John Kessenich140f3df2015-06-26 16:58:36 -06005198 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005199 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005200 break;
5201 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005202 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005203 break;
5204 case glslang::EOpTranspose:
5205 unaryOp = spv::OpTranspose;
5206 break;
5207
5208 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005209 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005210 break;
5211 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005212 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005213 break;
5214 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005215 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005216 break;
5217 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005218 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005219 break;
5220 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005221 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005222 break;
5223 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005224 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005225 break;
5226 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005227 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005228 break;
5229 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005230 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005231 break;
5232
5233 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005234 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005235 break;
5236 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005237 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005238 break;
5239 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005240 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005241 break;
5242 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005243 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005244 break;
5245 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005246 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005247 break;
5248 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005249 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005250 break;
5251
5252 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005253 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005254 break;
5255 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005256 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005257 break;
5258
5259 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005260 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005261 break;
5262 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005263 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005264 break;
5265 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005266 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005267 break;
5268 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005269 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005270 break;
5271 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005272 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005273 break;
5274 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005275 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005276 break;
5277
5278 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005279 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005280 break;
5281 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005282 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005283 break;
5284 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005285 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005286 break;
5287 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005288 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005289 break;
5290 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005291 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005292 break;
5293 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005294 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005295 break;
5296
5297 case glslang::EOpIsNan:
5298 unaryOp = spv::OpIsNan;
5299 break;
5300 case glslang::EOpIsInf:
5301 unaryOp = spv::OpIsInf;
5302 break;
LoopDawg592860c2016-06-09 08:57:35 -06005303 case glslang::EOpIsFinite:
5304 unaryOp = spv::OpIsFinite;
5305 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005306
Rex Xucbc426e2015-12-15 16:03:10 +08005307 case glslang::EOpFloatBitsToInt:
5308 case glslang::EOpFloatBitsToUint:
5309 case glslang::EOpIntBitsToFloat:
5310 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005311 case glslang::EOpDoubleBitsToInt64:
5312 case glslang::EOpDoubleBitsToUint64:
5313 case glslang::EOpInt64BitsToDouble:
5314 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005315 case glslang::EOpFloat16BitsToInt16:
5316 case glslang::EOpFloat16BitsToUint16:
5317 case glslang::EOpInt16BitsToFloat16:
5318 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005319 unaryOp = spv::OpBitcast;
5320 break;
5321
John Kessenich140f3df2015-06-26 16:58:36 -06005322 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005323 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005324 break;
5325 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005326 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005327 break;
5328 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005329 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005330 break;
5331 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005332 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005333 break;
5334 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005335 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005336 break;
5337 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005338 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005339 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005340 case glslang::EOpPackSnorm4x8:
5341 libCall = spv::GLSLstd450PackSnorm4x8;
5342 break;
5343 case glslang::EOpUnpackSnorm4x8:
5344 libCall = spv::GLSLstd450UnpackSnorm4x8;
5345 break;
5346 case glslang::EOpPackUnorm4x8:
5347 libCall = spv::GLSLstd450PackUnorm4x8;
5348 break;
5349 case glslang::EOpUnpackUnorm4x8:
5350 libCall = spv::GLSLstd450UnpackUnorm4x8;
5351 break;
5352 case glslang::EOpPackDouble2x32:
5353 libCall = spv::GLSLstd450PackDouble2x32;
5354 break;
5355 case glslang::EOpUnpackDouble2x32:
5356 libCall = spv::GLSLstd450UnpackDouble2x32;
5357 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005358
Rex Xu8ff43de2016-04-22 16:51:45 +08005359 case glslang::EOpPackInt2x32:
5360 case glslang::EOpUnpackInt2x32:
5361 case glslang::EOpPackUint2x32:
5362 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005363 case glslang::EOpPack16:
5364 case glslang::EOpPack32:
5365 case glslang::EOpPack64:
5366 case glslang::EOpUnpack32:
5367 case glslang::EOpUnpack16:
5368 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005369 case glslang::EOpPackInt2x16:
5370 case glslang::EOpUnpackInt2x16:
5371 case glslang::EOpPackUint2x16:
5372 case glslang::EOpUnpackUint2x16:
5373 case glslang::EOpPackInt4x16:
5374 case glslang::EOpUnpackInt4x16:
5375 case glslang::EOpPackUint4x16:
5376 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005377 case glslang::EOpPackFloat2x16:
5378 case glslang::EOpUnpackFloat2x16:
5379 unaryOp = spv::OpBitcast;
5380 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005381
John Kessenich140f3df2015-06-26 16:58:36 -06005382 case glslang::EOpDPdx:
5383 unaryOp = spv::OpDPdx;
5384 break;
5385 case glslang::EOpDPdy:
5386 unaryOp = spv::OpDPdy;
5387 break;
5388 case glslang::EOpFwidth:
5389 unaryOp = spv::OpFwidth;
5390 break;
5391 case glslang::EOpDPdxFine:
5392 unaryOp = spv::OpDPdxFine;
5393 break;
5394 case glslang::EOpDPdyFine:
5395 unaryOp = spv::OpDPdyFine;
5396 break;
5397 case glslang::EOpFwidthFine:
5398 unaryOp = spv::OpFwidthFine;
5399 break;
5400 case glslang::EOpDPdxCoarse:
5401 unaryOp = spv::OpDPdxCoarse;
5402 break;
5403 case glslang::EOpDPdyCoarse:
5404 unaryOp = spv::OpDPdyCoarse;
5405 break;
5406 case glslang::EOpFwidthCoarse:
5407 unaryOp = spv::OpFwidthCoarse;
5408 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005409 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005410#ifdef AMD_EXTENSIONS
5411 if (typeProxy == glslang::EbtFloat16)
5412 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5413#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005414 libCall = spv::GLSLstd450InterpolateAtCentroid;
5415 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005416 case glslang::EOpAny:
5417 unaryOp = spv::OpAny;
5418 break;
5419 case glslang::EOpAll:
5420 unaryOp = spv::OpAll;
5421 break;
5422
5423 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005424 if (isFloat)
5425 libCall = spv::GLSLstd450FAbs;
5426 else
5427 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005428 break;
5429 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005430 if (isFloat)
5431 libCall = spv::GLSLstd450FSign;
5432 else
5433 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005434 break;
5435
John Kessenichfc51d282015-08-19 13:34:18 -06005436 case glslang::EOpAtomicCounterIncrement:
5437 case glslang::EOpAtomicCounterDecrement:
5438 case glslang::EOpAtomicCounter:
5439 {
5440 // Handle all of the atomics in one place, in createAtomicOperation()
5441 std::vector<spv::Id> operands;
5442 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005443 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005444 }
5445
John Kessenichfc51d282015-08-19 13:34:18 -06005446 case glslang::EOpBitFieldReverse:
5447 unaryOp = spv::OpBitReverse;
5448 break;
5449 case glslang::EOpBitCount:
5450 unaryOp = spv::OpBitCount;
5451 break;
5452 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005453 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005454 break;
5455 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005456 if (isUnsigned)
5457 libCall = spv::GLSLstd450FindUMsb;
5458 else
5459 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005460 break;
5461
Rex Xu574ab042016-04-14 16:53:07 +08005462 case glslang::EOpBallot:
5463 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005464 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005465 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005466 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005467#ifdef AMD_EXTENSIONS
5468 case glslang::EOpMinInvocations:
5469 case glslang::EOpMaxInvocations:
5470 case glslang::EOpAddInvocations:
5471 case glslang::EOpMinInvocationsNonUniform:
5472 case glslang::EOpMaxInvocationsNonUniform:
5473 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005474 case glslang::EOpMinInvocationsInclusiveScan:
5475 case glslang::EOpMaxInvocationsInclusiveScan:
5476 case glslang::EOpAddInvocationsInclusiveScan:
5477 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5478 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5479 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5480 case glslang::EOpMinInvocationsExclusiveScan:
5481 case glslang::EOpMaxInvocationsExclusiveScan:
5482 case glslang::EOpAddInvocationsExclusiveScan:
5483 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5484 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5485 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005486#endif
Rex Xu51596642016-09-21 18:56:12 +08005487 {
5488 std::vector<spv::Id> operands;
5489 operands.push_back(operand);
5490 return createInvocationsOperation(op, typeId, operands, typeProxy);
5491 }
John Kessenich66011cb2018-03-06 16:12:04 -07005492 case glslang::EOpSubgroupAll:
5493 case glslang::EOpSubgroupAny:
5494 case glslang::EOpSubgroupAllEqual:
5495 case glslang::EOpSubgroupBroadcastFirst:
5496 case glslang::EOpSubgroupBallot:
5497 case glslang::EOpSubgroupInverseBallot:
5498 case glslang::EOpSubgroupBallotBitCount:
5499 case glslang::EOpSubgroupBallotInclusiveBitCount:
5500 case glslang::EOpSubgroupBallotExclusiveBitCount:
5501 case glslang::EOpSubgroupBallotFindLSB:
5502 case glslang::EOpSubgroupBallotFindMSB:
5503 case glslang::EOpSubgroupAdd:
5504 case glslang::EOpSubgroupMul:
5505 case glslang::EOpSubgroupMin:
5506 case glslang::EOpSubgroupMax:
5507 case glslang::EOpSubgroupAnd:
5508 case glslang::EOpSubgroupOr:
5509 case glslang::EOpSubgroupXor:
5510 case glslang::EOpSubgroupInclusiveAdd:
5511 case glslang::EOpSubgroupInclusiveMul:
5512 case glslang::EOpSubgroupInclusiveMin:
5513 case glslang::EOpSubgroupInclusiveMax:
5514 case glslang::EOpSubgroupInclusiveAnd:
5515 case glslang::EOpSubgroupInclusiveOr:
5516 case glslang::EOpSubgroupInclusiveXor:
5517 case glslang::EOpSubgroupExclusiveAdd:
5518 case glslang::EOpSubgroupExclusiveMul:
5519 case glslang::EOpSubgroupExclusiveMin:
5520 case glslang::EOpSubgroupExclusiveMax:
5521 case glslang::EOpSubgroupExclusiveAnd:
5522 case glslang::EOpSubgroupExclusiveOr:
5523 case glslang::EOpSubgroupExclusiveXor:
5524 case glslang::EOpSubgroupQuadSwapHorizontal:
5525 case glslang::EOpSubgroupQuadSwapVertical:
5526 case glslang::EOpSubgroupQuadSwapDiagonal: {
5527 std::vector<spv::Id> operands;
5528 operands.push_back(operand);
5529 return createSubgroupOperation(op, typeId, operands, typeProxy);
5530 }
Rex Xu9d93a232016-05-05 12:30:44 +08005531#ifdef AMD_EXTENSIONS
5532 case glslang::EOpMbcnt:
5533 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5534 libCall = spv::MbcntAMD;
5535 break;
5536
5537 case glslang::EOpCubeFaceIndex:
5538 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5539 libCall = spv::CubeFaceIndexAMD;
5540 break;
5541
5542 case glslang::EOpCubeFaceCoord:
5543 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5544 libCall = spv::CubeFaceCoordAMD;
5545 break;
5546#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005547#ifdef NV_EXTENSIONS
5548 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005549 unaryOp = spv::OpGroupNonUniformPartitionNV;
5550 break;
5551#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005552 case glslang::EOpConstructReference:
5553 unaryOp = spv::OpBitcast;
5554 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005555 default:
5556 return 0;
5557 }
5558
5559 spv::Id id;
5560 if (libCall >= 0) {
5561 std::vector<spv::Id> args;
5562 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005563 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005564 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005565 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005566 }
John Kessenich140f3df2015-06-26 16:58:36 -06005567
John Kessenichead86222018-03-28 18:01:20 -06005568 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005569 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005570 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005571}
5572
John Kessenich7a53f762016-01-20 11:19:27 -07005573// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005574spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5575 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005576{
5577 // Handle unary operations vector by vector.
5578 // The result type is the same type as the original type.
5579 // The algorithm is to:
5580 // - break the matrix into vectors
5581 // - apply the operation to each vector
5582 // - make a matrix out the vector results
5583
5584 // get the types sorted out
5585 int numCols = builder.getNumColumns(operand);
5586 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005587 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5588 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005589 std::vector<spv::Id> results;
5590
5591 // do each vector op
5592 for (int c = 0; c < numCols; ++c) {
5593 std::vector<unsigned int> indexes;
5594 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005595 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5596 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005597 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005598 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005599 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005600 }
5601
5602 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005603 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005604 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005605 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005606}
5607
John Kessenichad7645f2018-06-04 19:11:25 -06005608// For converting integers where both the bitwidth and the signedness could
5609// change, but only do the width change here. The caller is still responsible
5610// for the signedness conversion.
5611spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005612{
John Kessenichad7645f2018-06-04 19:11:25 -06005613 // Get the result type width, based on the type to convert to.
5614 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005615 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005616 case glslang::EOpConvInt16ToUint8:
5617 case glslang::EOpConvIntToUint8:
5618 case glslang::EOpConvInt64ToUint8:
5619 case glslang::EOpConvUint16ToInt8:
5620 case glslang::EOpConvUintToInt8:
5621 case glslang::EOpConvUint64ToInt8:
5622 width = 8;
5623 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005624 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005625 case glslang::EOpConvIntToUint16:
5626 case glslang::EOpConvInt64ToUint16:
5627 case glslang::EOpConvUint8ToInt16:
5628 case glslang::EOpConvUintToInt16:
5629 case glslang::EOpConvUint64ToInt16:
5630 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005631 break;
5632 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005633 case glslang::EOpConvInt16ToUint:
5634 case glslang::EOpConvInt64ToUint:
5635 case glslang::EOpConvUint8ToInt:
5636 case glslang::EOpConvUint16ToInt:
5637 case glslang::EOpConvUint64ToInt:
5638 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005639 break;
5640 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005641 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005642 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005643 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005644 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005645 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005646 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005647 break;
5648
5649 default:
5650 assert(false && "Default missing");
5651 break;
5652 }
5653
John Kessenichad7645f2018-06-04 19:11:25 -06005654 // Get the conversion operation and result type,
5655 // based on the target width, but the source type.
5656 spv::Id type = spv::NoType;
5657 spv::Op convOp = spv::OpNop;
5658 switch(op) {
5659 case glslang::EOpConvInt8ToUint16:
5660 case glslang::EOpConvInt8ToUint:
5661 case glslang::EOpConvInt8ToUint64:
5662 case glslang::EOpConvInt16ToUint8:
5663 case glslang::EOpConvInt16ToUint:
5664 case glslang::EOpConvInt16ToUint64:
5665 case glslang::EOpConvIntToUint8:
5666 case glslang::EOpConvIntToUint16:
5667 case glslang::EOpConvIntToUint64:
5668 case glslang::EOpConvInt64ToUint8:
5669 case glslang::EOpConvInt64ToUint16:
5670 case glslang::EOpConvInt64ToUint:
5671 convOp = spv::OpSConvert;
5672 type = builder.makeIntType(width);
5673 break;
5674 default:
5675 convOp = spv::OpUConvert;
5676 type = builder.makeUintType(width);
5677 break;
5678 }
5679
John Kessenich66011cb2018-03-06 16:12:04 -07005680 if (vectorSize > 0)
5681 type = builder.makeVectorType(type, vectorSize);
5682
John Kessenichad7645f2018-06-04 19:11:25 -06005683 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005684}
5685
John Kessenichead86222018-03-28 18:01:20 -06005686spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5687 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005688{
5689 spv::Op convOp = spv::OpNop;
5690 spv::Id zero = 0;
5691 spv::Id one = 0;
5692
5693 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5694
5695 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005696 case glslang::EOpConvInt8ToBool:
5697 case glslang::EOpConvUint8ToBool:
5698 zero = builder.makeUint8Constant(0);
5699 zero = makeSmearedConstant(zero, vectorSize);
5700 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005701 case glslang::EOpConvInt16ToBool:
5702 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005703 zero = builder.makeUint16Constant(0);
5704 zero = makeSmearedConstant(zero, vectorSize);
5705 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5706 case glslang::EOpConvIntToBool:
5707 case glslang::EOpConvUintToBool:
5708 zero = builder.makeUintConstant(0);
5709 zero = makeSmearedConstant(zero, vectorSize);
5710 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5711 case glslang::EOpConvInt64ToBool:
5712 case glslang::EOpConvUint64ToBool:
5713 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005714 zero = makeSmearedConstant(zero, vectorSize);
5715 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5716
5717 case glslang::EOpConvFloatToBool:
5718 zero = builder.makeFloatConstant(0.0F);
5719 zero = makeSmearedConstant(zero, vectorSize);
5720 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5721
5722 case glslang::EOpConvDoubleToBool:
5723 zero = builder.makeDoubleConstant(0.0);
5724 zero = makeSmearedConstant(zero, vectorSize);
5725 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5726
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005727 case glslang::EOpConvFloat16ToBool:
5728 zero = builder.makeFloat16Constant(0.0F);
5729 zero = makeSmearedConstant(zero, vectorSize);
5730 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005731
John Kessenich140f3df2015-06-26 16:58:36 -06005732 case glslang::EOpConvBoolToFloat:
5733 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005734 zero = builder.makeFloatConstant(0.0F);
5735 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005736 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005737
John Kessenich140f3df2015-06-26 16:58:36 -06005738 case glslang::EOpConvBoolToDouble:
5739 convOp = spv::OpSelect;
5740 zero = builder.makeDoubleConstant(0.0);
5741 one = builder.makeDoubleConstant(1.0);
5742 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005743
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005744 case glslang::EOpConvBoolToFloat16:
5745 convOp = spv::OpSelect;
5746 zero = builder.makeFloat16Constant(0.0F);
5747 one = builder.makeFloat16Constant(1.0F);
5748 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005749
5750 case glslang::EOpConvBoolToInt8:
5751 zero = builder.makeInt8Constant(0);
5752 one = builder.makeInt8Constant(1);
5753 convOp = spv::OpSelect;
5754 break;
5755
5756 case glslang::EOpConvBoolToUint8:
5757 zero = builder.makeUint8Constant(0);
5758 one = builder.makeUint8Constant(1);
5759 convOp = spv::OpSelect;
5760 break;
5761
5762 case glslang::EOpConvBoolToInt16:
5763 zero = builder.makeInt16Constant(0);
5764 one = builder.makeInt16Constant(1);
5765 convOp = spv::OpSelect;
5766 break;
5767
5768 case glslang::EOpConvBoolToUint16:
5769 zero = builder.makeUint16Constant(0);
5770 one = builder.makeUint16Constant(1);
5771 convOp = spv::OpSelect;
5772 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005773
John Kessenich140f3df2015-06-26 16:58:36 -06005774 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005775 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005776 if (op == glslang::EOpConvBoolToInt64)
5777 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005778 else
5779 zero = builder.makeIntConstant(0);
5780
5781 if (op == glslang::EOpConvBoolToInt64)
5782 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005783 else
5784 one = builder.makeIntConstant(1);
5785
John Kessenich140f3df2015-06-26 16:58:36 -06005786 convOp = spv::OpSelect;
5787 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005788
John Kessenich140f3df2015-06-26 16:58:36 -06005789 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005790 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005791 if (op == glslang::EOpConvBoolToUint64)
5792 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005793 else
5794 zero = builder.makeUintConstant(0);
5795
5796 if (op == glslang::EOpConvBoolToUint64)
5797 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005798 else
5799 one = builder.makeUintConstant(1);
5800
John Kessenich140f3df2015-06-26 16:58:36 -06005801 convOp = spv::OpSelect;
5802 break;
5803
John Kessenich66011cb2018-03-06 16:12:04 -07005804 case glslang::EOpConvInt8ToFloat16:
5805 case glslang::EOpConvInt8ToFloat:
5806 case glslang::EOpConvInt8ToDouble:
5807 case glslang::EOpConvInt16ToFloat16:
5808 case glslang::EOpConvInt16ToFloat:
5809 case glslang::EOpConvInt16ToDouble:
5810 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005811 case glslang::EOpConvIntToFloat:
5812 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005813 case glslang::EOpConvInt64ToFloat:
5814 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005815 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005816 convOp = spv::OpConvertSToF;
5817 break;
5818
John Kessenich66011cb2018-03-06 16:12:04 -07005819 case glslang::EOpConvUint8ToFloat16:
5820 case glslang::EOpConvUint8ToFloat:
5821 case glslang::EOpConvUint8ToDouble:
5822 case glslang::EOpConvUint16ToFloat16:
5823 case glslang::EOpConvUint16ToFloat:
5824 case glslang::EOpConvUint16ToDouble:
5825 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005826 case glslang::EOpConvUintToFloat:
5827 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005828 case glslang::EOpConvUint64ToFloat:
5829 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005830 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005831 convOp = spv::OpConvertUToF;
5832 break;
5833
5834 case glslang::EOpConvDoubleToFloat:
5835 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005836 case glslang::EOpConvDoubleToFloat16:
5837 case glslang::EOpConvFloat16ToDouble:
5838 case glslang::EOpConvFloatToFloat16:
5839 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005840 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005841 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005842 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005843 break;
5844
John Kessenich66011cb2018-03-06 16:12:04 -07005845 case glslang::EOpConvFloat16ToInt8:
5846 case glslang::EOpConvFloatToInt8:
5847 case glslang::EOpConvDoubleToInt8:
5848 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005849 case glslang::EOpConvFloatToInt16:
5850 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005851 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005852 case glslang::EOpConvFloatToInt:
5853 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005854 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005855 case glslang::EOpConvFloatToInt64:
5856 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005857 convOp = spv::OpConvertFToS;
5858 break;
5859
John Kessenich66011cb2018-03-06 16:12:04 -07005860 case glslang::EOpConvUint8ToInt8:
5861 case glslang::EOpConvInt8ToUint8:
5862 case glslang::EOpConvUint16ToInt16:
5863 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005864 case glslang::EOpConvUintToInt:
5865 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005866 case glslang::EOpConvUint64ToInt64:
5867 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005868 if (builder.isInSpecConstCodeGenMode()) {
5869 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005870 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5871 zero = builder.makeUint8Constant(0);
5872 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005873 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005874 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5875 zero = builder.makeUint64Constant(0);
5876 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005877 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005878 }
qining189b2032016-04-12 23:16:20 -04005879 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005880 // Use OpIAdd, instead of OpBitcast to do the conversion when
5881 // generating for OpSpecConstantOp instruction.
5882 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5883 }
5884 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005885 convOp = spv::OpBitcast;
5886 break;
5887
John Kessenich66011cb2018-03-06 16:12:04 -07005888 case glslang::EOpConvFloat16ToUint8:
5889 case glslang::EOpConvFloatToUint8:
5890 case glslang::EOpConvDoubleToUint8:
5891 case glslang::EOpConvFloat16ToUint16:
5892 case glslang::EOpConvFloatToUint16:
5893 case glslang::EOpConvDoubleToUint16:
5894 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005895 case glslang::EOpConvFloatToUint:
5896 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005897 case glslang::EOpConvFloatToUint64:
5898 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005899 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005900 convOp = spv::OpConvertFToU;
5901 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005902
John Kessenich66011cb2018-03-06 16:12:04 -07005903 case glslang::EOpConvInt8ToInt16:
5904 case glslang::EOpConvInt8ToInt:
5905 case glslang::EOpConvInt8ToInt64:
5906 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005907 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005908 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005909 case glslang::EOpConvIntToInt8:
5910 case glslang::EOpConvIntToInt16:
5911 case glslang::EOpConvIntToInt64:
5912 case glslang::EOpConvInt64ToInt8:
5913 case glslang::EOpConvInt64ToInt16:
5914 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005915 convOp = spv::OpSConvert;
5916 break;
5917
John Kessenich66011cb2018-03-06 16:12:04 -07005918 case glslang::EOpConvUint8ToUint16:
5919 case glslang::EOpConvUint8ToUint:
5920 case glslang::EOpConvUint8ToUint64:
5921 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005922 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005923 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005924 case glslang::EOpConvUintToUint8:
5925 case glslang::EOpConvUintToUint16:
5926 case glslang::EOpConvUintToUint64:
5927 case glslang::EOpConvUint64ToUint8:
5928 case glslang::EOpConvUint64ToUint16:
5929 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005930 convOp = spv::OpUConvert;
5931 break;
5932
John Kessenich66011cb2018-03-06 16:12:04 -07005933 case glslang::EOpConvInt8ToUint16:
5934 case glslang::EOpConvInt8ToUint:
5935 case glslang::EOpConvInt8ToUint64:
5936 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005937 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005938 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005939 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005940 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005941 case glslang::EOpConvIntToUint64:
5942 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005943 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005944 case glslang::EOpConvInt64ToUint:
5945 case glslang::EOpConvUint8ToInt16:
5946 case glslang::EOpConvUint8ToInt:
5947 case glslang::EOpConvUint8ToInt64:
5948 case glslang::EOpConvUint16ToInt8:
5949 case glslang::EOpConvUint16ToInt:
5950 case glslang::EOpConvUint16ToInt64:
5951 case glslang::EOpConvUintToInt8:
5952 case glslang::EOpConvUintToInt16:
5953 case glslang::EOpConvUintToInt64:
5954 case glslang::EOpConvUint64ToInt8:
5955 case glslang::EOpConvUint64ToInt16:
5956 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005957 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005958 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005959
5960 if (builder.isInSpecConstCodeGenMode()) {
5961 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005962 switch(op) {
5963 case glslang::EOpConvInt16ToUint8:
5964 case glslang::EOpConvIntToUint8:
5965 case glslang::EOpConvInt64ToUint8:
5966 case glslang::EOpConvUint16ToInt8:
5967 case glslang::EOpConvUintToInt8:
5968 case glslang::EOpConvUint64ToInt8:
5969 zero = builder.makeUint8Constant(0);
5970 break;
5971 case glslang::EOpConvInt8ToUint16:
5972 case glslang::EOpConvIntToUint16:
5973 case glslang::EOpConvInt64ToUint16:
5974 case glslang::EOpConvUint8ToInt16:
5975 case glslang::EOpConvUintToInt16:
5976 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005977 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005978 break;
5979 case glslang::EOpConvInt8ToUint:
5980 case glslang::EOpConvInt16ToUint:
5981 case glslang::EOpConvInt64ToUint:
5982 case glslang::EOpConvUint8ToInt:
5983 case glslang::EOpConvUint16ToInt:
5984 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005985 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005986 break;
5987 case glslang::EOpConvInt8ToUint64:
5988 case glslang::EOpConvInt16ToUint64:
5989 case glslang::EOpConvIntToUint64:
5990 case glslang::EOpConvUint8ToInt64:
5991 case glslang::EOpConvUint16ToInt64:
5992 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005993 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005994 break;
5995 default:
5996 assert(false && "Default missing");
5997 break;
5998 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005999 zero = makeSmearedConstant(zero, vectorSize);
6000 // Use OpIAdd, instead of OpBitcast to do the conversion when
6001 // generating for OpSpecConstantOp instruction.
6002 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6003 }
6004 // For normal run-time conversion instruction, use OpBitcast.
6005 convOp = spv::OpBitcast;
6006 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006007 case glslang::EOpConvUint64ToPtr:
6008 convOp = spv::OpConvertUToPtr;
6009 break;
6010 case glslang::EOpConvPtrToUint64:
6011 convOp = spv::OpConvertPtrToU;
6012 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006013 default:
6014 break;
6015 }
6016
6017 spv::Id result = 0;
6018 if (convOp == spv::OpNop)
6019 return result;
6020
6021 if (convOp == spv::OpSelect) {
6022 zero = makeSmearedConstant(zero, vectorSize);
6023 one = makeSmearedConstant(one, vectorSize);
6024 result = builder.createTriOp(convOp, destType, operand, one, zero);
6025 } else
6026 result = builder.createUnaryOp(convOp, destType, operand);
6027
John Kessenichead86222018-03-28 18:01:20 -06006028 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006029 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006030 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006031}
6032
6033spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6034{
6035 if (vectorSize == 0)
6036 return constant;
6037
6038 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6039 std::vector<spv::Id> components;
6040 for (int c = 0; c < vectorSize; ++c)
6041 components.push_back(constant);
6042 return builder.makeCompositeConstant(vectorTypeId, components);
6043}
6044
John Kessenich426394d2015-07-23 10:22:48 -06006045// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07006046spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration /*precision*/, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich426394d2015-07-23 10:22:48 -06006047{
6048 spv::Op opCode = spv::OpNop;
6049
6050 switch (op) {
6051 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006052 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006053 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006054 opCode = spv::OpAtomicIAdd;
6055 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006056 case glslang::EOpAtomicCounterSubtract:
6057 opCode = spv::OpAtomicISub;
6058 break;
John Kessenich426394d2015-07-23 10:22:48 -06006059 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006060 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006061 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006062 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006063 break;
6064 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006065 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006066 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006067 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006068 break;
6069 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006070 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006071 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006072 opCode = spv::OpAtomicAnd;
6073 break;
6074 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006075 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006076 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006077 opCode = spv::OpAtomicOr;
6078 break;
6079 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006080 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006081 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006082 opCode = spv::OpAtomicXor;
6083 break;
6084 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006085 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006086 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006087 opCode = spv::OpAtomicExchange;
6088 break;
6089 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006090 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006091 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006092 opCode = spv::OpAtomicCompareExchange;
6093 break;
6094 case glslang::EOpAtomicCounterIncrement:
6095 opCode = spv::OpAtomicIIncrement;
6096 break;
6097 case glslang::EOpAtomicCounterDecrement:
6098 opCode = spv::OpAtomicIDecrement;
6099 break;
6100 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006101 case glslang::EOpImageAtomicLoad:
6102 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006103 opCode = spv::OpAtomicLoad;
6104 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006105 case glslang::EOpAtomicStore:
6106 case glslang::EOpImageAtomicStore:
6107 opCode = spv::OpAtomicStore;
6108 break;
John Kessenich426394d2015-07-23 10:22:48 -06006109 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006110 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006111 break;
6112 }
6113
Rex Xue8fe8b02017-09-26 15:42:56 +08006114 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6115 builder.addCapability(spv::CapabilityInt64Atomics);
6116
John Kessenich426394d2015-07-23 10:22:48 -06006117 // Sort out the operands
6118 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006119 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006120 // - compare-exchange swaps the value and comparator
6121 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006122 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006123 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6124 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6125 spv::Id scopeId;
6126 if (glslangIntermediate->usingVulkanMemoryModel()) {
6127 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6128 } else {
6129 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6130 }
6131 // semantics default to relaxed
6132 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
6133 spv::Id semanticsId2 = semanticsId;
6134
6135 pointerId = operands[0];
6136 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6137 // no additional operands
6138 } else if (opCode == spv::OpAtomicCompareExchange) {
6139 compareId = operands[1];
6140 valueId = operands[2];
6141 if (operands.size() > 3) {
6142 scopeId = operands[3];
6143 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6144 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6145 }
6146 } else if (opCode == spv::OpAtomicLoad) {
6147 if (operands.size() > 1) {
6148 scopeId = operands[1];
6149 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6150 }
6151 } else {
6152 // atomic store or RMW
6153 valueId = operands[1];
6154 if (operands.size() > 2) {
6155 scopeId = operands[2];
6156 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6157 }
Rex Xu04db3f52015-09-16 11:44:02 +08006158 }
John Kessenich426394d2015-07-23 10:22:48 -06006159
Jeff Bolz36831c92018-09-05 10:11:41 -05006160 // Check for capabilities
6161 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
6162 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6163 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6164 }
John Kessenich426394d2015-07-23 10:22:48 -06006165
Jeff Bolz36831c92018-09-05 10:11:41 -05006166 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6167 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6168 }
John Kessenich48d6e792017-10-06 21:21:48 -06006169
Jeff Bolz36831c92018-09-05 10:11:41 -05006170 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6171 spvAtomicOperands.push_back(pointerId);
6172 spvAtomicOperands.push_back(scopeId);
6173 spvAtomicOperands.push_back(semanticsId);
6174 if (opCode == spv::OpAtomicCompareExchange) {
6175 spvAtomicOperands.push_back(semanticsId2);
6176 spvAtomicOperands.push_back(valueId);
6177 spvAtomicOperands.push_back(compareId);
6178 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6179 spvAtomicOperands.push_back(valueId);
6180 }
John Kessenich48d6e792017-10-06 21:21:48 -06006181
Jeff Bolz36831c92018-09-05 10:11:41 -05006182 if (opCode == spv::OpAtomicStore) {
6183 builder.createNoResultOp(opCode, spvAtomicOperands);
6184 return 0;
6185 } else {
6186 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6187
6188 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6189 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6190 if (op == glslang::EOpAtomicCounterDecrement)
6191 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6192
6193 return resultId;
6194 }
John Kessenich426394d2015-07-23 10:22:48 -06006195}
6196
John Kessenich91cef522016-05-05 16:45:40 -06006197// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006198spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006199{
Corentin Walleze7061422018-08-08 15:20:15 +02006200#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006201 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6202 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006203#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006204
Rex Xu51596642016-09-21 18:56:12 +08006205 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006206 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006207 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6208
chaocf200da82016-12-20 12:44:35 -08006209 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6210 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006211 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6212 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006213 } else if (op == glslang::EOpAnyInvocation ||
6214 op == glslang::EOpAllInvocations ||
6215 op == glslang::EOpAllInvocationsEqual) {
6216 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6217 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006218 } else {
6219 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006220#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006221 if (op == glslang::EOpMinInvocationsNonUniform ||
6222 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006223 op == glslang::EOpAddInvocationsNonUniform ||
6224 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6225 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6226 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6227 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6228 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6229 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006230 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006231#endif
Rex Xu51596642016-09-21 18:56:12 +08006232
Rex Xu9d93a232016-05-05 12:30:44 +08006233#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006234 switch (op) {
6235 case glslang::EOpMinInvocations:
6236 case glslang::EOpMaxInvocations:
6237 case glslang::EOpAddInvocations:
6238 case glslang::EOpMinInvocationsNonUniform:
6239 case glslang::EOpMaxInvocationsNonUniform:
6240 case glslang::EOpAddInvocationsNonUniform:
6241 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006242 break;
6243 case glslang::EOpMinInvocationsInclusiveScan:
6244 case glslang::EOpMaxInvocationsInclusiveScan:
6245 case glslang::EOpAddInvocationsInclusiveScan:
6246 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6247 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6248 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6249 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006250 break;
6251 case glslang::EOpMinInvocationsExclusiveScan:
6252 case glslang::EOpMaxInvocationsExclusiveScan:
6253 case glslang::EOpAddInvocationsExclusiveScan:
6254 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6255 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6256 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6257 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006258 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006259 default:
6260 break;
Rex Xu430ef402016-10-14 17:22:23 +08006261 }
John Kessenich149afc32018-08-14 13:31:43 -06006262 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6263 spvGroupOperands.push_back(scope);
6264 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006265 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006266 spvGroupOperands.push_back(groupOp);
6267 }
Rex Xu9d93a232016-05-05 12:30:44 +08006268#endif
Rex Xu51596642016-09-21 18:56:12 +08006269 }
6270
John Kessenich149afc32018-08-14 13:31:43 -06006271 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6272 spv::IdImmediate op = { true, *opIt };
6273 spvGroupOperands.push_back(op);
6274 }
John Kessenich91cef522016-05-05 16:45:40 -06006275
6276 switch (op) {
6277 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006278 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006279 break;
John Kessenich91cef522016-05-05 16:45:40 -06006280 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006281 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006282 break;
John Kessenich91cef522016-05-05 16:45:40 -06006283 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006284 opCode = spv::OpSubgroupAllEqualKHR;
6285 break;
Rex Xu51596642016-09-21 18:56:12 +08006286 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006287 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006288 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006289 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006290 break;
6291 case glslang::EOpReadFirstInvocation:
6292 opCode = spv::OpSubgroupFirstInvocationKHR;
6293 break;
6294 case glslang::EOpBallot:
6295 {
6296 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6297 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6298 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6299 //
6300 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6301 //
6302 spv::Id uintType = builder.makeUintType(32);
6303 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6304 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6305
6306 std::vector<spv::Id> components;
6307 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6308 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6309
6310 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6311 return builder.createUnaryOp(spv::OpBitcast, typeId,
6312 builder.createCompositeConstruct(uvec2Type, components));
6313 }
6314
Rex Xu9d93a232016-05-05 12:30:44 +08006315#ifdef AMD_EXTENSIONS
6316 case glslang::EOpMinInvocations:
6317 case glslang::EOpMaxInvocations:
6318 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006319 case glslang::EOpMinInvocationsInclusiveScan:
6320 case glslang::EOpMaxInvocationsInclusiveScan:
6321 case glslang::EOpAddInvocationsInclusiveScan:
6322 case glslang::EOpMinInvocationsExclusiveScan:
6323 case glslang::EOpMaxInvocationsExclusiveScan:
6324 case glslang::EOpAddInvocationsExclusiveScan:
6325 if (op == glslang::EOpMinInvocations ||
6326 op == glslang::EOpMinInvocationsInclusiveScan ||
6327 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006328 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006329 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006330 else {
6331 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006332 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006333 else
Rex Xu51596642016-09-21 18:56:12 +08006334 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006335 }
Rex Xu430ef402016-10-14 17:22:23 +08006336 } else if (op == glslang::EOpMaxInvocations ||
6337 op == glslang::EOpMaxInvocationsInclusiveScan ||
6338 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006339 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006340 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006341 else {
6342 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006343 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006344 else
Rex Xu51596642016-09-21 18:56:12 +08006345 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006346 }
6347 } else {
6348 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006349 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006350 else
Rex Xu51596642016-09-21 18:56:12 +08006351 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006352 }
6353
Rex Xu2bbbe062016-08-23 15:41:05 +08006354 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006355 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006356
6357 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006358 case glslang::EOpMinInvocationsNonUniform:
6359 case glslang::EOpMaxInvocationsNonUniform:
6360 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006361 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6362 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6363 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6364 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6365 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6366 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6367 if (op == glslang::EOpMinInvocationsNonUniform ||
6368 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6369 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006370 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006371 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006372 else {
6373 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006374 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006375 else
Rex Xu51596642016-09-21 18:56:12 +08006376 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006377 }
6378 }
Rex Xu430ef402016-10-14 17:22:23 +08006379 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6380 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6381 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006382 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006383 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006384 else {
6385 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006386 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006387 else
Rex Xu51596642016-09-21 18:56:12 +08006388 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006389 }
6390 }
6391 else {
6392 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006393 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006394 else
Rex Xu51596642016-09-21 18:56:12 +08006395 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006396 }
6397
Rex Xu2bbbe062016-08-23 15:41:05 +08006398 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006399 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006400
6401 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006402#endif
John Kessenich91cef522016-05-05 16:45:40 -06006403 default:
6404 logger->missingFunctionality("invocation operation");
6405 return spv::NoResult;
6406 }
Rex Xu51596642016-09-21 18:56:12 +08006407
6408 assert(opCode != spv::OpNop);
6409 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006410}
6411
Rex Xu2bbbe062016-08-23 15:41:05 +08006412// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006413spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6414 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006415{
Rex Xub7072052016-09-26 15:53:40 +08006416#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006417 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6418 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006419 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006420 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006421 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6422 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6423 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006424#else
6425 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6426 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006427 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6428 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006429#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006430
6431 // Handle group invocation operations scalar by scalar.
6432 // The result type is the same type as the original type.
6433 // The algorithm is to:
6434 // - break the vector into scalars
6435 // - apply the operation to each scalar
6436 // - make a vector out the scalar results
6437
6438 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006439 int numComponents = builder.getNumComponents(operands[0]);
6440 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006441 std::vector<spv::Id> results;
6442
6443 // do each scalar op
6444 for (int comp = 0; comp < numComponents; ++comp) {
6445 std::vector<unsigned int> indexes;
6446 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006447 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6448 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006449 if (op == spv::OpSubgroupReadInvocationKHR) {
6450 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006451 spv::IdImmediate operand = { true, operands[1] };
6452 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006453 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006454 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6455 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006456 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006457 spv::IdImmediate operand = { true, operands[1] };
6458 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006459 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006460 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6461 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006462 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006463 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006464 spvGroupOperands.push_back(scalar);
6465 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006466
Rex Xub7072052016-09-26 15:53:40 +08006467 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006468 }
6469
6470 // put the pieces together
6471 return builder.createCompositeConstruct(typeId, results);
6472}
Rex Xu2bbbe062016-08-23 15:41:05 +08006473
John Kessenich66011cb2018-03-06 16:12:04 -07006474// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006475spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6476 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006477{
6478 // Add the required capabilities.
6479 switch (op) {
6480 case glslang::EOpSubgroupElect:
6481 builder.addCapability(spv::CapabilityGroupNonUniform);
6482 break;
6483 case glslang::EOpSubgroupAll:
6484 case glslang::EOpSubgroupAny:
6485 case glslang::EOpSubgroupAllEqual:
6486 builder.addCapability(spv::CapabilityGroupNonUniform);
6487 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6488 break;
6489 case glslang::EOpSubgroupBroadcast:
6490 case glslang::EOpSubgroupBroadcastFirst:
6491 case glslang::EOpSubgroupBallot:
6492 case glslang::EOpSubgroupInverseBallot:
6493 case glslang::EOpSubgroupBallotBitExtract:
6494 case glslang::EOpSubgroupBallotBitCount:
6495 case glslang::EOpSubgroupBallotInclusiveBitCount:
6496 case glslang::EOpSubgroupBallotExclusiveBitCount:
6497 case glslang::EOpSubgroupBallotFindLSB:
6498 case glslang::EOpSubgroupBallotFindMSB:
6499 builder.addCapability(spv::CapabilityGroupNonUniform);
6500 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6501 break;
6502 case glslang::EOpSubgroupShuffle:
6503 case glslang::EOpSubgroupShuffleXor:
6504 builder.addCapability(spv::CapabilityGroupNonUniform);
6505 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6506 break;
6507 case glslang::EOpSubgroupShuffleUp:
6508 case glslang::EOpSubgroupShuffleDown:
6509 builder.addCapability(spv::CapabilityGroupNonUniform);
6510 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6511 break;
6512 case glslang::EOpSubgroupAdd:
6513 case glslang::EOpSubgroupMul:
6514 case glslang::EOpSubgroupMin:
6515 case glslang::EOpSubgroupMax:
6516 case glslang::EOpSubgroupAnd:
6517 case glslang::EOpSubgroupOr:
6518 case glslang::EOpSubgroupXor:
6519 case glslang::EOpSubgroupInclusiveAdd:
6520 case glslang::EOpSubgroupInclusiveMul:
6521 case glslang::EOpSubgroupInclusiveMin:
6522 case glslang::EOpSubgroupInclusiveMax:
6523 case glslang::EOpSubgroupInclusiveAnd:
6524 case glslang::EOpSubgroupInclusiveOr:
6525 case glslang::EOpSubgroupInclusiveXor:
6526 case glslang::EOpSubgroupExclusiveAdd:
6527 case glslang::EOpSubgroupExclusiveMul:
6528 case glslang::EOpSubgroupExclusiveMin:
6529 case glslang::EOpSubgroupExclusiveMax:
6530 case glslang::EOpSubgroupExclusiveAnd:
6531 case glslang::EOpSubgroupExclusiveOr:
6532 case glslang::EOpSubgroupExclusiveXor:
6533 builder.addCapability(spv::CapabilityGroupNonUniform);
6534 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6535 break;
6536 case glslang::EOpSubgroupClusteredAdd:
6537 case glslang::EOpSubgroupClusteredMul:
6538 case glslang::EOpSubgroupClusteredMin:
6539 case glslang::EOpSubgroupClusteredMax:
6540 case glslang::EOpSubgroupClusteredAnd:
6541 case glslang::EOpSubgroupClusteredOr:
6542 case glslang::EOpSubgroupClusteredXor:
6543 builder.addCapability(spv::CapabilityGroupNonUniform);
6544 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6545 break;
6546 case glslang::EOpSubgroupQuadBroadcast:
6547 case glslang::EOpSubgroupQuadSwapHorizontal:
6548 case glslang::EOpSubgroupQuadSwapVertical:
6549 case glslang::EOpSubgroupQuadSwapDiagonal:
6550 builder.addCapability(spv::CapabilityGroupNonUniform);
6551 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6552 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006553#ifdef NV_EXTENSIONS
6554 case glslang::EOpSubgroupPartitionedAdd:
6555 case glslang::EOpSubgroupPartitionedMul:
6556 case glslang::EOpSubgroupPartitionedMin:
6557 case glslang::EOpSubgroupPartitionedMax:
6558 case glslang::EOpSubgroupPartitionedAnd:
6559 case glslang::EOpSubgroupPartitionedOr:
6560 case glslang::EOpSubgroupPartitionedXor:
6561 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6562 case glslang::EOpSubgroupPartitionedInclusiveMul:
6563 case glslang::EOpSubgroupPartitionedInclusiveMin:
6564 case glslang::EOpSubgroupPartitionedInclusiveMax:
6565 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6566 case glslang::EOpSubgroupPartitionedInclusiveOr:
6567 case glslang::EOpSubgroupPartitionedInclusiveXor:
6568 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6569 case glslang::EOpSubgroupPartitionedExclusiveMul:
6570 case glslang::EOpSubgroupPartitionedExclusiveMin:
6571 case glslang::EOpSubgroupPartitionedExclusiveMax:
6572 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6573 case glslang::EOpSubgroupPartitionedExclusiveOr:
6574 case glslang::EOpSubgroupPartitionedExclusiveXor:
6575 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6576 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6577 break;
6578#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006579 default: assert(0 && "Unhandled subgroup operation!");
6580 }
6581
6582 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6583 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6584 const bool isBool = typeProxy == glslang::EbtBool;
6585
6586 spv::Op opCode = spv::OpNop;
6587
6588 // Figure out which opcode to use.
6589 switch (op) {
6590 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6591 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6592 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6593 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6594 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6595 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6596 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6597 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6598 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6599 case glslang::EOpSubgroupBallotBitCount:
6600 case glslang::EOpSubgroupBallotInclusiveBitCount:
6601 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6602 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6603 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6604 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6605 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6606 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6607 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6608 case glslang::EOpSubgroupAdd:
6609 case glslang::EOpSubgroupInclusiveAdd:
6610 case glslang::EOpSubgroupExclusiveAdd:
6611 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006612#ifdef NV_EXTENSIONS
6613 case glslang::EOpSubgroupPartitionedAdd:
6614 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6615 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6616#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006617 if (isFloat) {
6618 opCode = spv::OpGroupNonUniformFAdd;
6619 } else {
6620 opCode = spv::OpGroupNonUniformIAdd;
6621 }
6622 break;
6623 case glslang::EOpSubgroupMul:
6624 case glslang::EOpSubgroupInclusiveMul:
6625 case glslang::EOpSubgroupExclusiveMul:
6626 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006627#ifdef NV_EXTENSIONS
6628 case glslang::EOpSubgroupPartitionedMul:
6629 case glslang::EOpSubgroupPartitionedInclusiveMul:
6630 case glslang::EOpSubgroupPartitionedExclusiveMul:
6631#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006632 if (isFloat) {
6633 opCode = spv::OpGroupNonUniformFMul;
6634 } else {
6635 opCode = spv::OpGroupNonUniformIMul;
6636 }
6637 break;
6638 case glslang::EOpSubgroupMin:
6639 case glslang::EOpSubgroupInclusiveMin:
6640 case glslang::EOpSubgroupExclusiveMin:
6641 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006642#ifdef NV_EXTENSIONS
6643 case glslang::EOpSubgroupPartitionedMin:
6644 case glslang::EOpSubgroupPartitionedInclusiveMin:
6645 case glslang::EOpSubgroupPartitionedExclusiveMin:
6646#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006647 if (isFloat) {
6648 opCode = spv::OpGroupNonUniformFMin;
6649 } else if (isUnsigned) {
6650 opCode = spv::OpGroupNonUniformUMin;
6651 } else {
6652 opCode = spv::OpGroupNonUniformSMin;
6653 }
6654 break;
6655 case glslang::EOpSubgroupMax:
6656 case glslang::EOpSubgroupInclusiveMax:
6657 case glslang::EOpSubgroupExclusiveMax:
6658 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006659#ifdef NV_EXTENSIONS
6660 case glslang::EOpSubgroupPartitionedMax:
6661 case glslang::EOpSubgroupPartitionedInclusiveMax:
6662 case glslang::EOpSubgroupPartitionedExclusiveMax:
6663#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006664 if (isFloat) {
6665 opCode = spv::OpGroupNonUniformFMax;
6666 } else if (isUnsigned) {
6667 opCode = spv::OpGroupNonUniformUMax;
6668 } else {
6669 opCode = spv::OpGroupNonUniformSMax;
6670 }
6671 break;
6672 case glslang::EOpSubgroupAnd:
6673 case glslang::EOpSubgroupInclusiveAnd:
6674 case glslang::EOpSubgroupExclusiveAnd:
6675 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006676#ifdef NV_EXTENSIONS
6677 case glslang::EOpSubgroupPartitionedAnd:
6678 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6679 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6680#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006681 if (isBool) {
6682 opCode = spv::OpGroupNonUniformLogicalAnd;
6683 } else {
6684 opCode = spv::OpGroupNonUniformBitwiseAnd;
6685 }
6686 break;
6687 case glslang::EOpSubgroupOr:
6688 case glslang::EOpSubgroupInclusiveOr:
6689 case glslang::EOpSubgroupExclusiveOr:
6690 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006691#ifdef NV_EXTENSIONS
6692 case glslang::EOpSubgroupPartitionedOr:
6693 case glslang::EOpSubgroupPartitionedInclusiveOr:
6694 case glslang::EOpSubgroupPartitionedExclusiveOr:
6695#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006696 if (isBool) {
6697 opCode = spv::OpGroupNonUniformLogicalOr;
6698 } else {
6699 opCode = spv::OpGroupNonUniformBitwiseOr;
6700 }
6701 break;
6702 case glslang::EOpSubgroupXor:
6703 case glslang::EOpSubgroupInclusiveXor:
6704 case glslang::EOpSubgroupExclusiveXor:
6705 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006706#ifdef NV_EXTENSIONS
6707 case glslang::EOpSubgroupPartitionedXor:
6708 case glslang::EOpSubgroupPartitionedInclusiveXor:
6709 case glslang::EOpSubgroupPartitionedExclusiveXor:
6710#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006711 if (isBool) {
6712 opCode = spv::OpGroupNonUniformLogicalXor;
6713 } else {
6714 opCode = spv::OpGroupNonUniformBitwiseXor;
6715 }
6716 break;
6717 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6718 case glslang::EOpSubgroupQuadSwapHorizontal:
6719 case glslang::EOpSubgroupQuadSwapVertical:
6720 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6721 default: assert(0 && "Unhandled subgroup operation!");
6722 }
6723
John Kessenich149afc32018-08-14 13:31:43 -06006724 // get the right Group Operation
6725 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006726 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006727 default:
6728 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006729 case glslang::EOpSubgroupBallotBitCount:
6730 case glslang::EOpSubgroupAdd:
6731 case glslang::EOpSubgroupMul:
6732 case glslang::EOpSubgroupMin:
6733 case glslang::EOpSubgroupMax:
6734 case glslang::EOpSubgroupAnd:
6735 case glslang::EOpSubgroupOr:
6736 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006737 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006738 break;
6739 case glslang::EOpSubgroupBallotInclusiveBitCount:
6740 case glslang::EOpSubgroupInclusiveAdd:
6741 case glslang::EOpSubgroupInclusiveMul:
6742 case glslang::EOpSubgroupInclusiveMin:
6743 case glslang::EOpSubgroupInclusiveMax:
6744 case glslang::EOpSubgroupInclusiveAnd:
6745 case glslang::EOpSubgroupInclusiveOr:
6746 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006747 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006748 break;
6749 case glslang::EOpSubgroupBallotExclusiveBitCount:
6750 case glslang::EOpSubgroupExclusiveAdd:
6751 case glslang::EOpSubgroupExclusiveMul:
6752 case glslang::EOpSubgroupExclusiveMin:
6753 case glslang::EOpSubgroupExclusiveMax:
6754 case glslang::EOpSubgroupExclusiveAnd:
6755 case glslang::EOpSubgroupExclusiveOr:
6756 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006757 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006758 break;
6759 case glslang::EOpSubgroupClusteredAdd:
6760 case glslang::EOpSubgroupClusteredMul:
6761 case glslang::EOpSubgroupClusteredMin:
6762 case glslang::EOpSubgroupClusteredMax:
6763 case glslang::EOpSubgroupClusteredAnd:
6764 case glslang::EOpSubgroupClusteredOr:
6765 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006766 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006767 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006768#ifdef NV_EXTENSIONS
6769 case glslang::EOpSubgroupPartitionedAdd:
6770 case glslang::EOpSubgroupPartitionedMul:
6771 case glslang::EOpSubgroupPartitionedMin:
6772 case glslang::EOpSubgroupPartitionedMax:
6773 case glslang::EOpSubgroupPartitionedAnd:
6774 case glslang::EOpSubgroupPartitionedOr:
6775 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006776 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006777 break;
6778 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6779 case glslang::EOpSubgroupPartitionedInclusiveMul:
6780 case glslang::EOpSubgroupPartitionedInclusiveMin:
6781 case glslang::EOpSubgroupPartitionedInclusiveMax:
6782 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6783 case glslang::EOpSubgroupPartitionedInclusiveOr:
6784 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006785 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006786 break;
6787 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6788 case glslang::EOpSubgroupPartitionedExclusiveMul:
6789 case glslang::EOpSubgroupPartitionedExclusiveMin:
6790 case glslang::EOpSubgroupPartitionedExclusiveMax:
6791 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6792 case glslang::EOpSubgroupPartitionedExclusiveOr:
6793 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006794 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006795 break;
6796#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006797 }
6798
John Kessenich149afc32018-08-14 13:31:43 -06006799 // build the instruction
6800 std::vector<spv::IdImmediate> spvGroupOperands;
6801
6802 // Every operation begins with the Execution Scope operand.
6803 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6804 spvGroupOperands.push_back(executionScope);
6805
6806 // Next, for all operations that use a Group Operation, push that as an operand.
6807 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006808 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006809 spvGroupOperands.push_back(groupOperand);
6810 }
6811
John Kessenich66011cb2018-03-06 16:12:04 -07006812 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006813 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6814 spv::IdImmediate operand = { true, *opIt };
6815 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006816 }
6817
6818 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006819 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006820 switch (op) {
6821 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006822 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6823 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6824 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6825 }
6826 if (directionId != spv::NoResult) {
6827 spv::IdImmediate direction = { true, directionId };
6828 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006829 }
6830
6831 return builder.createOp(opCode, typeId, spvGroupOperands);
6832}
6833
John Kessenich5e4b1242015-08-06 22:53:06 -06006834spv::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 -06006835{
John Kessenich66011cb2018-03-06 16:12:04 -07006836 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6837 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006838
John Kessenich140f3df2015-06-26 16:58:36 -06006839 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006840 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006841 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006842 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006843 spv::Id typeId0 = 0;
6844 if (consumedOperands > 0)
6845 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006846 spv::Id typeId1 = 0;
6847 if (consumedOperands > 1)
6848 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006849 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006850
6851 switch (op) {
6852 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006853 if (isFloat)
6854 libCall = spv::GLSLstd450FMin;
6855 else if (isUnsigned)
6856 libCall = spv::GLSLstd450UMin;
6857 else
6858 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006859 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006860 break;
6861 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006862 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006863 break;
6864 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006865 if (isFloat)
6866 libCall = spv::GLSLstd450FMax;
6867 else if (isUnsigned)
6868 libCall = spv::GLSLstd450UMax;
6869 else
6870 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006871 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006872 break;
6873 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006874 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006875 break;
6876 case glslang::EOpDot:
6877 opCode = spv::OpDot;
6878 break;
6879 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006880 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006881 break;
6882
6883 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006884 if (isFloat)
6885 libCall = spv::GLSLstd450FClamp;
6886 else if (isUnsigned)
6887 libCall = spv::GLSLstd450UClamp;
6888 else
6889 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006890 builder.promoteScalar(precision, operands.front(), operands[1]);
6891 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006892 break;
6893 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006894 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6895 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006896 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006897 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006898 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006899 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006900 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006901 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006902 break;
6903 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006904 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006905 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006906 break;
6907 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006908 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006909 builder.promoteScalar(precision, operands[0], operands[2]);
6910 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006911 break;
6912
6913 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006914 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006915 break;
6916 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006917 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006918 break;
6919 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006920 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006921 break;
6922 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006923 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006924 break;
6925 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006926 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006927 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006928 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006929#ifdef AMD_EXTENSIONS
6930 if (typeProxy == glslang::EbtFloat16)
6931 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6932#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006933 libCall = spv::GLSLstd450InterpolateAtSample;
6934 break;
6935 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006936#ifdef AMD_EXTENSIONS
6937 if (typeProxy == glslang::EbtFloat16)
6938 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6939#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006940 libCall = spv::GLSLstd450InterpolateAtOffset;
6941 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006942 case glslang::EOpAddCarry:
6943 opCode = spv::OpIAddCarry;
6944 typeId = builder.makeStructResultType(typeId0, typeId0);
6945 consumedOperands = 2;
6946 break;
6947 case glslang::EOpSubBorrow:
6948 opCode = spv::OpISubBorrow;
6949 typeId = builder.makeStructResultType(typeId0, typeId0);
6950 consumedOperands = 2;
6951 break;
6952 case glslang::EOpUMulExtended:
6953 opCode = spv::OpUMulExtended;
6954 typeId = builder.makeStructResultType(typeId0, typeId0);
6955 consumedOperands = 2;
6956 break;
6957 case glslang::EOpIMulExtended:
6958 opCode = spv::OpSMulExtended;
6959 typeId = builder.makeStructResultType(typeId0, typeId0);
6960 consumedOperands = 2;
6961 break;
6962 case glslang::EOpBitfieldExtract:
6963 if (isUnsigned)
6964 opCode = spv::OpBitFieldUExtract;
6965 else
6966 opCode = spv::OpBitFieldSExtract;
6967 break;
6968 case glslang::EOpBitfieldInsert:
6969 opCode = spv::OpBitFieldInsert;
6970 break;
6971
6972 case glslang::EOpFma:
6973 libCall = spv::GLSLstd450Fma;
6974 break;
6975 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006976 {
6977 libCall = spv::GLSLstd450FrexpStruct;
6978 assert(builder.isPointerType(typeId1));
6979 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006980 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006981#ifdef AMD_EXTENSIONS
6982 if (width == 16)
6983 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6984 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6985#endif
Rex Xu470026f2017-03-29 17:12:40 +08006986 if (builder.getNumComponents(operands[0]) == 1)
6987 frexpIntType = builder.makeIntegerType(width, true);
6988 else
6989 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6990 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6991 consumedOperands = 1;
6992 }
John Kessenich55e7d112015-11-15 21:33:39 -07006993 break;
6994 case glslang::EOpLdexp:
6995 libCall = spv::GLSLstd450Ldexp;
6996 break;
6997
Rex Xu574ab042016-04-14 16:53:07 +08006998 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006999 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007000
John Kessenich66011cb2018-03-06 16:12:04 -07007001 case glslang::EOpSubgroupBroadcast:
7002 case glslang::EOpSubgroupBallotBitExtract:
7003 case glslang::EOpSubgroupShuffle:
7004 case glslang::EOpSubgroupShuffleXor:
7005 case glslang::EOpSubgroupShuffleUp:
7006 case glslang::EOpSubgroupShuffleDown:
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:
7014 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007015#ifdef NV_EXTENSIONS
7016 case glslang::EOpSubgroupPartitionedAdd:
7017 case glslang::EOpSubgroupPartitionedMul:
7018 case glslang::EOpSubgroupPartitionedMin:
7019 case glslang::EOpSubgroupPartitionedMax:
7020 case glslang::EOpSubgroupPartitionedAnd:
7021 case glslang::EOpSubgroupPartitionedOr:
7022 case glslang::EOpSubgroupPartitionedXor:
7023 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7024 case glslang::EOpSubgroupPartitionedInclusiveMul:
7025 case glslang::EOpSubgroupPartitionedInclusiveMin:
7026 case glslang::EOpSubgroupPartitionedInclusiveMax:
7027 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7028 case glslang::EOpSubgroupPartitionedInclusiveOr:
7029 case glslang::EOpSubgroupPartitionedInclusiveXor:
7030 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7031 case glslang::EOpSubgroupPartitionedExclusiveMul:
7032 case glslang::EOpSubgroupPartitionedExclusiveMin:
7033 case glslang::EOpSubgroupPartitionedExclusiveMax:
7034 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7035 case glslang::EOpSubgroupPartitionedExclusiveOr:
7036 case glslang::EOpSubgroupPartitionedExclusiveXor:
7037#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007038 return createSubgroupOperation(op, typeId, operands, typeProxy);
7039
Rex Xu9d93a232016-05-05 12:30:44 +08007040#ifdef AMD_EXTENSIONS
7041 case glslang::EOpSwizzleInvocations:
7042 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7043 libCall = spv::SwizzleInvocationsAMD;
7044 break;
7045 case glslang::EOpSwizzleInvocationsMasked:
7046 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7047 libCall = spv::SwizzleInvocationsMaskedAMD;
7048 break;
7049 case glslang::EOpWriteInvocation:
7050 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7051 libCall = spv::WriteInvocationAMD;
7052 break;
7053
7054 case glslang::EOpMin3:
7055 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7056 if (isFloat)
7057 libCall = spv::FMin3AMD;
7058 else {
7059 if (isUnsigned)
7060 libCall = spv::UMin3AMD;
7061 else
7062 libCall = spv::SMin3AMD;
7063 }
7064 break;
7065 case glslang::EOpMax3:
7066 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7067 if (isFloat)
7068 libCall = spv::FMax3AMD;
7069 else {
7070 if (isUnsigned)
7071 libCall = spv::UMax3AMD;
7072 else
7073 libCall = spv::SMax3AMD;
7074 }
7075 break;
7076 case glslang::EOpMid3:
7077 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7078 if (isFloat)
7079 libCall = spv::FMid3AMD;
7080 else {
7081 if (isUnsigned)
7082 libCall = spv::UMid3AMD;
7083 else
7084 libCall = spv::SMid3AMD;
7085 }
7086 break;
7087
7088 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007089 if (typeProxy == glslang::EbtFloat16)
7090 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007091 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7092 libCall = spv::InterpolateAtVertexAMD;
7093 break;
7094#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007095 case glslang::EOpBarrier:
7096 {
7097 // This is for the extended controlBarrier function, with four operands.
7098 // The unextended barrier() goes through createNoArgOperation.
7099 assert(operands.size() == 4);
7100 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7101 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7102 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7103 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7104 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7105 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7106 }
7107 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7108 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7109 }
7110 return 0;
7111 }
7112 break;
7113 case glslang::EOpMemoryBarrier:
7114 {
7115 // This is for the extended memoryBarrier function, with three operands.
7116 // The unextended memoryBarrier() goes through createNoArgOperation.
7117 assert(operands.size() == 3);
7118 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7119 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7120 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7121 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7122 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7123 }
7124 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7125 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7126 }
7127 return 0;
7128 }
7129 break;
Chao Chen3c366992018-09-19 11:41:59 -07007130
7131#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007132 case glslang::EOpReportIntersectionNV:
7133 {
7134 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007135 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007136 }
7137 break;
7138 case glslang::EOpTraceNV:
7139 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007140 builder.createNoResultOp(spv::OpTraceNV, operands);
7141 return 0;
7142 }
7143 break;
7144 case glslang::EOpExecuteCallableNV:
7145 {
7146 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007147 return 0;
7148 }
7149 break;
Chao Chen3c366992018-09-19 11:41:59 -07007150 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7151 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7152 return 0;
7153#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007154 case glslang::EOpCooperativeMatrixMulAdd:
7155 opCode = spv::OpCooperativeMatrixMulAddNV;
7156 break;
7157
John Kessenich140f3df2015-06-26 16:58:36 -06007158 default:
7159 return 0;
7160 }
7161
7162 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007163 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007164 // Use an extended instruction from the standard library.
7165 // Construct the call arguments, without modifying the original operands vector.
7166 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7167 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007168 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007169 } else if (opCode == spv::OpDot && !isFloat) {
7170 // int dot(int, int)
7171 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7172 const int componentCount = builder.getNumComponents(operands[0]);
7173 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7174 builder.setPrecision(mulOp, precision);
7175 id = builder.createCompositeExtract(mulOp, typeId, 0);
7176 for (int i = 1; i < componentCount; ++i) {
7177 builder.setPrecision(id, precision);
7178 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7179 }
John Kessenich2359bd02015-12-06 19:29:11 -07007180 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007181 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007182 case 0:
7183 // should all be handled by visitAggregate and createNoArgOperation
7184 assert(0);
7185 return 0;
7186 case 1:
7187 // should all be handled by createUnaryOperation
7188 assert(0);
7189 return 0;
7190 case 2:
7191 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7192 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007193 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007194 // anything 3 or over doesn't have l-value operands, so all should be consumed
7195 assert(consumedOperands == operands.size());
7196 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007197 break;
7198 }
7199 }
7200
John Kessenich55e7d112015-11-15 21:33:39 -07007201 // Decode the return types that were structures
7202 switch (op) {
7203 case glslang::EOpAddCarry:
7204 case glslang::EOpSubBorrow:
7205 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7206 id = builder.createCompositeExtract(id, typeId0, 0);
7207 break;
7208 case glslang::EOpUMulExtended:
7209 case glslang::EOpIMulExtended:
7210 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7211 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7212 break;
7213 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007214 {
7215 assert(operands.size() == 2);
7216 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7217 // "exp" is floating-point type (from HLSL intrinsic)
7218 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7219 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7220 builder.createStore(member1, operands[1]);
7221 } else
7222 // "exp" is integer type (from GLSL built-in function)
7223 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7224 id = builder.createCompositeExtract(id, typeId0, 0);
7225 }
John Kessenich55e7d112015-11-15 21:33:39 -07007226 break;
7227 default:
7228 break;
7229 }
7230
John Kessenich32cfd492016-02-02 12:37:46 -07007231 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007232}
7233
Rex Xu9d93a232016-05-05 12:30:44 +08007234// Intrinsics with no arguments (or no return value, and no precision).
7235spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007236{
Jeff Bolz36831c92018-09-05 10:11:41 -05007237 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7238 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007239
7240 switch (op) {
7241 case glslang::EOpEmitVertex:
7242 builder.createNoResultOp(spv::OpEmitVertex);
7243 return 0;
7244 case glslang::EOpEndPrimitive:
7245 builder.createNoResultOp(spv::OpEndPrimitive);
7246 return 0;
7247 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007248 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007249 if (glslangIntermediate->usingVulkanMemoryModel()) {
7250 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7251 spv::MemorySemanticsOutputMemoryKHRMask |
7252 spv::MemorySemanticsAcquireReleaseMask);
7253 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7254 } else {
7255 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7256 }
John Kessenich82979362017-12-11 04:02:24 -07007257 } else {
7258 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7259 spv::MemorySemanticsWorkgroupMemoryMask |
7260 spv::MemorySemanticsAcquireReleaseMask);
7261 }
John Kessenich140f3df2015-06-26 16:58:36 -06007262 return 0;
7263 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007264 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7265 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007266 return 0;
7267 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007268 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7269 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007270 return 0;
7271 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007272 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7273 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007274 return 0;
7275 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007276 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7277 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007278 return 0;
7279 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007280 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7281 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007282 return 0;
7283 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007284 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7285 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007286 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007287 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007288 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007289 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007290 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007291 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007292 case glslang::EOpDeviceMemoryBarrier:
7293 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7294 spv::MemorySemanticsImageMemoryMask |
7295 spv::MemorySemanticsAcquireReleaseMask);
7296 return 0;
7297 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7298 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7299 spv::MemorySemanticsImageMemoryMask |
7300 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007301 return 0;
7302 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007303 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7304 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007305 return 0;
7306 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007307 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7308 spv::MemorySemanticsWorkgroupMemoryMask |
7309 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007310 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007311 case glslang::EOpSubgroupBarrier:
7312 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7313 spv::MemorySemanticsAcquireReleaseMask);
7314 return spv::NoResult;
7315 case glslang::EOpSubgroupMemoryBarrier:
7316 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7317 spv::MemorySemanticsAcquireReleaseMask);
7318 return spv::NoResult;
7319 case glslang::EOpSubgroupMemoryBarrierBuffer:
7320 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7321 spv::MemorySemanticsAcquireReleaseMask);
7322 return spv::NoResult;
7323 case glslang::EOpSubgroupMemoryBarrierImage:
7324 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7325 spv::MemorySemanticsAcquireReleaseMask);
7326 return spv::NoResult;
7327 case glslang::EOpSubgroupMemoryBarrierShared:
7328 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7329 spv::MemorySemanticsAcquireReleaseMask);
7330 return spv::NoResult;
7331 case glslang::EOpSubgroupElect: {
7332 std::vector<spv::Id> operands;
7333 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7334 }
Rex Xu9d93a232016-05-05 12:30:44 +08007335#ifdef AMD_EXTENSIONS
7336 case glslang::EOpTime:
7337 {
7338 std::vector<spv::Id> args; // Dummy arguments
7339 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7340 return builder.setPrecision(id, precision);
7341 }
7342#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007343#ifdef NV_EXTENSIONS
7344 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007345 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007346 return 0;
7347 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007348 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007349 return 0;
7350#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007351 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007352 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007353 return 0;
7354 }
7355}
7356
7357spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7358{
John Kessenich2f273362015-07-18 22:34:27 -06007359 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007360 spv::Id id;
7361 if (symbolValues.end() != iter) {
7362 id = iter->second;
7363 return id;
7364 }
7365
7366 // it was not found, create it
7367 id = createSpvVariable(symbol);
7368 symbolValues[symbol->getId()] = id;
7369
Rex Xuc884b4a2016-06-29 15:03:44 +08007370 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007371 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7372 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7373 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007374#ifdef NV_EXTENSIONS
7375 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7376#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007377 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007378 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007379 if (symbol->getQualifier().hasIndex())
7380 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7381 if (symbol->getQualifier().hasComponent())
7382 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007383 // atomic counters use this:
7384 if (symbol->getQualifier().hasOffset())
7385 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007386 }
7387
scygan2c864272016-05-18 18:09:17 +02007388 if (symbol->getQualifier().hasLocation())
7389 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007390 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007391 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007392 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007393 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007394 }
John Kessenich140f3df2015-06-26 16:58:36 -06007395 if (symbol->getQualifier().hasSet())
7396 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007397 else if (IsDescriptorResource(symbol->getType())) {
7398 // default to 0
7399 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7400 }
John Kessenich140f3df2015-06-26 16:58:36 -06007401 if (symbol->getQualifier().hasBinding())
7402 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007403 else if (IsDescriptorResource(symbol->getType())) {
7404 // default to 0
7405 builder.addDecoration(id, spv::DecorationBinding, 0);
7406 }
John Kessenich6c292d32016-02-15 20:58:50 -07007407 if (symbol->getQualifier().hasAttachment())
7408 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007409 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007410 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007411 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007412 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007413 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7414 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7415 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7416 }
7417 if (symbol->getQualifier().hasXfbOffset())
7418 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007419 }
7420
Rex Xu1da878f2016-02-21 20:59:01 +08007421 if (symbol->getType().isImage()) {
7422 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007423 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007424 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007425 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007426 }
7427
John Kessenich140f3df2015-06-26 16:58:36 -06007428 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007429 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007430 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007431 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007432
John Kessenich5611c6d2018-04-05 11:25:02 -06007433 // nonuniform
7434 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7435
John Kessenichecba76f2017-01-06 00:34:48 -07007436#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007437 if (builtIn == spv::BuiltInSampleMask) {
7438 spv::Decoration decoration;
7439 // GL_NV_sample_mask_override_coverage extension
7440 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007441 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007442 else
7443 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007444 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007445 if (decoration != spv::DecorationMax) {
7446 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7447 }
7448 }
chaoc771d89f2017-01-13 01:10:53 -08007449 else if (builtIn == spv::BuiltInLayer) {
7450 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007451 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007452 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007453 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7454 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7455 }
John Kessenichb41bff62017-08-11 13:07:17 -06007456 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007457 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7458 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007459 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7460 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7461 }
7462 }
7463
chaoc6e5acae2016-12-20 13:28:52 -08007464 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007465 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007466 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007467 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7468 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007469 if (symbol->getQualifier().pervertexNV) {
7470 builder.addDecoration(id, spv::DecorationPerVertexNV);
7471 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7472 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7473 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007474#endif
7475
John Kessenich5d610ee2018-03-07 18:05:55 -07007476 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7477 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7478 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7479 symbol->getType().getQualifier().semanticName);
7480 }
7481
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007482 if (symbol->getBasicType() == glslang::EbtReference) {
7483 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7484 }
7485
John Kessenich140f3df2015-06-26 16:58:36 -06007486 return id;
7487}
7488
Chao Chen3c366992018-09-19 11:41:59 -07007489#ifdef NV_EXTENSIONS
7490// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7491void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7492{
7493 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007494 if (qualifier.perPrimitiveNV) {
7495 // Need to add capability/extension for fragment shader.
7496 // Mesh shader already adds this by default.
7497 if (glslangIntermediate->getStage() == EShLangFragment) {
7498 builder.addCapability(spv::CapabilityMeshShadingNV);
7499 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7500 }
Chao Chen3c366992018-09-19 11:41:59 -07007501 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007502 }
Chao Chen3c366992018-09-19 11:41:59 -07007503 if (qualifier.perViewNV)
7504 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7505 if (qualifier.perTaskNV)
7506 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7507 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007508 if (qualifier.perPrimitiveNV) {
7509 // Need to add capability/extension for fragment shader.
7510 // Mesh shader already adds this by default.
7511 if (glslangIntermediate->getStage() == EShLangFragment) {
7512 builder.addCapability(spv::CapabilityMeshShadingNV);
7513 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7514 }
Chao Chen3c366992018-09-19 11:41:59 -07007515 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007516 }
Chao Chen3c366992018-09-19 11:41:59 -07007517 if (qualifier.perViewNV)
7518 builder.addDecoration(id, spv::DecorationPerViewNV);
7519 if (qualifier.perTaskNV)
7520 builder.addDecoration(id, spv::DecorationPerTaskNV);
7521 }
7522}
7523#endif
7524
John Kessenich55e7d112015-11-15 21:33:39 -07007525// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007526// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007527//
7528// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7529//
7530// Recursively walk the nodes. The nodes form a tree whose leaves are
7531// regular constants, which themselves are trees that createSpvConstant()
7532// recursively walks. So, this function walks the "top" of the tree:
7533// - emit specialization constant-building instructions for specConstant
7534// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007535spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007536{
John Kessenich7cc0e282016-03-20 00:46:02 -06007537 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007538
qining4f4bb812016-04-03 23:55:17 -04007539 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007540 if (! node.getQualifier().specConstant) {
7541 // hand off to the non-spec-constant path
7542 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7543 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007544 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007545 nextConst, false);
7546 }
7547
7548 // We now know we have a specialization constant to build
7549
John Kessenichd94c0032016-05-30 19:29:40 -06007550 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007551 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7552 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7553 std::vector<spv::Id> dimConstId;
7554 for (int dim = 0; dim < 3; ++dim) {
7555 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7556 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007557 if (specConst) {
7558 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7559 glslangIntermediate->getLocalSizeSpecId(dim));
7560 }
qining4f4bb812016-04-03 23:55:17 -04007561 }
7562 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7563 }
7564
7565 // An AST node labelled as specialization constant should be a symbol node.
7566 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7567 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007568 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007569 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007570 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7571 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7572 // will set the builder into spec constant op instruction generating mode.
7573 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007574 result = accessChainLoad(sub_tree->getType());
7575 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007576 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007577 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007578 } else {
7579 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007580 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007581 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007582 builder.addName(result, sn->getName().c_str());
7583 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007584 }
qining4f4bb812016-04-03 23:55:17 -04007585
7586 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7587 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007588 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007589 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007590}
7591
John Kessenich140f3df2015-06-26 16:58:36 -06007592// Use 'consts' as the flattened glslang source of scalar constants to recursively
7593// build the aggregate SPIR-V constant.
7594//
7595// If there are not enough elements present in 'consts', 0 will be substituted;
7596// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7597//
qining08408382016-03-21 09:51:37 -04007598spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007599{
7600 // vector of constants for SPIR-V
7601 std::vector<spv::Id> spvConsts;
7602
7603 // Type is used for struct and array constants
7604 spv::Id typeId = convertGlslangToSpvType(glslangType);
7605
7606 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007607 glslang::TType elementType(glslangType, 0);
7608 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007609 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007610 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007611 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007612 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007613 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007614 } else if (glslangType.isCoopMat()) {
7615 glslang::TType componentType(glslangType.getBasicType());
7616 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007617 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007618 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7619 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007620 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007621 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007622 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7623 bool zero = nextConst >= consts.size();
7624 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007625 case glslang::EbtInt8:
7626 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7627 break;
7628 case glslang::EbtUint8:
7629 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7630 break;
7631 case glslang::EbtInt16:
7632 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7633 break;
7634 case glslang::EbtUint16:
7635 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7636 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007637 case glslang::EbtInt:
7638 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7639 break;
7640 case glslang::EbtUint:
7641 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7642 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007643 case glslang::EbtInt64:
7644 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7645 break;
7646 case glslang::EbtUint64:
7647 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7648 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007649 case glslang::EbtFloat:
7650 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7651 break;
7652 case glslang::EbtDouble:
7653 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7654 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007655 case glslang::EbtFloat16:
7656 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7657 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007658 case glslang::EbtBool:
7659 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7660 break;
7661 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007662 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007663 break;
7664 }
7665 ++nextConst;
7666 }
7667 } else {
7668 // we have a non-aggregate (scalar) constant
7669 bool zero = nextConst >= consts.size();
7670 spv::Id scalar = 0;
7671 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007672 case glslang::EbtInt8:
7673 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7674 break;
7675 case glslang::EbtUint8:
7676 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7677 break;
7678 case glslang::EbtInt16:
7679 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7680 break;
7681 case glslang::EbtUint16:
7682 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7683 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007684 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007685 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007686 break;
7687 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007688 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007689 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007690 case glslang::EbtInt64:
7691 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7692 break;
7693 case glslang::EbtUint64:
7694 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7695 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007696 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007697 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007698 break;
7699 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007700 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007701 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007702 case glslang::EbtFloat16:
7703 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7704 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007705 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007706 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007707 break;
7708 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007709 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007710 break;
7711 }
7712 ++nextConst;
7713 return scalar;
7714 }
7715
7716 return builder.makeCompositeConstant(typeId, spvConsts);
7717}
7718
John Kessenich7c1aa102015-10-15 13:29:11 -06007719// Return true if the node is a constant or symbol whose reading has no
7720// non-trivial observable cost or effect.
7721bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7722{
7723 // don't know what this is
7724 if (node == nullptr)
7725 return false;
7726
7727 // a constant is safe
7728 if (node->getAsConstantUnion() != nullptr)
7729 return true;
7730
7731 // not a symbol means non-trivial
7732 if (node->getAsSymbolNode() == nullptr)
7733 return false;
7734
7735 // a symbol, depends on what's being read
7736 switch (node->getType().getQualifier().storage) {
7737 case glslang::EvqTemporary:
7738 case glslang::EvqGlobal:
7739 case glslang::EvqIn:
7740 case glslang::EvqInOut:
7741 case glslang::EvqConst:
7742 case glslang::EvqConstReadOnly:
7743 case glslang::EvqUniform:
7744 return true;
7745 default:
7746 return false;
7747 }
qining25262b32016-05-06 17:25:16 -04007748}
John Kessenich7c1aa102015-10-15 13:29:11 -06007749
7750// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007751// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007752// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007753// Return true if trivial.
7754bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7755{
7756 if (node == nullptr)
7757 return false;
7758
John Kessenich84cc15f2017-05-24 16:44:47 -06007759 // count non scalars as trivial, as well as anything coming from HLSL
7760 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007761 return true;
7762
John Kessenich7c1aa102015-10-15 13:29:11 -06007763 // symbols and constants are trivial
7764 if (isTrivialLeaf(node))
7765 return true;
7766
7767 // otherwise, it needs to be a simple operation or one or two leaf nodes
7768
7769 // not a simple operation
7770 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7771 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7772 if (binaryNode == nullptr && unaryNode == nullptr)
7773 return false;
7774
7775 // not on leaf nodes
7776 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7777 return false;
7778
7779 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7780 return false;
7781 }
7782
7783 switch (node->getAsOperator()->getOp()) {
7784 case glslang::EOpLogicalNot:
7785 case glslang::EOpConvIntToBool:
7786 case glslang::EOpConvUintToBool:
7787 case glslang::EOpConvFloatToBool:
7788 case glslang::EOpConvDoubleToBool:
7789 case glslang::EOpEqual:
7790 case glslang::EOpNotEqual:
7791 case glslang::EOpLessThan:
7792 case glslang::EOpGreaterThan:
7793 case glslang::EOpLessThanEqual:
7794 case glslang::EOpGreaterThanEqual:
7795 case glslang::EOpIndexDirect:
7796 case glslang::EOpIndexDirectStruct:
7797 case glslang::EOpLogicalXor:
7798 case glslang::EOpAny:
7799 case glslang::EOpAll:
7800 return true;
7801 default:
7802 return false;
7803 }
7804}
7805
7806// Emit short-circuiting code, where 'right' is never evaluated unless
7807// the left side is true (for &&) or false (for ||).
7808spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7809{
7810 spv::Id boolTypeId = builder.makeBoolType();
7811
7812 // emit left operand
7813 builder.clearAccessChain();
7814 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007815 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007816
7817 // Operands to accumulate OpPhi operands
7818 std::vector<spv::Id> phiOperands;
7819 // accumulate left operand's phi information
7820 phiOperands.push_back(leftId);
7821 phiOperands.push_back(builder.getBuildPoint()->getId());
7822
7823 // Make the two kinds of operation symmetric with a "!"
7824 // || => emit "if (! left) result = right"
7825 // && => emit "if ( left) result = right"
7826 //
7827 // TODO: this runtime "not" for || could be avoided by adding functionality
7828 // to 'builder' to have an "else" without an "then"
7829 if (op == glslang::EOpLogicalOr)
7830 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7831
7832 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007833 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007834
7835 // emit right operand as the "then" part of the "if"
7836 builder.clearAccessChain();
7837 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007838 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007839
7840 // accumulate left operand's phi information
7841 phiOperands.push_back(rightId);
7842 phiOperands.push_back(builder.getBuildPoint()->getId());
7843
7844 // finish the "if"
7845 ifBuilder.makeEndIf();
7846
7847 // phi together the two results
7848 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7849}
7850
Frank Henigman541f7bb2018-01-16 00:18:26 -05007851#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007852// Return type Id of the imported set of extended instructions corresponds to the name.
7853// Import this set if it has not been imported yet.
7854spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7855{
7856 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7857 return extBuiltinMap[name];
7858 else {
Rex Xu51596642016-09-21 18:56:12 +08007859 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007860 spv::Id extBuiltins = builder.import(name);
7861 extBuiltinMap[name] = extBuiltins;
7862 return extBuiltins;
7863 }
7864}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007865#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007866
John Kessenich140f3df2015-06-26 16:58:36 -06007867}; // end anonymous namespace
7868
7869namespace glslang {
7870
John Kessenich68d78fd2015-07-12 19:28:10 -06007871void GetSpirvVersion(std::string& version)
7872{
John Kessenich9e55f632015-07-15 10:03:39 -06007873 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007874 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007875 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007876 version = buf;
7877}
7878
John Kessenicha372a3e2017-11-02 22:32:14 -06007879// For low-order part of the generator's magic number. Bump up
7880// when there is a change in the style (e.g., if SSA form changes,
7881// or a different instruction sequence to do something gets used).
7882int GetSpirvGeneratorVersion()
7883{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007884 // return 1; // start
7885 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007886 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007887 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007888 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007889 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7890 // versions 4 and 6 each generate OpArrayLength as it has long been done
7891 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007892}
7893
John Kessenich140f3df2015-06-26 16:58:36 -06007894// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007895void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007896{
7897 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007898 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007899 if (out.fail())
7900 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007901 for (int i = 0; i < (int)spirv.size(); ++i) {
7902 unsigned int word = spirv[i];
7903 out.write((const char*)&word, 4);
7904 }
7905 out.close();
7906}
7907
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007908// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007909void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007910{
7911 std::ofstream out;
7912 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007913 if (out.fail())
7914 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007915 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007916 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007917 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007918 if (varName != nullptr) {
7919 out << "\t #pragma once" << std::endl;
7920 out << "const uint32_t " << varName << "[] = {" << std::endl;
7921 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007922 const int WORDS_PER_LINE = 8;
7923 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7924 out << "\t";
7925 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7926 const unsigned int word = spirv[i + j];
7927 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7928 if (i + j + 1 < (int)spirv.size()) {
7929 out << ",";
7930 }
7931 }
7932 out << std::endl;
7933 }
Flavio15017db2017-02-15 14:29:33 -08007934 if (varName != nullptr) {
7935 out << "};";
7936 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007937 out.close();
7938}
7939
John Kessenich140f3df2015-06-26 16:58:36 -06007940//
7941// Set up the glslang traversal
7942//
John Kessenich4e11b612018-08-30 16:56:59 -06007943void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007944{
Lei Zhang17535f72016-05-04 15:55:59 -04007945 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007946 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007947}
7948
John Kessenich4e11b612018-08-30 16:56:59 -06007949void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007950 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007951{
John Kessenich140f3df2015-06-26 16:58:36 -06007952 TIntermNode* root = intermediate.getTreeRoot();
7953
7954 if (root == 0)
7955 return;
7956
John Kessenich4e11b612018-08-30 16:56:59 -06007957 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007958 if (options == nullptr)
7959 options = &defaultOptions;
7960
John Kessenich4e11b612018-08-30 16:56:59 -06007961 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007962
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007963 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007964 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007965 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007966 it.dumpSpv(spirv);
7967
GregFfb03a552018-03-29 11:49:14 -06007968#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007969 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7970 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007971 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007972 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007973
John Kessenich4e11b612018-08-30 16:56:59 -06007974 if (options->validate)
7975 SpirvToolsValidate(intermediate, spirv, logger);
7976
John Kessenich717c80a2018-08-23 15:17:10 -06007977 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007978 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007979
GregFcd1f1692017-09-21 18:40:22 -06007980#endif
7981
John Kessenich4e11b612018-08-30 16:56:59 -06007982 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06007983}
7984
7985}; // end namespace glslang