blob: 7dc0b947eb23c5d0e1bba822e91874b16e25be2c [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;
568 // *coherent variables are implicitly nonprivate in GLSL
569 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500570 flags.subgroupcoherent ||
571 flags.workgroupcoherent ||
572 flags.queuefamilycoherent ||
573 flags.devicecoherent ||
574 flags.coherent;
Jeff Bolz36831c92018-09-05 10:11:41 -0500575 flags.volatil = type.getQualifier().volatil;
576 flags.isImage = type.getBasicType() == glslang::EbtSampler;
577 return flags;
578}
579
580spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
581{
582 spv::Scope scope;
583 if (coherentFlags.coherent) {
584 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
585 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
586 } else if (coherentFlags.devicecoherent) {
587 scope = spv::ScopeDevice;
588 } else if (coherentFlags.queuefamilycoherent) {
589 scope = spv::ScopeQueueFamilyKHR;
590 } else if (coherentFlags.workgroupcoherent) {
591 scope = spv::ScopeWorkgroup;
592 } else if (coherentFlags.subgroupcoherent) {
593 scope = spv::ScopeSubgroup;
594 } else {
595 scope = spv::ScopeMax;
596 }
597 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
598 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
599 }
600 return scope;
601}
602
David Netoa901ffe2016-06-08 14:11:40 +0100603// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
604// associated capabilities when required. For some built-in variables, a capability
605// is generated only when using the variable in an executable instruction, but not when
606// just declaring a struct member variable with it. This is true for PointSize,
607// ClipDistance, and CullDistance.
608spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600609{
610 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700611 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600612 // Defer adding the capability until the built-in is actually used.
613 if (! memberDeclaration) {
614 switch (glslangIntermediate->getStage()) {
615 case EShLangGeometry:
616 builder.addCapability(spv::CapabilityGeometryPointSize);
617 break;
618 case EShLangTessControl:
619 case EShLangTessEvaluation:
620 builder.addCapability(spv::CapabilityTessellationPointSize);
621 break;
622 default:
623 break;
624 }
John Kessenich92187592016-02-01 13:45:25 -0700625 }
626 return spv::BuiltInPointSize;
627
John Kessenichebb50532016-05-16 19:22:05 -0600628 // These *Distance capabilities logically belong here, but if the member is declared and
629 // then never used, consumers of SPIR-V prefer the capability not be declared.
630 // They are now generated when used, rather than here when declared.
631 // Potentially, the specification should be more clear what the minimum
632 // use needed is to trigger the capability.
633 //
John Kessenich92187592016-02-01 13:45:25 -0700634 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100635 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800636 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700637 return spv::BuiltInClipDistance;
638
639 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100640 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800641 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700642 return spv::BuiltInCullDistance;
643
644 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600645 builder.addCapability(spv::CapabilityMultiViewport);
646 if (glslangIntermediate->getStage() == EShLangVertex ||
647 glslangIntermediate->getStage() == EShLangTessControl ||
648 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800649
John Kessenichba6a3c22017-09-13 13:22:50 -0600650 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
651 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800652 }
John Kessenich92187592016-02-01 13:45:25 -0700653 return spv::BuiltInViewportIndex;
654
John Kessenich5e801132016-02-15 11:09:46 -0700655 case glslang::EbvSampleId:
656 builder.addCapability(spv::CapabilitySampleRateShading);
657 return spv::BuiltInSampleId;
658
659 case glslang::EbvSamplePosition:
660 builder.addCapability(spv::CapabilitySampleRateShading);
661 return spv::BuiltInSamplePosition;
662
663 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700664 return spv::BuiltInSampleMask;
665
John Kessenich78a45572016-07-08 14:05:15 -0600666 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700667#ifdef NV_EXTENSIONS
668 if (glslangIntermediate->getStage() == EShLangMeshNV) {
669 return spv::BuiltInLayer;
670 }
671#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600672 builder.addCapability(spv::CapabilityGeometry);
673 if (glslangIntermediate->getStage() == EShLangVertex ||
674 glslangIntermediate->getStage() == EShLangTessControl ||
675 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800676
John Kessenichba6a3c22017-09-13 13:22:50 -0600677 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
678 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800679 }
John Kessenich78a45572016-07-08 14:05:15 -0600680 return spv::BuiltInLayer;
681
John Kessenich140f3df2015-06-26 16:58:36 -0600682 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600683 case glslang::EbvVertexId: return spv::BuiltInVertexId;
684 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700685 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
686 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800687
John Kessenichda581a22015-10-14 14:10:30 -0600688 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700689 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800690 builder.addCapability(spv::CapabilityDrawParameters);
691 return spv::BuiltInBaseVertex;
692
John Kessenichda581a22015-10-14 14:10:30 -0600693 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700694 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800695 builder.addCapability(spv::CapabilityDrawParameters);
696 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200697
John Kessenichda581a22015-10-14 14:10:30 -0600698 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700699 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800700 builder.addCapability(spv::CapabilityDrawParameters);
701 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200702
703 case glslang::EbvPrimitiveId:
704 if (glslangIntermediate->getStage() == EShLangFragment)
705 builder.addCapability(spv::CapabilityGeometry);
706 return spv::BuiltInPrimitiveId;
707
Rex Xu37cdcee2017-06-29 17:46:34 +0800708 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800709 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
710 builder.addCapability(spv::CapabilityStencilExportEXT);
711 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800712
John Kessenich140f3df2015-06-26 16:58:36 -0600713 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600714 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
715 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
716 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
717 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
718 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
719 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
720 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600721 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
722 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
723 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
724 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
725 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
726 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
727 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
728 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800729
Rex Xu574ab042016-04-14 16:53:07 +0800730 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800731 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800732 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
733 return spv::BuiltInSubgroupSize;
734
Rex Xu574ab042016-04-14 16:53:07 +0800735 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800736 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800737 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
738 return spv::BuiltInSubgroupLocalInvocationId;
739
Rex Xu574ab042016-04-14 16:53:07 +0800740 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800741 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
742 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
743 return spv::BuiltInSubgroupEqMaskKHR;
744
Rex Xu574ab042016-04-14 16:53:07 +0800745 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800746 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
747 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
748 return spv::BuiltInSubgroupGeMaskKHR;
749
Rex Xu574ab042016-04-14 16:53:07 +0800750 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800751 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
752 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
753 return spv::BuiltInSubgroupGtMaskKHR;
754
Rex Xu574ab042016-04-14 16:53:07 +0800755 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800756 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
757 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
758 return spv::BuiltInSubgroupLeMaskKHR;
759
Rex Xu574ab042016-04-14 16:53:07 +0800760 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800761 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
762 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
763 return spv::BuiltInSubgroupLtMaskKHR;
764
John Kessenich66011cb2018-03-06 16:12:04 -0700765 case glslang::EbvNumSubgroups:
766 builder.addCapability(spv::CapabilityGroupNonUniform);
767 return spv::BuiltInNumSubgroups;
768
769 case glslang::EbvSubgroupID:
770 builder.addCapability(spv::CapabilityGroupNonUniform);
771 return spv::BuiltInSubgroupId;
772
773 case glslang::EbvSubgroupSize2:
774 builder.addCapability(spv::CapabilityGroupNonUniform);
775 return spv::BuiltInSubgroupSize;
776
777 case glslang::EbvSubgroupInvocation2:
778 builder.addCapability(spv::CapabilityGroupNonUniform);
779 return spv::BuiltInSubgroupLocalInvocationId;
780
781 case glslang::EbvSubgroupEqMask2:
782 builder.addCapability(spv::CapabilityGroupNonUniform);
783 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
784 return spv::BuiltInSubgroupEqMask;
785
786 case glslang::EbvSubgroupGeMask2:
787 builder.addCapability(spv::CapabilityGroupNonUniform);
788 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
789 return spv::BuiltInSubgroupGeMask;
790
791 case glslang::EbvSubgroupGtMask2:
792 builder.addCapability(spv::CapabilityGroupNonUniform);
793 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
794 return spv::BuiltInSubgroupGtMask;
795
796 case glslang::EbvSubgroupLeMask2:
797 builder.addCapability(spv::CapabilityGroupNonUniform);
798 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
799 return spv::BuiltInSubgroupLeMask;
800
801 case glslang::EbvSubgroupLtMask2:
802 builder.addCapability(spv::CapabilityGroupNonUniform);
803 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
804 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800805#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800806 case glslang::EbvBaryCoordNoPersp:
807 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
808 return spv::BuiltInBaryCoordNoPerspAMD;
809
810 case glslang::EbvBaryCoordNoPerspCentroid:
811 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
812 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
813
814 case glslang::EbvBaryCoordNoPerspSample:
815 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
816 return spv::BuiltInBaryCoordNoPerspSampleAMD;
817
818 case glslang::EbvBaryCoordSmooth:
819 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
820 return spv::BuiltInBaryCoordSmoothAMD;
821
822 case glslang::EbvBaryCoordSmoothCentroid:
823 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
824 return spv::BuiltInBaryCoordSmoothCentroidAMD;
825
826 case glslang::EbvBaryCoordSmoothSample:
827 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
828 return spv::BuiltInBaryCoordSmoothSampleAMD;
829
830 case glslang::EbvBaryCoordPullModel:
831 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
832 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800833#endif
chaoc771d89f2017-01-13 01:10:53 -0800834
John Kessenich6c8aaac2017-02-27 01:20:51 -0700835 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700836 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700837 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700838 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700839
840 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700841 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700842 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700843 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700844
Daniel Koch5154db52018-11-26 10:01:58 -0500845 case glslang::EbvFragSizeEXT:
846 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
847 builder.addCapability(spv::CapabilityFragmentDensityEXT);
848 return spv::BuiltInFragSizeEXT;
849
850 case glslang::EbvFragInvocationCountEXT:
851 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
852 builder.addCapability(spv::CapabilityFragmentDensityEXT);
853 return spv::BuiltInFragInvocationCountEXT;
854
chaoc771d89f2017-01-13 01:10:53 -0800855#ifdef NV_EXTENSIONS
856 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800857 if (!memberDeclaration) {
858 builder.addExtension(spv::E_SPV_NV_viewport_array2);
859 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
860 }
chaoc771d89f2017-01-13 01:10:53 -0800861 return spv::BuiltInViewportMaskNV;
862 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800863 if (!memberDeclaration) {
864 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
865 builder.addCapability(spv::CapabilityShaderStereoViewNV);
866 }
chaoc771d89f2017-01-13 01:10:53 -0800867 return spv::BuiltInSecondaryPositionNV;
868 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800869 if (!memberDeclaration) {
870 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
871 builder.addCapability(spv::CapabilityShaderStereoViewNV);
872 }
chaoc771d89f2017-01-13 01:10:53 -0800873 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800874 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800875 if (!memberDeclaration) {
876 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
877 builder.addCapability(spv::CapabilityPerViewAttributesNV);
878 }
chaocdf3956c2017-02-14 14:52:34 -0800879 return spv::BuiltInPositionPerViewNV;
880 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800881 if (!memberDeclaration) {
882 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
883 builder.addCapability(spv::CapabilityPerViewAttributesNV);
884 }
chaocdf3956c2017-02-14 14:52:34 -0800885 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700886 case glslang::EbvFragFullyCoveredNV:
887 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
888 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
889 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700890 case glslang::EbvFragmentSizeNV:
891 builder.addExtension(spv::E_SPV_NV_shading_rate);
892 builder.addCapability(spv::CapabilityShadingRateNV);
893 return spv::BuiltInFragmentSizeNV;
894 case glslang::EbvInvocationsPerPixelNV:
895 builder.addExtension(spv::E_SPV_NV_shading_rate);
896 builder.addCapability(spv::CapabilityShadingRateNV);
897 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700898
899 // raytracing
900 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700901 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700902 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700903 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700904 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700905 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700906 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700907 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700908 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700909 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700910 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700911 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700912 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700913 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700914 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700915 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700916 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700917 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700918 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700919 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700920 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700921 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700922 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700923 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700924 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700925 return spv::BuiltInWorldToObjectNV;
926 case glslang::EbvIncomingRayFlagsNV:
927 return spv::BuiltInIncomingRayFlagsNV;
Chao Chen9eada4b2018-09-19 11:39:56 -0700928 case glslang::EbvBaryCoordNV:
929 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
930 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
931 return spv::BuiltInBaryCoordNV;
932 case glslang::EbvBaryCoordNoPerspNV:
933 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
934 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
935 return spv::BuiltInBaryCoordNoPerspNV;
Chao Chen3c366992018-09-19 11:41:59 -0700936 case glslang::EbvTaskCountNV:
937 return spv::BuiltInTaskCountNV;
938 case glslang::EbvPrimitiveCountNV:
939 return spv::BuiltInPrimitiveCountNV;
940 case glslang::EbvPrimitiveIndicesNV:
941 return spv::BuiltInPrimitiveIndicesNV;
942 case glslang::EbvClipDistancePerViewNV:
943 return spv::BuiltInClipDistancePerViewNV;
944 case glslang::EbvCullDistancePerViewNV:
945 return spv::BuiltInCullDistancePerViewNV;
946 case glslang::EbvLayerPerViewNV:
947 return spv::BuiltInLayerPerViewNV;
948 case glslang::EbvMeshViewCountNV:
949 return spv::BuiltInMeshViewCountNV;
950 case glslang::EbvMeshViewIndicesNV:
951 return spv::BuiltInMeshViewIndicesNV;
chaoc771d89f2017-01-13 01:10:53 -0800952#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800953 default:
954 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600955 }
956}
957
Rex Xufc618912015-09-09 16:42:49 +0800958// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700959spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800960{
961 assert(type.getBasicType() == glslang::EbtSampler);
962
John Kessenich5d0fa972016-02-15 11:57:00 -0700963 // Check for capabilities
964 switch (type.getQualifier().layoutFormat) {
965 case glslang::ElfRg32f:
966 case glslang::ElfRg16f:
967 case glslang::ElfR11fG11fB10f:
968 case glslang::ElfR16f:
969 case glslang::ElfRgba16:
970 case glslang::ElfRgb10A2:
971 case glslang::ElfRg16:
972 case glslang::ElfRg8:
973 case glslang::ElfR16:
974 case glslang::ElfR8:
975 case glslang::ElfRgba16Snorm:
976 case glslang::ElfRg16Snorm:
977 case glslang::ElfRg8Snorm:
978 case glslang::ElfR16Snorm:
979 case glslang::ElfR8Snorm:
980
981 case glslang::ElfRg32i:
982 case glslang::ElfRg16i:
983 case glslang::ElfRg8i:
984 case glslang::ElfR16i:
985 case glslang::ElfR8i:
986
987 case glslang::ElfRgb10a2ui:
988 case glslang::ElfRg32ui:
989 case glslang::ElfRg16ui:
990 case glslang::ElfRg8ui:
991 case glslang::ElfR16ui:
992 case glslang::ElfR8ui:
993 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
994 break;
995
996 default:
997 break;
998 }
999
1000 // do the translation
Rex Xufc618912015-09-09 16:42:49 +08001001 switch (type.getQualifier().layoutFormat) {
1002 case glslang::ElfNone: return spv::ImageFormatUnknown;
1003 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1004 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1005 case glslang::ElfR32f: return spv::ImageFormatR32f;
1006 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1007 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1008 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1009 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1010 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1011 case glslang::ElfR16f: return spv::ImageFormatR16f;
1012 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1013 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1014 case glslang::ElfRg16: return spv::ImageFormatRg16;
1015 case glslang::ElfRg8: return spv::ImageFormatRg8;
1016 case glslang::ElfR16: return spv::ImageFormatR16;
1017 case glslang::ElfR8: return spv::ImageFormatR8;
1018 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1019 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1020 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1021 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1022 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1023 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1024 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1025 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1026 case glslang::ElfR32i: return spv::ImageFormatR32i;
1027 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1028 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1029 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1030 case glslang::ElfR16i: return spv::ImageFormatR16i;
1031 case glslang::ElfR8i: return spv::ImageFormatR8i;
1032 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1033 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1034 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1035 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1036 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1037 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1038 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1039 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1040 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1041 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001042 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001043 }
1044}
1045
John Kesseniche18fd202018-01-30 11:01:39 -07001046spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001047{
John Kesseniche18fd202018-01-30 11:01:39 -07001048 if (selectionNode.getFlatten())
1049 return spv::SelectionControlFlattenMask;
1050 if (selectionNode.getDontFlatten())
1051 return spv::SelectionControlDontFlattenMask;
1052 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001053}
1054
John Kesseniche18fd202018-01-30 11:01:39 -07001055spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001056{
John Kesseniche18fd202018-01-30 11:01:39 -07001057 if (switchNode.getFlatten())
1058 return spv::SelectionControlFlattenMask;
1059 if (switchNode.getDontFlatten())
1060 return spv::SelectionControlDontFlattenMask;
1061 return spv::SelectionControlMaskNone;
1062}
1063
John Kessenicha2858d92018-01-31 08:11:18 -07001064// return a non-0 dependency if the dependency argument must be set
1065spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
1066 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -07001067{
1068 spv::LoopControlMask control = spv::LoopControlMaskNone;
1069
1070 if (loopNode.getDontUnroll())
1071 control = control | spv::LoopControlDontUnrollMask;
1072 if (loopNode.getUnroll())
1073 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001074 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001075 control = control | spv::LoopControlDependencyInfiniteMask;
1076 else if (loopNode.getLoopDependency() > 0) {
1077 control = control | spv::LoopControlDependencyLengthMask;
1078 dependencyLength = loopNode.getLoopDependency();
1079 }
John Kesseniche18fd202018-01-30 11:01:39 -07001080
1081 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001082}
1083
John Kessenicha5c5fb62017-05-05 05:09:58 -06001084// Translate glslang type to SPIR-V storage class.
1085spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1086{
1087 if (type.getQualifier().isPipeInput())
1088 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001089 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001090 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001091
1092 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1093 type.getQualifier().storage == glslang::EvqUniform) {
1094 if (type.getBasicType() == glslang::EbtAtomicUint)
1095 return spv::StorageClassAtomicCounter;
1096 if (type.containsOpaque())
1097 return spv::StorageClassUniformConstant;
1098 }
1099
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001100#ifdef NV_EXTENSIONS
1101 if (type.getQualifier().isUniformOrBuffer() &&
1102 type.getQualifier().layoutShaderRecordNV) {
1103 return spv::StorageClassShaderRecordBufferNV;
1104 }
1105#endif
1106
John Kessenichbed4e4f2017-09-08 02:38:07 -06001107 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001108 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001109 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001110 }
1111
1112 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001113 if (type.getQualifier().layoutPushConstant)
1114 return spv::StorageClassPushConstant;
1115 if (type.getBasicType() == glslang::EbtBlock)
1116 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001117 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001118 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001119
1120 switch (type.getQualifier().storage) {
1121 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1122 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1123 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1124 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001125#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001126 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1127 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1128 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1129 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1130 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001131#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001132 default:
1133 assert(0);
1134 break;
1135 }
1136
1137 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001138}
1139
John Kessenich5611c6d2018-04-05 11:25:02 -06001140// Add capabilities pertaining to how an array is indexed.
1141void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1142 const glslang::TType& indexType)
1143{
1144 if (indexType.getQualifier().isNonUniform()) {
1145 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001146 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001147 if (baseType.getBasicType() == glslang::EbtSampler) {
1148 if (baseType.getQualifier().hasAttachment())
1149 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1150 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1151 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1152 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1153 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1154 else if (baseType.isImage())
1155 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1156 else if (baseType.isTexture())
1157 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1158 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1159 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1160 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1161 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1162 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1163 }
1164 } else {
1165 // assume a dynamically uniform index
1166 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001167 if (baseType.getQualifier().hasAttachment()) {
1168 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001169 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001170 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1171 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001172 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001173 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1174 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001175 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001176 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001177 }
1178 }
1179}
1180
qining25262b32016-05-06 17:25:16 -04001181// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001182// descriptor set.
1183bool IsDescriptorResource(const glslang::TType& type)
1184{
John Kessenichf7497e22016-03-08 21:36:22 -07001185 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001186 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001187 return type.getQualifier().isUniformOrBuffer() &&
1188#ifdef NV_EXTENSIONS
1189 ! type.getQualifier().layoutShaderRecordNV &&
1190#endif
1191 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001192
1193 // non block...
1194 // basically samplerXXX/subpass/sampler/texture are all included
1195 // if they are the global-scope-class, not the function parameter
1196 // (or local, if they ever exist) class.
1197 if (type.getBasicType() == glslang::EbtSampler)
1198 return type.getQualifier().isUniformOrBuffer();
1199
1200 // None of the above.
1201 return false;
1202}
1203
John Kesseniche0b6cad2015-12-24 10:30:13 -07001204void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1205{
1206 if (child.layoutMatrix == glslang::ElmNone)
1207 child.layoutMatrix = parent.layoutMatrix;
1208
1209 if (parent.invariant)
1210 child.invariant = true;
1211 if (parent.nopersp)
1212 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001213#ifdef AMD_EXTENSIONS
1214 if (parent.explicitInterp)
1215 child.explicitInterp = true;
1216#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001217 if (parent.flat)
1218 child.flat = true;
1219 if (parent.centroid)
1220 child.centroid = true;
1221 if (parent.patch)
1222 child.patch = true;
1223 if (parent.sample)
1224 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001225 if (parent.coherent)
1226 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001227 if (parent.devicecoherent)
1228 child.devicecoherent = true;
1229 if (parent.queuefamilycoherent)
1230 child.queuefamilycoherent = true;
1231 if (parent.workgroupcoherent)
1232 child.workgroupcoherent = true;
1233 if (parent.subgroupcoherent)
1234 child.subgroupcoherent = true;
1235 if (parent.nonprivate)
1236 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001237 if (parent.volatil)
1238 child.volatil = true;
1239 if (parent.restrict)
1240 child.restrict = true;
1241 if (parent.readonly)
1242 child.readonly = true;
1243 if (parent.writeonly)
1244 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001245#ifdef NV_EXTENSIONS
1246 if (parent.perPrimitiveNV)
1247 child.perPrimitiveNV = true;
1248 if (parent.perViewNV)
1249 child.perViewNV = true;
1250 if (parent.perTaskNV)
1251 child.perTaskNV = true;
1252#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001253}
1254
John Kessenichf2b7f332016-09-01 17:05:23 -06001255bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001256{
John Kessenich7b9fa252016-01-21 18:56:57 -07001257 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001258 // - struct members might inherit from a struct declaration
1259 // (note that non-block structs don't explicitly inherit,
1260 // only implicitly, meaning no decoration involved)
1261 // - affect decorations on the struct members
1262 // (note smooth does not, and expecting something like volatile
1263 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001264 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001265 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001266}
1267
John Kessenich140f3df2015-06-26 16:58:36 -06001268//
1269// Implement the TGlslangToSpvTraverser class.
1270//
1271
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001272TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001273 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1274 : TIntermTraverser(true, false, true),
1275 options(options),
1276 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001277 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001278 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001279 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001280 glslangIntermediate(glslangIntermediate)
1281{
1282 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1283
1284 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001285 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1286 glslangIntermediate->getVersion());
1287
John Kessenich121853f2017-05-31 17:11:16 -06001288 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001289 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001290 builder.setSourceFile(glslangIntermediate->getSourceFile());
1291
1292 // Set the source shader's text. If for SPV version 1.0, include
1293 // a preamble in comments stating the OpModuleProcessed instructions.
1294 // Otherwise, emit those as actual instructions.
1295 std::string text;
1296 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1297 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001298 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001299 text.append("// OpModuleProcessed ");
1300 text.append(processes[p]);
1301 text.append("\n");
1302 } else
1303 builder.addModuleProcessed(processes[p]);
1304 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001305 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001306 text.append("#line 1\n");
1307 text.append(glslangIntermediate->getSourceText());
1308 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001309 // Pass name and text for all included files
1310 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1311 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1312 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001313 }
John Kessenich140f3df2015-06-26 16:58:36 -06001314 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001315
1316 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1317 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1318
1319 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1320 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1321 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1322 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1323 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001324 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001325 memoryModel = spv::MemoryModelVulkanKHR;
1326 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001327 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001328 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001329 builder.setMemoryModel(addressingModel, memoryModel);
1330
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001331 if (glslangIntermediate->usingVariablePointers()) {
1332 builder.addCapability(spv::CapabilityVariablePointers);
1333 }
1334
John Kessenicheee9d532016-09-19 18:09:30 -06001335 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1336 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001337
1338 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001339 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1340 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001341 builder.addSourceExtension(it->c_str());
1342
1343 // Add the top-level modes for this shader.
1344
John Kessenich92187592016-02-01 13:45:25 -07001345 if (glslangIntermediate->getXfbMode()) {
1346 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001347 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001348 }
John Kessenich140f3df2015-06-26 16:58:36 -06001349
1350 unsigned int mode;
1351 switch (glslangIntermediate->getStage()) {
1352 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001353 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001354 break;
1355
steve-lunarge7412492017-03-23 11:56:07 -06001356 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001357 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001358 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001359
steve-lunarge7412492017-03-23 11:56:07 -06001360 glslang::TLayoutGeometry primitive;
1361
1362 if (glslangIntermediate->getStage() == EShLangTessControl) {
1363 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1364 primitive = glslangIntermediate->getOutputPrimitive();
1365 } else {
1366 primitive = glslangIntermediate->getInputPrimitive();
1367 }
1368
1369 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001370 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1371 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1372 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001373 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001374 }
John Kessenich4016e382016-07-15 11:53:56 -06001375 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001376 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1377
John Kesseniche6903322015-10-13 16:29:02 -06001378 switch (glslangIntermediate->getVertexSpacing()) {
1379 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1380 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1381 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001382 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001383 }
John Kessenich4016e382016-07-15 11:53:56 -06001384 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001385 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1386
1387 switch (glslangIntermediate->getVertexOrder()) {
1388 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1389 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001390 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001391 }
John Kessenich4016e382016-07-15 11:53:56 -06001392 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001393 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1394
1395 if (glslangIntermediate->getPointMode())
1396 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001397 break;
1398
1399 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001400 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001401 switch (glslangIntermediate->getInputPrimitive()) {
1402 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1403 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1404 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001405 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001406 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001407 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001408 }
John Kessenich4016e382016-07-15 11:53:56 -06001409 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001410 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001411
John Kessenich140f3df2015-06-26 16:58:36 -06001412 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1413
1414 switch (glslangIntermediate->getOutputPrimitive()) {
1415 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1416 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1417 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001418 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001419 }
John Kessenich4016e382016-07-15 11:53:56 -06001420 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001421 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1422 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1423 break;
1424
1425 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001426 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001427 if (glslangIntermediate->getPixelCenterInteger())
1428 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001429
John Kessenich140f3df2015-06-26 16:58:36 -06001430 if (glslangIntermediate->getOriginUpperLeft())
1431 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001432 else
1433 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001434
1435 if (glslangIntermediate->getEarlyFragmentTests())
1436 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1437
chaocc1204522017-06-30 17:14:30 -07001438 if (glslangIntermediate->getPostDepthCoverage()) {
1439 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1440 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1441 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1442 }
1443
John Kesseniche6903322015-10-13 16:29:02 -06001444 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001445 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1446 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001447 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001448 }
John Kessenich4016e382016-07-15 11:53:56 -06001449 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001450 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1451
1452 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1453 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001454 break;
1455
1456 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001457 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001458 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1459 glslangIntermediate->getLocalSize(1),
1460 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001461#ifdef NV_EXTENSIONS
1462 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1463 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1464 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1465 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1466 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1467 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1468 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1469 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1470 }
1471#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001472 break;
1473
Chao Chen3c366992018-09-19 11:41:59 -07001474#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001475 case EShLangRayGenNV:
1476 case EShLangIntersectNV:
1477 case EShLangAnyHitNV:
1478 case EShLangClosestHitNV:
1479 case EShLangMissNV:
1480 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001481 builder.addCapability(spv::CapabilityRayTracingNV);
1482 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001483 break;
Chao Chen3c366992018-09-19 11:41:59 -07001484 case EShLangTaskNV:
1485 case EShLangMeshNV:
1486 builder.addCapability(spv::CapabilityMeshShadingNV);
1487 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1488 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1489 glslangIntermediate->getLocalSize(1),
1490 glslangIntermediate->getLocalSize(2));
1491 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1492 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1493 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1494
1495 switch (glslangIntermediate->getOutputPrimitive()) {
1496 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1497 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1498 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1499 default: mode = spv::ExecutionModeMax; break;
1500 }
1501 if (mode != spv::ExecutionModeMax)
1502 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1503 }
1504 break;
1505#endif
1506
John Kessenich140f3df2015-06-26 16:58:36 -06001507 default:
1508 break;
1509 }
John Kessenich140f3df2015-06-26 16:58:36 -06001510}
1511
John Kessenichfca82622016-11-26 13:23:20 -07001512// Finish creating SPV, after the traversal is complete.
1513void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001514{
John Kessenichf04c51b2018-08-03 15:56:12 -06001515 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001516 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001517 builder.setBuildPoint(shaderEntry->getLastBlock());
1518 builder.leaveFunction();
1519 }
1520
John Kessenich7ba63412015-12-20 17:37:07 -07001521 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001522 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1523 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001524
John Kessenichf04c51b2018-08-03 15:56:12 -06001525 // Add capabilities, extensions, remove unneeded decorations, etc.,
1526 // based on the resulting SPIR-V.
1527 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001528}
1529
John Kessenichfca82622016-11-26 13:23:20 -07001530// Write the SPV into 'out'.
1531void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001532{
John Kessenichfca82622016-11-26 13:23:20 -07001533 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001534}
1535
1536//
1537// Implement the traversal functions.
1538//
1539// Return true from interior nodes to have the external traversal
1540// continue on to children. Return false if children were
1541// already processed.
1542//
1543
1544//
qining25262b32016-05-06 17:25:16 -04001545// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001546// - uniform/input reads
1547// - output writes
1548// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1549// - something simple that degenerates into the last bullet
1550//
1551void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1552{
qining75d1d802016-04-06 14:42:01 -04001553 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1554 if (symbol->getType().getQualifier().isSpecConstant())
1555 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1556
John Kessenich140f3df2015-06-26 16:58:36 -06001557 // getSymbolId() will set up all the IO decorations on the first call.
1558 // Formal function parameters were mapped during makeFunctions().
1559 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001560
1561 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1562 if (builder.isPointer(id)) {
1563 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001564 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1565 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1566 iOSet.insert(id);
1567 }
John Kessenich7ba63412015-12-20 17:37:07 -07001568 }
1569
1570 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001571 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001572 // Prepare to generate code for the access
1573
1574 // L-value chains will be computed left to right. We're on the symbol now,
1575 // which is the left-most part of the access chain, so now is "clear" time,
1576 // followed by setting the base.
1577 builder.clearAccessChain();
1578
1579 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001580 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001581 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001582 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001583 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001584 // These are also pure R-values.
1585 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001586 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001587 builder.setAccessChainRValue(id);
1588 else
1589 builder.setAccessChainLValue(id);
1590 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001591
1592 // Process linkage-only nodes for any special additional interface work.
1593 if (linkageOnly) {
1594 if (glslangIntermediate->getHlslFunctionality1()) {
1595 // Map implicit counter buffers to their originating buffers, which should have been
1596 // seen by now, given earlier pruning of unused counters, and preservation of order
1597 // of declaration.
1598 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1599 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1600 // Save possible originating buffers for counter buffers, keyed by
1601 // making the potential counter-buffer name.
1602 std::string keyName = symbol->getName().c_str();
1603 keyName = glslangIntermediate->addCounterBufferName(keyName);
1604 counterOriginator[keyName] = symbol;
1605 } else {
1606 // Handle a counter buffer, by finding the saved originating buffer.
1607 std::string keyName = symbol->getName().c_str();
1608 auto it = counterOriginator.find(keyName);
1609 if (it != counterOriginator.end()) {
1610 id = getSymbolId(it->second);
1611 if (id != spv::NoResult) {
1612 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001613 if (counterId != spv::NoResult) {
1614 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001615 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001616 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001617 }
1618 }
1619 }
1620 }
1621 }
1622 }
John Kessenich140f3df2015-06-26 16:58:36 -06001623}
1624
1625bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1626{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001627 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001628
qining40887662016-04-03 22:20:42 -04001629 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1630 if (node->getType().getQualifier().isSpecConstant())
1631 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1632
John Kessenich140f3df2015-06-26 16:58:36 -06001633 // First, handle special cases
1634 switch (node->getOp()) {
1635 case glslang::EOpAssign:
1636 case glslang::EOpAddAssign:
1637 case glslang::EOpSubAssign:
1638 case glslang::EOpMulAssign:
1639 case glslang::EOpVectorTimesMatrixAssign:
1640 case glslang::EOpVectorTimesScalarAssign:
1641 case glslang::EOpMatrixTimesScalarAssign:
1642 case glslang::EOpMatrixTimesMatrixAssign:
1643 case glslang::EOpDivAssign:
1644 case glslang::EOpModAssign:
1645 case glslang::EOpAndAssign:
1646 case glslang::EOpInclusiveOrAssign:
1647 case glslang::EOpExclusiveOrAssign:
1648 case glslang::EOpLeftShiftAssign:
1649 case glslang::EOpRightShiftAssign:
1650 // A bin-op assign "a += b" means the same thing as "a = a + b"
1651 // where a is evaluated before b. For a simple assignment, GLSL
1652 // says to evaluate the left before the right. So, always, left
1653 // node then right node.
1654 {
1655 // get the left l-value, save it away
1656 builder.clearAccessChain();
1657 node->getLeft()->traverse(this);
1658 spv::Builder::AccessChain lValue = builder.getAccessChain();
1659
1660 // evaluate the right
1661 builder.clearAccessChain();
1662 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001663 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001664
1665 if (node->getOp() != glslang::EOpAssign) {
1666 // the left is also an r-value
1667 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001668 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001669
1670 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001671 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001672 TranslateNoContractionDecoration(node->getType().getQualifier()),
1673 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001674 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001675 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1676 node->getType().getBasicType());
1677
1678 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001679 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001680 }
1681
1682 // store the result
1683 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001684 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001685
1686 // assignments are expressions having an rValue after they are evaluated...
1687 builder.clearAccessChain();
1688 builder.setAccessChainRValue(rValue);
1689 }
1690 return false;
1691 case glslang::EOpIndexDirect:
1692 case glslang::EOpIndexDirectStruct:
1693 {
1694 // Get the left part of the access chain.
1695 node->getLeft()->traverse(this);
1696
1697 // Add the next element in the chain
1698
David Netoa901ffe2016-06-08 14:11:40 +01001699 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001700 if (! node->getLeft()->getType().isArray() &&
1701 node->getLeft()->getType().isVector() &&
1702 node->getOp() == glslang::EOpIndexDirect) {
1703 // This is essentially a hard-coded vector swizzle of size 1,
1704 // so short circuit the access-chain stuff with a swizzle.
1705 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001706 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001707 int dummySize;
1708 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1709 TranslateCoherent(node->getLeft()->getType()),
1710 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001711 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001712
1713 // Load through a block reference is performed with a dot operator that
1714 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1715 // do a load and reset the access chain.
1716 if (node->getLeft()->getBasicType() == glslang::EbtReference &&
1717 !node->getLeft()->getType().isArray() &&
1718 node->getOp() == glslang::EOpIndexDirectStruct)
1719 {
1720 spv::Id left = accessChainLoad(node->getLeft()->getType());
1721 builder.clearAccessChain();
1722 builder.setAccessChainLValue(left);
1723 }
1724
David Netoa901ffe2016-06-08 14:11:40 +01001725 int spvIndex = glslangIndex;
1726 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1727 node->getOp() == glslang::EOpIndexDirectStruct)
1728 {
1729 // This may be, e.g., an anonymous block-member selection, which generally need
1730 // index remapping due to hidden members in anonymous blocks.
1731 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1732 assert(remapper.size() > 0);
1733 spvIndex = remapper[glslangIndex];
1734 }
John Kessenichebb50532016-05-16 19:22:05 -06001735
David Netoa901ffe2016-06-08 14:11:40 +01001736 // normal case for indexing array or structure or block
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001737 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), getBufferReferenceAlignment(node->getLeft()->getType()));
David Netoa901ffe2016-06-08 14:11:40 +01001738
1739 // Add capabilities here for accessing PointSize and clip/cull distance.
1740 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001741 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001742 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001743 }
1744 }
1745 return false;
1746 case glslang::EOpIndexIndirect:
1747 {
1748 // Structure or array or vector indirection.
1749 // Will use native SPIR-V access-chain for struct and array indirection;
1750 // matrices are arrays of vectors, so will also work for a matrix.
1751 // Will use the access chain's 'component' for variable index into a vector.
1752
1753 // This adapter is building access chains left to right.
1754 // Set up the access chain to the left.
1755 node->getLeft()->traverse(this);
1756
1757 // save it so that computing the right side doesn't trash it
1758 spv::Builder::AccessChain partial = builder.getAccessChain();
1759
1760 // compute the next index in the chain
1761 builder.clearAccessChain();
1762 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001763 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001764
John Kessenich5611c6d2018-04-05 11:25:02 -06001765 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1766
John Kessenich140f3df2015-06-26 16:58:36 -06001767 // restore the saved access chain
1768 builder.setAccessChain(partial);
1769
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001770 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1771 int dummySize;
1772 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1773 TranslateCoherent(node->getLeft()->getType()),
1774 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1775 } else
1776 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), getBufferReferenceAlignment(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001777 }
1778 return false;
1779 case glslang::EOpVectorSwizzle:
1780 {
1781 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001782 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001783 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001784 int dummySize;
1785 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1786 TranslateCoherent(node->getLeft()->getType()),
1787 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001788 }
1789 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001790 case glslang::EOpMatrixSwizzle:
1791 logger->missingFunctionality("matrix swizzle");
1792 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001793 case glslang::EOpLogicalOr:
1794 case glslang::EOpLogicalAnd:
1795 {
1796
1797 // These may require short circuiting, but can sometimes be done as straight
1798 // binary operations. The right operand must be short circuited if it has
1799 // side effects, and should probably be if it is complex.
1800 if (isTrivial(node->getRight()->getAsTyped()))
1801 break; // handle below as a normal binary operation
1802 // otherwise, we need to do dynamic short circuiting on the right operand
1803 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1804 builder.clearAccessChain();
1805 builder.setAccessChainRValue(result);
1806 }
1807 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001808 default:
1809 break;
1810 }
1811
1812 // Assume generic binary op...
1813
John Kessenich32cfd492016-02-02 12:37:46 -07001814 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001815 builder.clearAccessChain();
1816 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001817 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001818
John Kessenich32cfd492016-02-02 12:37:46 -07001819 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001820 builder.clearAccessChain();
1821 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001822 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001823
John Kessenich32cfd492016-02-02 12:37:46 -07001824 // get result
John Kessenichead86222018-03-28 18:01:20 -06001825 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001826 TranslateNoContractionDecoration(node->getType().getQualifier()),
1827 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001828 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001829 convertGlslangToSpvType(node->getType()), left, right,
1830 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001831
John Kessenich50e57562015-12-21 21:21:11 -07001832 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001833 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001834 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001835 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001836 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001837 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001838 return false;
1839 }
John Kessenich140f3df2015-06-26 16:58:36 -06001840}
1841
1842bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1843{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001844 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001845
qining40887662016-04-03 22:20:42 -04001846 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1847 if (node->getType().getQualifier().isSpecConstant())
1848 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1849
John Kessenichfc51d282015-08-19 13:34:18 -06001850 spv::Id result = spv::NoResult;
1851
1852 // try texturing first
1853 result = createImageTextureFunctionCall(node);
1854 if (result != spv::NoResult) {
1855 builder.clearAccessChain();
1856 builder.setAccessChainRValue(result);
1857
1858 return false; // done with this node
1859 }
1860
1861 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001862
1863 if (node->getOp() == glslang::EOpArrayLength) {
1864 // Quite special; won't want to evaluate the operand.
1865
John Kessenich5611c6d2018-04-05 11:25:02 -06001866 // Currently, the front-end does not allow .length() on an array until it is sized,
1867 // except for the last block membeor of an SSBO.
1868 // TODO: If this changes, link-time sized arrays might show up here, and need their
1869 // size extracted.
1870
John Kessenichc9a80832015-09-12 12:17:44 -06001871 // Normal .length() would have been constant folded by the front-end.
1872 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001873 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001874
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001875 spv::Id length;
1876 if (node->getOperand()->getType().isCoopMat()) {
1877 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1878
1879 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
1880 assert(builder.isCooperativeMatrixType(typeId));
1881
1882 length = builder.createCooperativeMatrixLength(typeId);
1883 } else {
1884 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1885 block->traverse(this);
1886 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1887 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
1888 }
John Kessenichc9a80832015-09-12 12:17:44 -06001889
John Kessenich8c869672018-11-28 07:01:37 -07001890 // GLSL semantics say the result of .length() is an int, while SPIR-V says
1891 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
1892 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001893 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
1894 if (builder.isInSpecConstCodeGenMode()) {
1895 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
1896 } else {
1897 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
1898 }
1899 }
John Kessenich8c869672018-11-28 07:01:37 -07001900
John Kessenichc9a80832015-09-12 12:17:44 -06001901 builder.clearAccessChain();
1902 builder.setAccessChainRValue(length);
1903
1904 return false;
1905 }
1906
John Kessenichfc51d282015-08-19 13:34:18 -06001907 // Start by evaluating the operand
1908
John Kessenich8c8505c2016-07-26 12:50:38 -06001909 // Does it need a swizzle inversion? If so, evaluation is inverted;
1910 // operate first on the swizzle base, then apply the swizzle.
1911 spv::Id invertedType = spv::NoType;
1912 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1913 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1914 invertedType = getInvertedSwizzleType(*node->getOperand());
1915
John Kessenich140f3df2015-06-26 16:58:36 -06001916 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001917 if (invertedType != spv::NoType)
1918 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1919 else
1920 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001921
Rex Xufc618912015-09-09 16:42:49 +08001922 spv::Id operand = spv::NoResult;
1923
1924 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1925 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001926 node->getOp() == glslang::EOpAtomicCounter ||
1927 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001928 operand = builder.accessChainGetLValue(); // Special case l-value operands
1929 else
John Kessenich32cfd492016-02-02 12:37:46 -07001930 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001931
John Kessenichead86222018-03-28 18:01:20 -06001932 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001933 TranslateNoContractionDecoration(node->getType().getQualifier()),
1934 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001935
1936 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001937 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001938 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001939
1940 // if not, then possibly an operation
1941 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001942 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001943
1944 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001945 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001946 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001947 builder.addDecoration(result, decorations.nonUniform);
1948 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001949
John Kessenich140f3df2015-06-26 16:58:36 -06001950 builder.clearAccessChain();
1951 builder.setAccessChainRValue(result);
1952
1953 return false; // done with this node
1954 }
1955
1956 // it must be a special case, check...
1957 switch (node->getOp()) {
1958 case glslang::EOpPostIncrement:
1959 case glslang::EOpPostDecrement:
1960 case glslang::EOpPreIncrement:
1961 case glslang::EOpPreDecrement:
1962 {
1963 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001964 spv::Id one = 0;
1965 if (node->getBasicType() == glslang::EbtFloat)
1966 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001967 else if (node->getBasicType() == glslang::EbtDouble)
1968 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001969 else if (node->getBasicType() == glslang::EbtFloat16)
1970 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001971 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1972 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001973 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1974 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001975 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1976 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001977 else
1978 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001979 glslang::TOperator op;
1980 if (node->getOp() == glslang::EOpPreIncrement ||
1981 node->getOp() == glslang::EOpPostIncrement)
1982 op = glslang::EOpAdd;
1983 else
1984 op = glslang::EOpSub;
1985
John Kessenichead86222018-03-28 18:01:20 -06001986 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001987 convertGlslangToSpvType(node->getType()), operand, one,
1988 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001989 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001990
1991 // The result of operation is always stored, but conditionally the
1992 // consumed result. The consumed result is always an r-value.
1993 builder.accessChainStore(result);
1994 builder.clearAccessChain();
1995 if (node->getOp() == glslang::EOpPreIncrement ||
1996 node->getOp() == glslang::EOpPreDecrement)
1997 builder.setAccessChainRValue(result);
1998 else
1999 builder.setAccessChainRValue(operand);
2000 }
2001
2002 return false;
2003
2004 case glslang::EOpEmitStreamVertex:
2005 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2006 return false;
2007 case glslang::EOpEndStreamPrimitive:
2008 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2009 return false;
2010
2011 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002012 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002013 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002014 }
John Kessenich140f3df2015-06-26 16:58:36 -06002015}
2016
2017bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2018{
qining27e04a02016-04-14 16:40:20 -04002019 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2020 if (node->getType().getQualifier().isSpecConstant())
2021 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2022
John Kessenichfc51d282015-08-19 13:34:18 -06002023 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002024 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2025 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002026
2027 // try texturing
2028 result = createImageTextureFunctionCall(node);
2029 if (result != spv::NoResult) {
2030 builder.clearAccessChain();
2031 builder.setAccessChainRValue(result);
2032
2033 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05002034 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08002035#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05002036 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08002037#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05002038 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002039 // "imageStore" is a special case, which has no result
2040 return false;
2041 }
John Kessenichfc51d282015-08-19 13:34:18 -06002042
John Kessenich140f3df2015-06-26 16:58:36 -06002043 glslang::TOperator binOp = glslang::EOpNull;
2044 bool reduceComparison = true;
2045 bool isMatrix = false;
2046 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002047 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002048
2049 assert(node->getOp());
2050
John Kessenichf6640762016-08-01 19:44:00 -06002051 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002052
2053 switch (node->getOp()) {
2054 case glslang::EOpSequence:
2055 {
2056 if (preVisit)
2057 ++sequenceDepth;
2058 else
2059 --sequenceDepth;
2060
2061 if (sequenceDepth == 1) {
2062 // If this is the parent node of all the functions, we want to see them
2063 // early, so all call points have actual SPIR-V functions to reference.
2064 // In all cases, still let the traverser visit the children for us.
2065 makeFunctions(node->getAsAggregate()->getSequence());
2066
John Kessenich6fccb3c2016-09-19 16:01:41 -06002067 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002068 // anything else gets there, so visit out of order, doing them all now.
2069 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2070
John Kessenich6a60c2f2016-12-08 21:01:59 -07002071 // 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 -06002072 // so do them manually.
2073 visitFunctions(node->getAsAggregate()->getSequence());
2074
2075 return false;
2076 }
2077
2078 return true;
2079 }
2080 case glslang::EOpLinkerObjects:
2081 {
2082 if (visit == glslang::EvPreVisit)
2083 linkageOnly = true;
2084 else
2085 linkageOnly = false;
2086
2087 return true;
2088 }
2089 case glslang::EOpComma:
2090 {
2091 // processing from left to right naturally leaves the right-most
2092 // lying around in the access chain
2093 glslang::TIntermSequence& glslangOperands = node->getSequence();
2094 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2095 glslangOperands[i]->traverse(this);
2096
2097 return false;
2098 }
2099 case glslang::EOpFunction:
2100 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002101 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002102 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002103 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002104 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002105 } else {
2106 handleFunctionEntry(node);
2107 }
2108 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002109 if (inEntryPoint)
2110 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002111 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002112 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002113 }
2114
2115 return true;
2116 case glslang::EOpParameters:
2117 // Parameters will have been consumed by EOpFunction processing, but not
2118 // the body, so we still visited the function node's children, making this
2119 // child redundant.
2120 return false;
2121 case glslang::EOpFunctionCall:
2122 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002123 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002124 if (node->isUserDefined())
2125 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002126 // 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 -07002127 if (result) {
2128 builder.clearAccessChain();
2129 builder.setAccessChainRValue(result);
2130 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002131 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002132
2133 return false;
2134 }
2135 case glslang::EOpConstructMat2x2:
2136 case glslang::EOpConstructMat2x3:
2137 case glslang::EOpConstructMat2x4:
2138 case glslang::EOpConstructMat3x2:
2139 case glslang::EOpConstructMat3x3:
2140 case glslang::EOpConstructMat3x4:
2141 case glslang::EOpConstructMat4x2:
2142 case glslang::EOpConstructMat4x3:
2143 case glslang::EOpConstructMat4x4:
2144 case glslang::EOpConstructDMat2x2:
2145 case glslang::EOpConstructDMat2x3:
2146 case glslang::EOpConstructDMat2x4:
2147 case glslang::EOpConstructDMat3x2:
2148 case glslang::EOpConstructDMat3x3:
2149 case glslang::EOpConstructDMat3x4:
2150 case glslang::EOpConstructDMat4x2:
2151 case glslang::EOpConstructDMat4x3:
2152 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002153 case glslang::EOpConstructIMat2x2:
2154 case glslang::EOpConstructIMat2x3:
2155 case glslang::EOpConstructIMat2x4:
2156 case glslang::EOpConstructIMat3x2:
2157 case glslang::EOpConstructIMat3x3:
2158 case glslang::EOpConstructIMat3x4:
2159 case glslang::EOpConstructIMat4x2:
2160 case glslang::EOpConstructIMat4x3:
2161 case glslang::EOpConstructIMat4x4:
2162 case glslang::EOpConstructUMat2x2:
2163 case glslang::EOpConstructUMat2x3:
2164 case glslang::EOpConstructUMat2x4:
2165 case glslang::EOpConstructUMat3x2:
2166 case glslang::EOpConstructUMat3x3:
2167 case glslang::EOpConstructUMat3x4:
2168 case glslang::EOpConstructUMat4x2:
2169 case glslang::EOpConstructUMat4x3:
2170 case glslang::EOpConstructUMat4x4:
2171 case glslang::EOpConstructBMat2x2:
2172 case glslang::EOpConstructBMat2x3:
2173 case glslang::EOpConstructBMat2x4:
2174 case glslang::EOpConstructBMat3x2:
2175 case glslang::EOpConstructBMat3x3:
2176 case glslang::EOpConstructBMat3x4:
2177 case glslang::EOpConstructBMat4x2:
2178 case glslang::EOpConstructBMat4x3:
2179 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002180 case glslang::EOpConstructF16Mat2x2:
2181 case glslang::EOpConstructF16Mat2x3:
2182 case glslang::EOpConstructF16Mat2x4:
2183 case glslang::EOpConstructF16Mat3x2:
2184 case glslang::EOpConstructF16Mat3x3:
2185 case glslang::EOpConstructF16Mat3x4:
2186 case glslang::EOpConstructF16Mat4x2:
2187 case glslang::EOpConstructF16Mat4x3:
2188 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002189 isMatrix = true;
2190 // fall through
2191 case glslang::EOpConstructFloat:
2192 case glslang::EOpConstructVec2:
2193 case glslang::EOpConstructVec3:
2194 case glslang::EOpConstructVec4:
2195 case glslang::EOpConstructDouble:
2196 case glslang::EOpConstructDVec2:
2197 case glslang::EOpConstructDVec3:
2198 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002199 case glslang::EOpConstructFloat16:
2200 case glslang::EOpConstructF16Vec2:
2201 case glslang::EOpConstructF16Vec3:
2202 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002203 case glslang::EOpConstructBool:
2204 case glslang::EOpConstructBVec2:
2205 case glslang::EOpConstructBVec3:
2206 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002207 case glslang::EOpConstructInt8:
2208 case glslang::EOpConstructI8Vec2:
2209 case glslang::EOpConstructI8Vec3:
2210 case glslang::EOpConstructI8Vec4:
2211 case glslang::EOpConstructUint8:
2212 case glslang::EOpConstructU8Vec2:
2213 case glslang::EOpConstructU8Vec3:
2214 case glslang::EOpConstructU8Vec4:
2215 case glslang::EOpConstructInt16:
2216 case glslang::EOpConstructI16Vec2:
2217 case glslang::EOpConstructI16Vec3:
2218 case glslang::EOpConstructI16Vec4:
2219 case glslang::EOpConstructUint16:
2220 case glslang::EOpConstructU16Vec2:
2221 case glslang::EOpConstructU16Vec3:
2222 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002223 case glslang::EOpConstructInt:
2224 case glslang::EOpConstructIVec2:
2225 case glslang::EOpConstructIVec3:
2226 case glslang::EOpConstructIVec4:
2227 case glslang::EOpConstructUint:
2228 case glslang::EOpConstructUVec2:
2229 case glslang::EOpConstructUVec3:
2230 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002231 case glslang::EOpConstructInt64:
2232 case glslang::EOpConstructI64Vec2:
2233 case glslang::EOpConstructI64Vec3:
2234 case glslang::EOpConstructI64Vec4:
2235 case glslang::EOpConstructUint64:
2236 case glslang::EOpConstructU64Vec2:
2237 case glslang::EOpConstructU64Vec3:
2238 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002239 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002240 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002241 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002242 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002243 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002244 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002245 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002246 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002247 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002248 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002249 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002250 else if (node->getOp() == glslang::EOpConstructStruct ||
2251 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2252 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002253 std::vector<spv::Id> constituents;
2254 for (int c = 0; c < (int)arguments.size(); ++c)
2255 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002256 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002257 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002258 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002259 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002260 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002261
2262 builder.clearAccessChain();
2263 builder.setAccessChainRValue(constructed);
2264
2265 return false;
2266 }
2267
2268 // These six are component-wise compares with component-wise results.
2269 // Forward on to createBinaryOperation(), requesting a vector result.
2270 case glslang::EOpLessThan:
2271 case glslang::EOpGreaterThan:
2272 case glslang::EOpLessThanEqual:
2273 case glslang::EOpGreaterThanEqual:
2274 case glslang::EOpVectorEqual:
2275 case glslang::EOpVectorNotEqual:
2276 {
2277 // Map the operation to a binary
2278 binOp = node->getOp();
2279 reduceComparison = false;
2280 switch (node->getOp()) {
2281 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2282 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2283 default: binOp = node->getOp(); break;
2284 }
2285
2286 break;
2287 }
2288 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002289 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002290 binOp = glslang::EOpMul;
2291 break;
2292 case glslang::EOpOuterProduct:
2293 // two vectors multiplied to make a matrix
2294 binOp = glslang::EOpOuterProduct;
2295 break;
2296 case glslang::EOpDot:
2297 {
qining25262b32016-05-06 17:25:16 -04002298 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002299 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002300 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002301 binOp = glslang::EOpMul;
2302 break;
2303 }
2304 case glslang::EOpMod:
2305 // when an aggregate, this is the floating-point mod built-in function,
2306 // which can be emitted by the one in createBinaryOperation()
2307 binOp = glslang::EOpMod;
2308 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002309 case glslang::EOpEmitVertex:
2310 case glslang::EOpEndPrimitive:
2311 case glslang::EOpBarrier:
2312 case glslang::EOpMemoryBarrier:
2313 case glslang::EOpMemoryBarrierAtomicCounter:
2314 case glslang::EOpMemoryBarrierBuffer:
2315 case glslang::EOpMemoryBarrierImage:
2316 case glslang::EOpMemoryBarrierShared:
2317 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002318 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002319 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002320 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002321 case glslang::EOpWorkgroupMemoryBarrier:
2322 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002323 case glslang::EOpSubgroupBarrier:
2324 case glslang::EOpSubgroupMemoryBarrier:
2325 case glslang::EOpSubgroupMemoryBarrierBuffer:
2326 case glslang::EOpSubgroupMemoryBarrierImage:
2327 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002328 noReturnValue = true;
2329 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2330 break;
2331
Jeff Bolz36831c92018-09-05 10:11:41 -05002332 case glslang::EOpAtomicStore:
2333 noReturnValue = true;
2334 // fallthrough
2335 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002336 case glslang::EOpAtomicAdd:
2337 case glslang::EOpAtomicMin:
2338 case glslang::EOpAtomicMax:
2339 case glslang::EOpAtomicAnd:
2340 case glslang::EOpAtomicOr:
2341 case glslang::EOpAtomicXor:
2342 case glslang::EOpAtomicExchange:
2343 case glslang::EOpAtomicCompSwap:
2344 atomic = true;
2345 break;
2346
John Kessenich0d0c6d32017-07-23 16:08:26 -06002347 case glslang::EOpAtomicCounterAdd:
2348 case glslang::EOpAtomicCounterSubtract:
2349 case glslang::EOpAtomicCounterMin:
2350 case glslang::EOpAtomicCounterMax:
2351 case glslang::EOpAtomicCounterAnd:
2352 case glslang::EOpAtomicCounterOr:
2353 case glslang::EOpAtomicCounterXor:
2354 case glslang::EOpAtomicCounterExchange:
2355 case glslang::EOpAtomicCounterCompSwap:
2356 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2357 builder.addCapability(spv::CapabilityAtomicStorageOps);
2358 atomic = true;
2359 break;
2360
Chao Chen3c366992018-09-19 11:41:59 -07002361#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002362 case glslang::EOpIgnoreIntersectionNV:
2363 case glslang::EOpTerminateRayNV:
2364 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002365 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002366 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2367 noReturnValue = true;
2368 break;
2369#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002370 case glslang::EOpCooperativeMatrixLoad:
2371 case glslang::EOpCooperativeMatrixStore:
2372 noReturnValue = true;
2373 break;
Chao Chen3c366992018-09-19 11:41:59 -07002374
John Kessenich140f3df2015-06-26 16:58:36 -06002375 default:
2376 break;
2377 }
2378
2379 //
2380 // See if it maps to a regular operation.
2381 //
John Kessenich140f3df2015-06-26 16:58:36 -06002382 if (binOp != glslang::EOpNull) {
2383 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2384 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2385 assert(left && right);
2386
2387 builder.clearAccessChain();
2388 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002389 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002390
2391 builder.clearAccessChain();
2392 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002393 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002394
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002395 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002396 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002397 TranslateNoContractionDecoration(node->getType().getQualifier()),
2398 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002399 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002400 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002401 left->getType().getBasicType(), reduceComparison);
2402
2403 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002404 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002405 builder.clearAccessChain();
2406 builder.setAccessChainRValue(result);
2407
2408 return false;
2409 }
2410
John Kessenich426394d2015-07-23 10:22:48 -06002411 //
2412 // Create the list of operands.
2413 //
John Kessenich140f3df2015-06-26 16:58:36 -06002414 glslang::TIntermSequence& glslangOperands = node->getSequence();
2415 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002416 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002417 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002418 // special case l-value operands; there are just a few
2419 bool lvalue = false;
2420 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002421 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002422 case glslang::EOpModf:
2423 if (arg == 1)
2424 lvalue = true;
2425 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002426 case glslang::EOpInterpolateAtSample:
2427 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002428#ifdef AMD_EXTENSIONS
2429 case glslang::EOpInterpolateAtVertex:
2430#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002431 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002432 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002433
2434 // Does it need a swizzle inversion? If so, evaluation is inverted;
2435 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002436 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002437 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2438 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2439 }
Rex Xu7a26c172015-12-08 17:12:09 +08002440 break;
Rex Xud4782c12015-09-06 16:30:11 +08002441 case glslang::EOpAtomicAdd:
2442 case glslang::EOpAtomicMin:
2443 case glslang::EOpAtomicMax:
2444 case glslang::EOpAtomicAnd:
2445 case glslang::EOpAtomicOr:
2446 case glslang::EOpAtomicXor:
2447 case glslang::EOpAtomicExchange:
2448 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002449 case glslang::EOpAtomicLoad:
2450 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002451 case glslang::EOpAtomicCounterAdd:
2452 case glslang::EOpAtomicCounterSubtract:
2453 case glslang::EOpAtomicCounterMin:
2454 case glslang::EOpAtomicCounterMax:
2455 case glslang::EOpAtomicCounterAnd:
2456 case glslang::EOpAtomicCounterOr:
2457 case glslang::EOpAtomicCounterXor:
2458 case glslang::EOpAtomicCounterExchange:
2459 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002460 if (arg == 0)
2461 lvalue = true;
2462 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002463 case glslang::EOpAddCarry:
2464 case glslang::EOpSubBorrow:
2465 if (arg == 2)
2466 lvalue = true;
2467 break;
2468 case glslang::EOpUMulExtended:
2469 case glslang::EOpIMulExtended:
2470 if (arg >= 2)
2471 lvalue = true;
2472 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002473 case glslang::EOpCooperativeMatrixLoad:
2474 if (arg == 0 || arg == 1)
2475 lvalue = true;
2476 break;
2477 case glslang::EOpCooperativeMatrixStore:
2478 if (arg == 1)
2479 lvalue = true;
2480 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002481 default:
2482 break;
2483 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002484 builder.clearAccessChain();
2485 if (invertedType != spv::NoType && arg == 0)
2486 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2487 else
2488 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002489
2490 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2491 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2492
2493 if (arg == 1) {
2494 // fold "element" parameter into the access chain
2495 spv::Builder::AccessChain save = builder.getAccessChain();
2496 builder.clearAccessChain();
2497 glslangOperands[2]->traverse(this);
2498
2499 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2500
2501 builder.setAccessChain(save);
2502
2503 // Point to the first element of the array.
2504 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
2505 getBufferReferenceAlignment(glslangOperands[arg]->getAsTyped()->getType()));
2506
2507 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2508 unsigned int alignment = builder.getAccessChain().alignment;
2509
2510 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2511 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2512 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2513 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2514 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2515 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2516 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2517 }
2518
2519 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2520
2521 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2522 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2523 }
2524
2525 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2526 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2527 }
2528 } else if (arg == 2) {
2529 continue;
2530 }
2531 }
2532
John Kessenich140f3df2015-06-26 16:58:36 -06002533 if (lvalue)
2534 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002535 else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002536 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002537 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002538 }
John Kessenich140f3df2015-06-26 16:58:36 -06002539 }
John Kessenich426394d2015-07-23 10:22:48 -06002540
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002541 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002542 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2543 std::vector<spv::IdImmediate> idImmOps;
2544
2545 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2546 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2547 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2548 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2549 // get the pointee type
2550 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2551 assert(builder.isCooperativeMatrixType(typeId));
2552 // do the op
2553 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2554 // store the result to the pointer (out param 'm')
2555 builder.createStore(result, operands[0]);
2556 result = 0;
2557 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2558 std::vector<spv::IdImmediate> idImmOps;
2559
2560 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2561 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2562 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2563 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2564 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2565
2566 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2567 result = 0;
2568 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002569 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002570 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002571 } else {
2572 // Pass through to generic operations.
2573 switch (glslangOperands.size()) {
2574 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002575 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002576 break;
2577 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002578 {
2579 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002580 TranslateNoContractionDecoration(node->getType().getQualifier()),
2581 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002582 result = createUnaryOperation(
2583 node->getOp(), decorations,
2584 resultType(), operands.front(),
2585 glslangOperands[0]->getAsTyped()->getBasicType());
2586 }
John Kessenich426394d2015-07-23 10:22:48 -06002587 break;
2588 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002589 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002590 break;
2591 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002592 if (invertedType)
2593 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002594 }
2595
2596 if (noReturnValue)
2597 return false;
2598
2599 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002600 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002601 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002602 } else {
2603 builder.clearAccessChain();
2604 builder.setAccessChainRValue(result);
2605 return false;
2606 }
2607}
2608
John Kessenich433e9ff2017-01-26 20:31:11 -07002609// This path handles both if-then-else and ?:
2610// The if-then-else has a node type of void, while
2611// ?: has either a void or a non-void node type
2612//
2613// Leaving the result, when not void:
2614// GLSL only has r-values as the result of a :?, but
2615// if we have an l-value, that can be more efficient if it will
2616// become the base of a complex r-value expression, because the
2617// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002618bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2619{
John Kessenich4bee5312018-02-20 21:29:05 -07002620 // See if it simple and safe, or required, to execute both sides.
2621 // Crucially, side effects must be either semantically required or avoided,
2622 // and there are performance trade-offs.
2623 // Return true if required or a good idea (and safe) to execute both sides,
2624 // false otherwise.
2625 const auto bothSidesPolicy = [&]() -> bool {
2626 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002627 if (node->getTrueBlock() == nullptr ||
2628 node->getFalseBlock() == nullptr)
2629 return false;
2630
John Kessenich4bee5312018-02-20 21:29:05 -07002631 // required? (unless we write additional code to look for side effects
2632 // and make performance trade-offs if none are present)
2633 if (!node->getShortCircuit())
2634 return true;
2635
2636 // if not required to execute both, decide based on performance/practicality...
2637
2638 // see if OpSelect can handle it
2639 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2640 node->getBasicType() == glslang::EbtVoid)
2641 return false;
2642
John Kessenich433e9ff2017-01-26 20:31:11 -07002643 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2644 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2645
2646 // return true if a single operand to ? : is okay for OpSelect
2647 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002648 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002649 };
2650
2651 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2652 operandOkay(node->getFalseBlock()->getAsTyped());
2653 };
2654
John Kessenich4bee5312018-02-20 21:29:05 -07002655 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2656 // emit the condition before doing anything with selection
2657 node->getCondition()->traverse(this);
2658 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2659
2660 // Find a way of executing both sides and selecting the right result.
2661 const auto executeBothSides = [&]() -> void {
2662 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002663 node->getTrueBlock()->traverse(this);
2664 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2665 node->getFalseBlock()->traverse(this);
2666 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2667
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002668 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002669
John Kessenich4bee5312018-02-20 21:29:05 -07002670 // done if void
2671 if (node->getBasicType() == glslang::EbtVoid)
2672 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002673
John Kessenich4bee5312018-02-20 21:29:05 -07002674 // emit code to select between trueValue and falseValue
2675
2676 // see if OpSelect can handle it
2677 if (node->getType().isScalar() || node->getType().isVector()) {
2678 // Emit OpSelect for this selection.
2679
2680 // smear condition to vector, if necessary (AST is always scalar)
2681 if (builder.isVector(trueValue))
2682 condition = builder.smearScalar(spv::NoPrecision, condition,
2683 builder.makeVectorType(builder.makeBoolType(),
2684 builder.getNumComponents(trueValue)));
2685
2686 // OpSelect
2687 result = builder.createTriOp(spv::OpSelect,
2688 convertGlslangToSpvType(node->getType()), condition,
2689 trueValue, falseValue);
2690
2691 builder.clearAccessChain();
2692 builder.setAccessChainRValue(result);
2693 } else {
2694 // We need control flow to select the result.
2695 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2696 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2697
2698 // Selection control:
2699 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2700
2701 // make an "if" based on the value created by the condition
2702 spv::Builder::If ifBuilder(condition, control, builder);
2703
2704 // emit the "then" statement
2705 builder.createStore(trueValue, result);
2706 ifBuilder.makeBeginElse();
2707 // emit the "else" statement
2708 builder.createStore(falseValue, result);
2709
2710 // finish off the control flow
2711 ifBuilder.makeEndIf();
2712
2713 builder.clearAccessChain();
2714 builder.setAccessChainLValue(result);
2715 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002716 };
2717
John Kessenich4bee5312018-02-20 21:29:05 -07002718 // Execute the one side needed, as per the condition
2719 const auto executeOneSide = [&]() {
2720 // Always emit control flow.
2721 if (node->getBasicType() != glslang::EbtVoid)
2722 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002723
John Kessenich4bee5312018-02-20 21:29:05 -07002724 // Selection control:
2725 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2726
2727 // make an "if" based on the value created by the condition
2728 spv::Builder::If ifBuilder(condition, control, builder);
2729
2730 // emit the "then" statement
2731 if (node->getTrueBlock() != nullptr) {
2732 node->getTrueBlock()->traverse(this);
2733 if (result != spv::NoResult)
2734 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2735 }
2736
2737 if (node->getFalseBlock() != nullptr) {
2738 ifBuilder.makeBeginElse();
2739 // emit the "else" statement
2740 node->getFalseBlock()->traverse(this);
2741 if (result != spv::NoResult)
2742 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2743 }
2744
2745 // finish off the control flow
2746 ifBuilder.makeEndIf();
2747
2748 if (result != spv::NoResult) {
2749 builder.clearAccessChain();
2750 builder.setAccessChainLValue(result);
2751 }
2752 };
2753
2754 // Try for OpSelect (or a requirement to execute both sides)
2755 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002756 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2757 if (node->getType().getQualifier().isSpecConstant())
2758 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002759 executeBothSides();
2760 } else
2761 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002762
2763 return false;
2764}
2765
2766bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2767{
2768 // emit and get the condition before doing anything with switch
2769 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002770 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002771
Rex Xu57e65922017-07-04 23:23:40 +08002772 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002773 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002774
John Kessenich140f3df2015-06-26 16:58:36 -06002775 // browse the children to sort out code segments
2776 int defaultSegment = -1;
2777 std::vector<TIntermNode*> codeSegments;
2778 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2779 std::vector<int> caseValues;
2780 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2781 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2782 TIntermNode* child = *c;
2783 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002784 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002785 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002786 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002787 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2788 } else
2789 codeSegments.push_back(child);
2790 }
2791
qining25262b32016-05-06 17:25:16 -04002792 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002793 // statements between the last case and the end of the switch statement
2794 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2795 (int)codeSegments.size() == defaultSegment)
2796 codeSegments.push_back(nullptr);
2797
2798 // make the switch statement
2799 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002800 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002801
2802 // emit all the code in the segments
2803 breakForLoop.push(false);
2804 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2805 builder.nextSwitchSegment(segmentBlocks, s);
2806 if (codeSegments[s])
2807 codeSegments[s]->traverse(this);
2808 else
2809 builder.addSwitchBreak();
2810 }
2811 breakForLoop.pop();
2812
2813 builder.endSwitch(segmentBlocks);
2814
2815 return false;
2816}
2817
2818void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2819{
2820 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002821 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002822
2823 builder.clearAccessChain();
2824 builder.setAccessChainRValue(constant);
2825}
2826
2827bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2828{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002829 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002830 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002831
2832 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002833 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2834 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002835
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002836 // Spec requires back edges to target header blocks, and every header block
2837 // must dominate its merge block. Make a header block first to ensure these
2838 // conditions are met. By definition, it will contain OpLoopMerge, followed
2839 // by a block-ending branch. But we don't want to put any other body/test
2840 // instructions in it, since the body/test may have arbitrary instructions,
2841 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002842 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002843 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002844 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002845 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002846 spv::Block& test = builder.makeNewBlock();
2847 builder.createBranch(&test);
2848
2849 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002850 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002851 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002852 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2853
2854 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002855 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002856 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002857 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002858 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002859 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002860
2861 builder.setBuildPoint(&blocks.continue_target);
2862 if (node->getTerminal())
2863 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002864 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002865 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002866 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002867 builder.createBranch(&blocks.body);
2868
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002869 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002870 builder.setBuildPoint(&blocks.body);
2871 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002872 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002873 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002874 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002875
2876 builder.setBuildPoint(&blocks.continue_target);
2877 if (node->getTerminal())
2878 node->getTerminal()->traverse(this);
2879 if (node->getTest()) {
2880 node->getTest()->traverse(this);
2881 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002882 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002883 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002884 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002885 // TODO: unless there was a break/return/discard instruction
2886 // somewhere in the body, this is an infinite loop, so we should
2887 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002888 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002889 }
John Kessenich140f3df2015-06-26 16:58:36 -06002890 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002891 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002892 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002893 return false;
2894}
2895
2896bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2897{
2898 if (node->getExpression())
2899 node->getExpression()->traverse(this);
2900
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002901 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002902
John Kessenich140f3df2015-06-26 16:58:36 -06002903 switch (node->getFlowOp()) {
2904 case glslang::EOpKill:
2905 builder.makeDiscard();
2906 break;
2907 case glslang::EOpBreak:
2908 if (breakForLoop.top())
2909 builder.createLoopExit();
2910 else
2911 builder.addSwitchBreak();
2912 break;
2913 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002914 builder.createLoopContinue();
2915 break;
2916 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002917 if (node->getExpression()) {
2918 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2919 spv::Id returnId = accessChainLoad(glslangReturnType);
2920 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2921 builder.clearAccessChain();
2922 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2923 builder.setAccessChainLValue(copyId);
2924 multiTypeStore(glslangReturnType, returnId);
2925 returnId = builder.createLoad(copyId);
2926 }
2927 builder.makeReturn(false, returnId);
2928 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002929 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002930
2931 builder.clearAccessChain();
2932 break;
2933
2934 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002935 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002936 break;
2937 }
2938
2939 return false;
2940}
2941
2942spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2943{
qining25262b32016-05-06 17:25:16 -04002944 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002945 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002946 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002947 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05002948 spv::Id result = createSpvConstant(*node);
2949 if (result != spv::NoResult)
2950 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06002951 }
2952
2953 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002954 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002955 spv::Id spvType = convertGlslangToSpvType(node->getType());
2956
Rex Xucabbb782017-03-24 13:41:14 +08002957 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2958 node->getType().containsBasicType(glslang::EbtInt16) ||
2959 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002960 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002961 switch (storageClass) {
2962 case spv::StorageClassInput:
2963 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002964 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002965 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002966 break;
2967 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002968 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002969 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002970 break;
2971 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002972 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002973 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2974 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002975 else
2976 builder.addCapability(spv::CapabilityStorageUniform16);
2977 break;
2978 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002979 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06002980 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2981 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2982 break;
2983 default:
2984 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002985 }
2986 }
Rex Xuf89ad982017-04-07 23:22:33 +08002987
John Kessenich312dcfb2018-07-03 13:19:51 -06002988 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2989 node->getType().containsBasicType(glslang::EbtUint8);
2990 if (contains8BitType) {
2991 if (storageClass == spv::StorageClassPushConstant) {
2992 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2993 builder.addCapability(spv::CapabilityStoragePushConstant8);
2994 } else if (storageClass == spv::StorageClassUniform) {
2995 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2996 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01002997 } else if (storageClass == spv::StorageClassStorageBuffer) {
2998 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2999 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
John Kessenich312dcfb2018-07-03 13:19:51 -06003000 }
3001 }
3002
John Kessenich140f3df2015-06-26 16:58:36 -06003003 const char* name = node->getName().c_str();
3004 if (glslang::IsAnonymous(name))
3005 name = "";
3006
3007 return builder.createVariable(storageClass, spvType, name);
3008}
3009
3010// Return type Id of the sampled type.
3011spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3012{
3013 switch (sampler.type) {
3014 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003015#ifdef AMD_EXTENSIONS
3016 case glslang::EbtFloat16:
3017 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3018 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3019 return builder.makeFloatType(16);
3020#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003021 case glslang::EbtInt: return builder.makeIntType(32);
3022 case glslang::EbtUint: return builder.makeUintType(32);
3023 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003024 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003025 return builder.makeFloatType(32);
3026 }
3027}
3028
John Kessenich8c8505c2016-07-26 12:50:38 -06003029// If node is a swizzle operation, return the type that should be used if
3030// the swizzle base is first consumed by another operation, before the swizzle
3031// is applied.
3032spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3033{
John Kessenichecba76f2017-01-06 00:34:48 -07003034 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003035 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3036 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3037 else
3038 return spv::NoType;
3039}
3040
3041// When inverting a swizzle with a parent op, this function
3042// will apply the swizzle operation to a completed parent operation.
3043spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3044{
3045 std::vector<unsigned> swizzle;
3046 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3047 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3048}
3049
John Kessenich8c8505c2016-07-26 12:50:38 -06003050// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3051void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3052{
3053 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3054 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3055 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3056}
3057
John Kessenich3ac051e2015-12-20 11:29:16 -07003058// Convert from a glslang type to an SPV type, by calling into a
3059// recursive version of this function. This establishes the inherited
3060// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003061spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003062{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003063 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003064}
3065
3066// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003067// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003068// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003069spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003070 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3071 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003072{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003073 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003074
3075 switch (type.getBasicType()) {
3076 case glslang::EbtVoid:
3077 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003078 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003079 break;
3080 case glslang::EbtFloat:
3081 spvType = builder.makeFloatType(32);
3082 break;
3083 case glslang::EbtDouble:
3084 spvType = builder.makeFloatType(64);
3085 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003086 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003087 spvType = builder.makeFloatType(16);
3088 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003089 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003090 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3091 // a 32-bit int where non-0 means true.
3092 if (explicitLayout != glslang::ElpNone)
3093 spvType = builder.makeUintType(32);
3094 else
3095 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003096 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003097 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003098 spvType = builder.makeIntType(8);
3099 break;
3100 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003101 spvType = builder.makeUintType(8);
3102 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003103 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003104 spvType = builder.makeIntType(16);
3105 break;
3106 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003107 spvType = builder.makeUintType(16);
3108 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003109 case glslang::EbtInt:
3110 spvType = builder.makeIntType(32);
3111 break;
3112 case glslang::EbtUint:
3113 spvType = builder.makeUintType(32);
3114 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003115 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003116 spvType = builder.makeIntType(64);
3117 break;
3118 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003119 spvType = builder.makeUintType(64);
3120 break;
John Kessenich426394d2015-07-23 10:22:48 -06003121 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003122 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003123 spvType = builder.makeUintType(32);
3124 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003125#ifdef NV_EXTENSIONS
3126 case glslang::EbtAccStructNV:
3127 spvType = builder.makeAccelerationStructureNVType();
3128 break;
3129#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003130 case glslang::EbtSampler:
3131 {
3132 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003133 if (sampler.sampler) {
3134 // pure sampler
3135 spvType = builder.makeSamplerType();
3136 } else {
3137 // an image is present, make its type
3138 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3139 sampler.image ? 2 : 1, TranslateImageFormat(type));
3140 if (sampler.combined) {
3141 // already has both image and sampler, make the combined type
3142 spvType = builder.makeSampledImageType(spvType);
3143 }
John Kessenich55e7d112015-11-15 21:33:39 -07003144 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003145 }
John Kessenich140f3df2015-06-26 16:58:36 -06003146 break;
3147 case glslang::EbtStruct:
3148 case glslang::EbtBlock:
3149 {
3150 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003151 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003152
3153 // Try to share structs for different layouts, but not yet for other
3154 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003155 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003156 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003157 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003158 break;
3159
3160 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003161 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003162 memberRemapper[glslangMembers].resize(glslangMembers->size());
3163 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003164 }
3165 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003166 case glslang::EbtReference:
3167 {
3168 // Make the forward pointer, then recurse to convert the structure type, then
3169 // patch up the forward pointer with a real pointer type.
3170 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3171 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3172 forwardPointers[type.getReferentType()] = forwardId;
3173 }
3174 spvType = forwardPointers[type.getReferentType()];
3175 if (!forwardReferenceOnly) {
3176 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3177 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3178 forwardPointers[type.getReferentType()],
3179 referentType);
3180 }
3181 }
3182 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003183 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003184 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003185 break;
3186 }
3187
3188 if (type.isMatrix())
3189 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3190 else {
3191 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3192 if (type.getVectorSize() > 1)
3193 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3194 }
3195
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003196 if (type.isCoopMat()) {
3197 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3198 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3199 if (type.getBasicType() == glslang::EbtFloat16)
3200 builder.addCapability(spv::CapabilityFloat16);
3201
3202 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3203 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3204 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3205
3206 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3207 }
3208
John Kessenich140f3df2015-06-26 16:58:36 -06003209 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003210 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3211
John Kessenichc9a80832015-09-12 12:17:44 -06003212 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003213 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003214 // We need to decorate array strides for types needing explicit layout, except blocks.
3215 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003216 // Use a dummy glslang type for querying internal strides of
3217 // arrays of arrays, but using just a one-dimensional array.
3218 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003219 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3220 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003221
3222 // Will compute the higher-order strides here, rather than making a whole
3223 // pile of types and doing repetitive recursion on their contents.
3224 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3225 }
John Kessenichf8842e52016-01-04 19:22:56 -07003226
3227 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003228 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003229 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003230 if (stride > 0)
3231 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003232 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003233 }
3234 } else {
3235 // single-dimensional array, and don't yet have stride
3236
John Kessenichf8842e52016-01-04 19:22:56 -07003237 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003238 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3239 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003240 }
John Kessenich31ed4832015-09-09 17:51:38 -06003241
John Kessenichead86222018-03-28 18:01:20 -06003242 // Do the outer dimension, which might not be known for a runtime-sized array.
3243 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3244 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003245 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003246 else {
3247 if (!lastBufferBlockMember) {
3248 builder.addExtension("SPV_EXT_descriptor_indexing");
3249 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3250 }
John Kessenichead86222018-03-28 18:01:20 -06003251 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003252 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003253 if (stride > 0)
3254 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003255 }
3256
3257 return spvType;
3258}
3259
John Kessenich0e737842017-03-24 18:38:16 -06003260// TODO: this functionality should exist at a higher level, in creating the AST
3261//
3262// Identify interface members that don't have their required extension turned on.
3263//
3264bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3265{
Chao Chen3c366992018-09-19 11:41:59 -07003266#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003267 auto& extensions = glslangIntermediate->getRequestedExtensions();
3268
Rex Xubcf291a2017-03-29 23:01:36 +08003269 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3270 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3271 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003272 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3273 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3274 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003275
3276 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3277 if (member.getFieldName() == "gl_ViewportMask" &&
3278 extensions.find("GL_NV_viewport_array2") == extensions.end())
3279 return true;
3280 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3281 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3282 return true;
3283 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3284 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3285 return true;
3286 }
3287#endif
John Kessenich0e737842017-03-24 18:38:16 -06003288
3289 return false;
3290};
3291
John Kessenich6090df02016-06-30 21:18:02 -06003292// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3293// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3294// Mutually recursive with convertGlslangToSpvType().
3295spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3296 const glslang::TTypeList* glslangMembers,
3297 glslang::TLayoutPacking explicitLayout,
3298 const glslang::TQualifier& qualifier)
3299{
3300 // Create a vector of struct types for SPIR-V to consume
3301 std::vector<spv::Id> spvMembers;
3302 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 -06003303 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003304 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3305 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3306 if (glslangMember.hiddenMember()) {
3307 ++memberDelta;
3308 if (type.getBasicType() == glslang::EbtBlock)
3309 memberRemapper[glslangMembers][i] = -1;
3310 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003311 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003312 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003313 if (filterMember(glslangMember))
3314 continue;
3315 }
John Kessenich6090df02016-06-30 21:18:02 -06003316 // modify just this child's view of the qualifier
3317 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3318 InheritQualifiers(memberQualifier, qualifier);
3319
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003320 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003321 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003322 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003323
3324 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003325 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3326 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003327
3328 // Make forward pointers for any pointer members, and create a list of members to
3329 // convert to spirv types after creating the struct.
3330 if (glslangMember.getBasicType() == glslang::EbtReference) {
3331 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3332 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3333 }
3334 spvMembers.push_back(
3335 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3336 } else {
3337 spvMembers.push_back(
3338 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3339 }
John Kessenich6090df02016-06-30 21:18:02 -06003340 }
3341 }
3342
3343 // Make the SPIR-V type
3344 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003345 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003346 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3347
3348 // Decorate it
3349 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3350
John Kessenichd72f4882019-01-16 14:55:37 +07003351 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003352 auto it = deferredForwardPointers[i];
3353 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3354 }
3355
John Kessenich6090df02016-06-30 21:18:02 -06003356 return spvType;
3357}
3358
3359void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3360 const glslang::TTypeList* glslangMembers,
3361 glslang::TLayoutPacking explicitLayout,
3362 const glslang::TQualifier& qualifier,
3363 spv::Id spvType)
3364{
3365 // Name and decorate the non-hidden members
3366 int offset = -1;
3367 int locationOffset = 0; // for use within the members of this struct
3368 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3369 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3370 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003371 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003372 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003373 if (filterMember(glslangMember))
3374 continue;
3375 }
John Kessenich6090df02016-06-30 21:18:02 -06003376
3377 // modify just this child's view of the qualifier
3378 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3379 InheritQualifiers(memberQualifier, qualifier);
3380
3381 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003382 if (member < 0)
3383 continue;
3384
3385 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3386 builder.addMemberDecoration(spvType, member,
3387 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3388 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3389 // Add interpolation and auxiliary storage decorations only to
3390 // top-level members of Input and Output storage classes
3391 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3392 type.getQualifier().storage == glslang::EvqVaryingOut) {
3393 if (type.getBasicType() == glslang::EbtBlock ||
3394 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3395 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3396 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003397#ifdef NV_EXTENSIONS
3398 addMeshNVDecoration(spvType, member, memberQualifier);
3399#endif
John Kessenich6090df02016-06-30 21:18:02 -06003400 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003401 }
3402 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003403
John Kessenich5d610ee2018-03-07 18:05:55 -07003404 if (type.getBasicType() == glslang::EbtBlock &&
3405 qualifier.storage == glslang::EvqBuffer) {
3406 // Add memory decorations only to top-level members of shader storage block
3407 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003408 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003409 for (unsigned int i = 0; i < memory.size(); ++i)
3410 builder.addMemberDecoration(spvType, member, memory[i]);
3411 }
John Kessenich6090df02016-06-30 21:18:02 -06003412
John Kessenich5d610ee2018-03-07 18:05:55 -07003413 // Location assignment was already completed correctly by the front end,
3414 // just track whether a member needs to be decorated.
3415 // Ignore member locations if the container is an array, as that's
3416 // ill-specified and decisions have been made to not allow this.
3417 if (! type.isArray() && memberQualifier.hasLocation())
3418 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003419
John Kessenich5d610ee2018-03-07 18:05:55 -07003420 if (qualifier.hasLocation()) // track for upcoming inheritance
3421 locationOffset += glslangIntermediate->computeTypeLocationSize(
3422 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003423
John Kessenich5d610ee2018-03-07 18:05:55 -07003424 // component, XFB, others
3425 if (glslangMember.getQualifier().hasComponent())
3426 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3427 glslangMember.getQualifier().layoutComponent);
3428 if (glslangMember.getQualifier().hasXfbOffset())
3429 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3430 glslangMember.getQualifier().layoutXfbOffset);
3431 else if (explicitLayout != glslang::ElpNone) {
3432 // figure out what to do with offset, which is accumulating
3433 int nextOffset;
3434 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3435 if (offset >= 0)
3436 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3437 offset = nextOffset;
3438 }
John Kessenich6090df02016-06-30 21:18:02 -06003439
John Kessenich5d610ee2018-03-07 18:05:55 -07003440 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3441 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3442 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003443
John Kessenich5d610ee2018-03-07 18:05:55 -07003444 // built-in variable decorations
3445 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3446 if (builtIn != spv::BuiltInMax)
3447 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003448
John Kessenich5611c6d2018-04-05 11:25:02 -06003449 // nonuniform
3450 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3451
John Kessenichead86222018-03-28 18:01:20 -06003452 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3453 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3454 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3455 memberQualifier.semanticName);
3456 }
3457
chaoc771d89f2017-01-13 01:10:53 -08003458#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003459 if (builtIn == spv::BuiltInLayer) {
3460 // SPV_NV_viewport_array2 extension
3461 if (glslangMember.getQualifier().layoutViewportRelative){
3462 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3463 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3464 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003465 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003466 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3467 builder.addMemberDecoration(spvType, member,
3468 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3469 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3470 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3471 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003472 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003473 }
3474 if (glslangMember.getQualifier().layoutPassthrough) {
3475 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3476 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3477 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3478 }
chaoc771d89f2017-01-13 01:10:53 -08003479#endif
John Kessenich6090df02016-06-30 21:18:02 -06003480 }
3481
3482 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003483 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3484 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003485}
3486
John Kessenich6c292d32016-02-15 20:58:50 -07003487// Turn the expression forming the array size into an id.
3488// This is not quite trivial, because of specialization constants.
3489// Sometimes, a raw constant is turned into an Id, and sometimes
3490// a specialization constant expression is.
3491spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3492{
3493 // First, see if this is sized with a node, meaning a specialization constant:
3494 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3495 if (specNode != nullptr) {
3496 builder.clearAccessChain();
3497 specNode->traverse(this);
3498 return accessChainLoad(specNode->getAsTyped()->getType());
3499 }
qining25262b32016-05-06 17:25:16 -04003500
John Kessenich6c292d32016-02-15 20:58:50 -07003501 // Otherwise, need a compile-time (front end) size, get it:
3502 int size = arraySizes.getDimSize(dim);
3503 assert(size > 0);
3504 return builder.makeUintConstant(size);
3505}
3506
John Kessenich103bef92016-02-08 21:38:15 -07003507// Wrap the builder's accessChainLoad to:
3508// - localize handling of RelaxedPrecision
3509// - use the SPIR-V inferred type instead of another conversion of the glslang type
3510// (avoids unnecessary work and possible type punning for structures)
3511// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003512spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3513{
John Kessenich103bef92016-02-08 21:38:15 -07003514 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003515
3516 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3517 coherentFlags |= TranslateCoherent(type);
3518
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003519 unsigned int alignment = builder.getAccessChain().alignment;
3520 alignment |= getBufferReferenceAlignment(type);
3521
John Kessenich5611c6d2018-04-05 11:25:02 -06003522 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003523 TranslateNonUniformDecoration(type.getQualifier()),
3524 nominalTypeId,
3525 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003526 TranslateMemoryScope(coherentFlags),
3527 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003528
3529 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003530 if (type.getBasicType() == glslang::EbtBool) {
3531 if (builder.isScalarType(nominalTypeId)) {
3532 // Conversion for bool
3533 spv::Id boolType = builder.makeBoolType();
3534 if (nominalTypeId != boolType)
3535 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3536 } else if (builder.isVectorType(nominalTypeId)) {
3537 // Conversion for bvec
3538 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3539 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3540 if (nominalTypeId != bvecType)
3541 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3542 }
3543 }
John Kessenich103bef92016-02-08 21:38:15 -07003544
3545 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003546}
3547
Rex Xu27253232016-02-23 17:51:09 +08003548// Wrap the builder's accessChainStore to:
3549// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003550//
3551// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003552void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3553{
3554 // Need to convert to abstract types when necessary
3555 if (type.getBasicType() == glslang::EbtBool) {
3556 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3557
3558 if (builder.isScalarType(nominalTypeId)) {
3559 // Conversion for bool
3560 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003561 if (nominalTypeId != boolType) {
3562 // keep these outside arguments, for determinant order-of-evaluation
3563 spv::Id one = builder.makeUintConstant(1);
3564 spv::Id zero = builder.makeUintConstant(0);
3565 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3566 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003567 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003568 } else if (builder.isVectorType(nominalTypeId)) {
3569 // Conversion for bvec
3570 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3571 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003572 if (nominalTypeId != bvecType) {
3573 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003574 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3575 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3576 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003577 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003578 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3579 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003580 }
3581 }
3582
Jeff Bolz36831c92018-09-05 10:11:41 -05003583 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3584 coherentFlags |= TranslateCoherent(type);
3585
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003586 unsigned int alignment = builder.getAccessChain().alignment;
3587 alignment |= getBufferReferenceAlignment(type);
3588
Jeff Bolz36831c92018-09-05 10:11:41 -05003589 builder.accessChainStore(rvalue,
3590 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003591 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003592}
3593
John Kessenich4bf71552016-09-02 11:20:21 -06003594// For storing when types match at the glslang level, but not might match at the
3595// SPIR-V level.
3596//
3597// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003598// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003599// as in a member-decorated way.
3600//
3601// NOTE: This function can handle any store request; if it's not special it
3602// simplifies to a simple OpStore.
3603//
3604// Implicitly uses the existing builder.accessChain as the storage target.
3605void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3606{
John Kessenichb3e24e42016-09-11 12:33:43 -06003607 // we only do the complex path here if it's an aggregate
3608 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003609 accessChainStore(type, rValue);
3610 return;
3611 }
3612
John Kessenichb3e24e42016-09-11 12:33:43 -06003613 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003614 spv::Id rType = builder.getTypeId(rValue);
3615 spv::Id lValue = builder.accessChainGetLValue();
3616 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3617 if (lType == rType) {
3618 accessChainStore(type, rValue);
3619 return;
3620 }
3621
John Kessenichb3e24e42016-09-11 12:33:43 -06003622 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003623 // where the two types were the same type in GLSL. This requires member
3624 // by member copy, recursively.
3625
John Kessenichb3e24e42016-09-11 12:33:43 -06003626 // If an array, copy element by element.
3627 if (type.isArray()) {
3628 glslang::TType glslangElementType(type, 0);
3629 spv::Id elementRType = builder.getContainedTypeId(rType);
3630 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3631 // get the source member
3632 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003633
John Kessenichb3e24e42016-09-11 12:33:43 -06003634 // set up the target storage
3635 builder.clearAccessChain();
3636 builder.setAccessChainLValue(lValue);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003637 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), getBufferReferenceAlignment(type));
John Kessenich4bf71552016-09-02 11:20:21 -06003638
John Kessenichb3e24e42016-09-11 12:33:43 -06003639 // store the member
3640 multiTypeStore(glslangElementType, elementRValue);
3641 }
3642 } else {
3643 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003644
John Kessenichb3e24e42016-09-11 12:33:43 -06003645 // loop over structure members
3646 const glslang::TTypeList& members = *type.getStruct();
3647 for (int m = 0; m < (int)members.size(); ++m) {
3648 const glslang::TType& glslangMemberType = *members[m].type;
3649
3650 // get the source member
3651 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3652 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3653
3654 // set up the target storage
3655 builder.clearAccessChain();
3656 builder.setAccessChainLValue(lValue);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003657 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), getBufferReferenceAlignment(type));
John Kessenichb3e24e42016-09-11 12:33:43 -06003658
3659 // store the member
3660 multiTypeStore(glslangMemberType, memberRValue);
3661 }
John Kessenich4bf71552016-09-02 11:20:21 -06003662 }
3663}
3664
John Kessenichf85e8062015-12-19 13:57:10 -07003665// Decide whether or not this type should be
3666// decorated with offsets and strides, and if so
3667// whether std140 or std430 rules should be applied.
3668glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003669{
John Kessenichf85e8062015-12-19 13:57:10 -07003670 // has to be a block
3671 if (type.getBasicType() != glslang::EbtBlock)
3672 return glslang::ElpNone;
3673
Chao Chen3c366992018-09-19 11:41:59 -07003674 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003675 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003676 type.getQualifier().storage != glslang::EvqBuffer &&
3677 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003678 return glslang::ElpNone;
3679
3680 // return the layout to use
3681 switch (type.getQualifier().layoutPacking) {
3682 case glslang::ElpStd140:
3683 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003684 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003685 return type.getQualifier().layoutPacking;
3686 default:
3687 return glslang::ElpNone;
3688 }
John Kessenich31ed4832015-09-09 17:51:38 -06003689}
3690
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003691// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003692int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003693{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003694 int size;
John Kessenich49987892015-12-29 17:11:44 -07003695 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003696 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003697
3698 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003699}
3700
John Kessenich49987892015-12-29 17:11:44 -07003701// 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 -07003702// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003703int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003704{
John Kessenich49987892015-12-29 17:11:44 -07003705 glslang::TType elementType;
3706 elementType.shallowCopy(matrixType);
3707 elementType.clearArraySizes();
3708
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003709 int size;
John Kessenich49987892015-12-29 17:11:44 -07003710 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003711 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003712
3713 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003714}
3715
John Kessenich5e4b1242015-08-06 22:53:06 -06003716// Given a member type of a struct, realign the current offset for it, and compute
3717// the next (not yet aligned) offset for the next member, which will get aligned
3718// on the next call.
3719// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3720// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3721// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003722void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003723 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003724{
3725 // this will get a positive value when deemed necessary
3726 nextOffset = -1;
3727
John Kessenich5e4b1242015-08-06 22:53:06 -06003728 // override anything in currentOffset with user-set offset
3729 if (memberType.getQualifier().hasOffset())
3730 currentOffset = memberType.getQualifier().layoutOffset;
3731
3732 // It could be that current linker usage in glslang updated all the layoutOffset,
3733 // in which case the following code does not matter. But, that's not quite right
3734 // once cross-compilation unit GLSL validation is done, as the original user
3735 // settings are needed in layoutOffset, and then the following will come into play.
3736
John Kessenichf85e8062015-12-19 13:57:10 -07003737 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003738 if (! memberType.getQualifier().hasOffset())
3739 currentOffset = -1;
3740
3741 return;
3742 }
3743
John Kessenichf85e8062015-12-19 13:57:10 -07003744 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003745 if (currentOffset < 0)
3746 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003747
John Kessenich5e4b1242015-08-06 22:53:06 -06003748 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3749 // but possibly not yet correctly aligned.
3750
3751 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003752 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003753 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003754
3755 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003756 // TODO: make this consistent in early phases of code:
3757 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3758 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3759 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003760 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003761 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003762 int dummySize;
3763 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3764 if (componentAlignment <= 4)
3765 memberAlignment = componentAlignment;
3766 }
3767
3768 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003769 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003770
3771 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003772 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003773 glslang::RoundToPow2(currentOffset, 16);
3774
John Kessenich5e4b1242015-08-06 22:53:06 -06003775 nextOffset = currentOffset + memberSize;
3776}
3777
David Netoa901ffe2016-06-08 14:11:40 +01003778void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003779{
David Netoa901ffe2016-06-08 14:11:40 +01003780 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3781 switch (glslangBuiltIn)
3782 {
3783 case glslang::EbvClipDistance:
3784 case glslang::EbvCullDistance:
3785 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003786#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003787 case glslang::EbvViewportMaskNV:
3788 case glslang::EbvSecondaryPositionNV:
3789 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003790 case glslang::EbvPositionPerViewNV:
3791 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003792 case glslang::EbvTaskCountNV:
3793 case glslang::EbvPrimitiveCountNV:
3794 case glslang::EbvPrimitiveIndicesNV:
3795 case glslang::EbvClipDistancePerViewNV:
3796 case glslang::EbvCullDistancePerViewNV:
3797 case glslang::EbvLayerPerViewNV:
3798 case glslang::EbvMeshViewCountNV:
3799 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003800#endif
David Netoa901ffe2016-06-08 14:11:40 +01003801 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3802 // Alternately, we could just call this for any glslang built-in, since the
3803 // capability already guards against duplicates.
3804 TranslateBuiltInDecoration(glslangBuiltIn, false);
3805 break;
3806 default:
3807 // Capabilities were already generated when the struct was declared.
3808 break;
3809 }
John Kessenichebb50532016-05-16 19:22:05 -06003810}
3811
John Kessenich6fccb3c2016-09-19 16:01:41 -06003812bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003813{
John Kessenicheee9d532016-09-19 18:09:30 -06003814 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003815}
3816
John Kessenichd41993d2017-09-10 15:21:05 -06003817// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003818// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3819// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003820bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003821{
John Kessenich6a14f782017-12-04 02:48:10 -07003822 assert(qualifier == glslang::EvqIn ||
3823 qualifier == glslang::EvqOut ||
3824 qualifier == glslang::EvqInOut ||
3825 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003826 return qualifier != glslang::EvqConstReadOnly;
3827}
3828
3829// Is parameter pass-by-original?
3830bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3831 bool implicitThisParam)
3832{
3833 if (implicitThisParam) // implicit this
3834 return true;
3835 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003836 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003837 return paramType.containsOpaque() || // sampler, etc.
3838 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3839}
3840
John Kessenich140f3df2015-06-26 16:58:36 -06003841// Make all the functions, skeletally, without actually visiting their bodies.
3842void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3843{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003844 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003845 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3846 if (paramPrecision != spv::NoPrecision)
3847 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003848 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003849 if (type.getBasicType() == glslang::EbtReference) {
3850 // Original and non-writable params pass the pointer directly and
3851 // use restrict/aliased, others are stored to a pointer in Function
3852 // memory and use RestrictPointer/AliasedPointer.
3853 if (originalParam(type.getQualifier().storage, type, false) ||
3854 !writableParam(type.getQualifier().storage)) {
3855 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
3856 } else {
3857 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
3858 }
3859 }
John Kessenichfad62972017-07-18 02:35:46 -06003860 };
3861
John Kessenich140f3df2015-06-26 16:58:36 -06003862 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3863 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003864 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003865 continue;
3866
3867 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003868 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003869 //
qining25262b32016-05-06 17:25:16 -04003870 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003871 // function. What it is an address of varies:
3872 //
John Kessenich4bf71552016-09-02 11:20:21 -06003873 // - "in" parameters not marked as "const" can be written to without modifying the calling
3874 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003875 //
3876 // - "const in" parameters can just be the r-value, as no writes need occur.
3877 //
John Kessenich4bf71552016-09-02 11:20:21 -06003878 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3879 // 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 -06003880
3881 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003882 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003883 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3884
John Kessenichfad62972017-07-18 02:35:46 -06003885 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3886 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003887
John Kessenichfad62972017-07-18 02:35:46 -06003888 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003889 for (int p = 0; p < (int)parameters.size(); ++p) {
3890 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3891 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003892 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003893 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003894 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003895 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3896 else
John Kessenich4bf71552016-09-02 11:20:21 -06003897 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003898 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003899 paramTypes.push_back(typeId);
3900 }
3901
3902 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003903 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3904 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003905 glslFunction->getName().c_str(), paramTypes,
3906 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003907 if (implicitThis)
3908 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003909
3910 // Track function to emit/call later
3911 functionMap[glslFunction->getName().c_str()] = function;
3912
3913 // Set the parameter id's
3914 for (int p = 0; p < (int)parameters.size(); ++p) {
3915 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3916 // give a name too
3917 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3918 }
3919 }
3920}
3921
3922// Process all the initializers, while skipping the functions and link objects
3923void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3924{
3925 builder.setBuildPoint(shaderEntry->getLastBlock());
3926 for (int i = 0; i < (int)initializers.size(); ++i) {
3927 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3928 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3929
3930 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003931 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003932 initializer->traverse(this);
3933 }
3934 }
3935}
3936
3937// Process all the functions, while skipping initializers.
3938void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3939{
3940 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3941 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003942 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003943 node->traverse(this);
3944 }
3945}
3946
3947void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3948{
qining25262b32016-05-06 17:25:16 -04003949 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003950 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003951 currentFunction = functionMap[node->getName().c_str()];
3952 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003953 builder.setBuildPoint(functionBlock);
3954}
3955
Rex Xu04db3f52015-09-16 11:44:02 +08003956void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003957{
Rex Xufc618912015-09-09 16:42:49 +08003958 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003959
3960 glslang::TSampler sampler = {};
3961 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003962#ifdef AMD_EXTENSIONS
3963 bool f16ShadowCompare = false;
3964#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003965 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003966 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3967 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003968#ifdef AMD_EXTENSIONS
3969 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3970#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003971 }
3972
John Kessenich140f3df2015-06-26 16:58:36 -06003973 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3974 builder.clearAccessChain();
3975 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003976
3977 // Special case l-value operands
3978 bool lvalue = false;
3979 switch (node.getOp()) {
3980 case glslang::EOpImageAtomicAdd:
3981 case glslang::EOpImageAtomicMin:
3982 case glslang::EOpImageAtomicMax:
3983 case glslang::EOpImageAtomicAnd:
3984 case glslang::EOpImageAtomicOr:
3985 case glslang::EOpImageAtomicXor:
3986 case glslang::EOpImageAtomicExchange:
3987 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05003988 case glslang::EOpImageAtomicLoad:
3989 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08003990 if (i == 0)
3991 lvalue = true;
3992 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003993 case glslang::EOpSparseImageLoad:
3994 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3995 lvalue = true;
3996 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003997#ifdef AMD_EXTENSIONS
3998 case glslang::EOpSparseTexture:
3999 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4000 lvalue = true;
4001 break;
4002 case glslang::EOpSparseTextureClamp:
4003 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4004 lvalue = true;
4005 break;
4006 case glslang::EOpSparseTextureLod:
4007 case glslang::EOpSparseTextureOffset:
4008 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4009 lvalue = true;
4010 break;
4011#else
Rex Xu48edadf2015-12-31 16:11:41 +08004012 case glslang::EOpSparseTexture:
4013 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4014 lvalue = true;
4015 break;
4016 case glslang::EOpSparseTextureClamp:
4017 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4018 lvalue = true;
4019 break;
4020 case glslang::EOpSparseTextureLod:
4021 case glslang::EOpSparseTextureOffset:
4022 if (i == 3)
4023 lvalue = true;
4024 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004025#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004026 case glslang::EOpSparseTextureFetch:
4027 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4028 lvalue = true;
4029 break;
4030 case glslang::EOpSparseTextureFetchOffset:
4031 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4032 lvalue = true;
4033 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004034#ifdef AMD_EXTENSIONS
4035 case glslang::EOpSparseTextureLodOffset:
4036 case glslang::EOpSparseTextureGrad:
4037 case glslang::EOpSparseTextureOffsetClamp:
4038 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4039 lvalue = true;
4040 break;
4041 case glslang::EOpSparseTextureGradOffset:
4042 case glslang::EOpSparseTextureGradClamp:
4043 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4044 lvalue = true;
4045 break;
4046 case glslang::EOpSparseTextureGradOffsetClamp:
4047 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4048 lvalue = true;
4049 break;
4050#else
Rex Xu48edadf2015-12-31 16:11:41 +08004051 case glslang::EOpSparseTextureLodOffset:
4052 case glslang::EOpSparseTextureGrad:
4053 case glslang::EOpSparseTextureOffsetClamp:
4054 if (i == 4)
4055 lvalue = true;
4056 break;
4057 case glslang::EOpSparseTextureGradOffset:
4058 case glslang::EOpSparseTextureGradClamp:
4059 if (i == 5)
4060 lvalue = true;
4061 break;
4062 case glslang::EOpSparseTextureGradOffsetClamp:
4063 if (i == 6)
4064 lvalue = true;
4065 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004066#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004067 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004068 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4069 lvalue = true;
4070 break;
4071 case glslang::EOpSparseTextureGatherOffset:
4072 case glslang::EOpSparseTextureGatherOffsets:
4073 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4074 lvalue = true;
4075 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004076#ifdef AMD_EXTENSIONS
4077 case glslang::EOpSparseTextureGatherLod:
4078 if (i == 3)
4079 lvalue = true;
4080 break;
4081 case glslang::EOpSparseTextureGatherLodOffset:
4082 case glslang::EOpSparseTextureGatherLodOffsets:
4083 if (i == 4)
4084 lvalue = true;
4085 break;
Rex Xu129799a2017-07-05 17:23:28 +08004086 case glslang::EOpSparseImageLoadLod:
4087 if (i == 3)
4088 lvalue = true;
4089 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004090#endif
Chao Chen3a137962018-09-19 11:41:27 -07004091#ifdef NV_EXTENSIONS
4092 case glslang::EOpImageSampleFootprintNV:
4093 if (i == 4)
4094 lvalue = true;
4095 break;
4096 case glslang::EOpImageSampleFootprintClampNV:
4097 case glslang::EOpImageSampleFootprintLodNV:
4098 if (i == 5)
4099 lvalue = true;
4100 break;
4101 case glslang::EOpImageSampleFootprintGradNV:
4102 if (i == 6)
4103 lvalue = true;
4104 break;
4105 case glslang::EOpImageSampleFootprintGradClampNV:
4106 if (i == 7)
4107 lvalue = true;
4108 break;
4109#endif
Rex Xufc618912015-09-09 16:42:49 +08004110 default:
4111 break;
4112 }
4113
Rex Xu6b86d492015-09-16 17:48:22 +08004114 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08004115 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08004116 else
John Kessenich32cfd492016-02-02 12:37:46 -07004117 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004118 }
4119}
4120
John Kessenichfc51d282015-08-19 13:34:18 -06004121void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004122{
John Kessenichfc51d282015-08-19 13:34:18 -06004123 builder.clearAccessChain();
4124 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004125 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004126}
John Kessenich140f3df2015-06-26 16:58:36 -06004127
John Kessenichfc51d282015-08-19 13:34:18 -06004128spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4129{
John Kesseniche485c7a2017-05-31 18:50:53 -06004130 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004131 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004132
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004133 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004134
John Kessenichfc51d282015-08-19 13:34:18 -06004135 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004136
4137 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4138 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
4139 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004140#ifdef AMD_EXTENSIONS
4141 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
4142 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4143 : false;
4144#endif
4145
John Kessenichfc51d282015-08-19 13:34:18 -06004146 std::vector<spv::Id> arguments;
4147 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08004148 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06004149 else
4150 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004151 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004152
4153 spv::Builder::TextureParameters params = { };
4154 params.sampler = arguments[0];
4155
Rex Xu04db3f52015-09-16 11:44:02 +08004156 glslang::TCrackedTextureOp cracked;
4157 node->crackTexture(sampler, cracked);
4158
amhagan05506bb2017-06-13 16:53:02 -04004159 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004160
John Kessenichfc51d282015-08-19 13:34:18 -06004161 // Check for queries
4162 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004163 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4164 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004165 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004166
John Kessenichfc51d282015-08-19 13:34:18 -06004167 switch (node->getOp()) {
4168 case glslang::EOpImageQuerySize:
4169 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004170 if (arguments.size() > 1) {
4171 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004172 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004173 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004174 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004175 case glslang::EOpImageQuerySamples:
4176 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004177 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004178 case glslang::EOpTextureQueryLod:
4179 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004180 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004181 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004182 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004183 case glslang::EOpSparseTexelsResident:
4184 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004185 default:
4186 assert(0);
4187 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004188 }
John Kessenich140f3df2015-06-26 16:58:36 -06004189 }
4190
LoopDawg4425f242018-02-18 11:40:01 -07004191 int components = node->getType().getVectorSize();
4192
4193 if (node->getOp() == glslang::EOpTextureFetch) {
4194 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4195 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4196 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4197 // here around e.g. which ones return scalars or other types.
4198 components = 4;
4199 }
4200
4201 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4202
4203 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4204
Rex Xufc618912015-09-09 16:42:49 +08004205 // Check for image functions other than queries
4206 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004207 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004208 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004209 spv::IdImmediate image = { true, *(opIt++) };
4210 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004211
4212 // Handle subpass operations
4213 // TODO: GLSL should change to have the "MS" only on the type rather than the
4214 // built-in function.
4215 if (cracked.subpass) {
4216 // add on the (0,0) coordinate
4217 spv::Id zero = builder.makeIntConstant(0);
4218 std::vector<spv::Id> comps;
4219 comps.push_back(zero);
4220 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004221 spv::IdImmediate coord = { true,
4222 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4223 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07004224 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06004225 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
4226 operands.push_back(imageOperands);
4227 spv::IdImmediate imageOperand = { true, *(opIt++) };
4228 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07004229 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004230 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4231 builder.setPrecision(result, precision);
4232 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004233 }
4234
John Kessenich149afc32018-08-14 13:31:43 -06004235 spv::IdImmediate coord = { true, *(opIt++) };
4236 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004237#ifdef AMD_EXTENSIONS
4238 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4239#else
John Kessenich56bab042015-09-16 10:54:31 -06004240 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004241#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004242 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004243 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004244 mask = mask | spv::ImageOperandsSampleMask;
4245 }
Rex Xu129799a2017-07-05 17:23:28 +08004246#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004247 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004248 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4249 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004250 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004251 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004252#endif
4253 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4254 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4255 if (mask) {
4256 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4257 operands.push_back(imageOperands);
4258 }
4259 if (mask & spv::ImageOperandsSampleMask) {
4260 spv::IdImmediate imageOperand = { true, *opIt++ };
4261 operands.push_back(imageOperand);
4262 }
4263#ifdef AMD_EXTENSIONS
4264 if (mask & spv::ImageOperandsLodMask) {
4265 spv::IdImmediate imageOperand = { true, *opIt++ };
4266 operands.push_back(imageOperand);
4267 }
4268#endif
4269 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4270 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4271 operands.push_back(imageOperand);
4272 }
4273
John Kessenich149afc32018-08-14 13:31:43 -06004274 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004275 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004276
John Kessenich149afc32018-08-14 13:31:43 -06004277 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004278 builder.setPrecision(result[0], precision);
4279
4280 // If needed, add a conversion constructor to the proper size.
4281 if (components != node->getType().getVectorSize())
4282 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4283
4284 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004285#ifdef AMD_EXTENSIONS
4286 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4287#else
John Kessenich56bab042015-09-16 10:54:31 -06004288 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004289#endif
Rex Xu129799a2017-07-05 17:23:28 +08004290
Jeff Bolz36831c92018-09-05 10:11:41 -05004291 // Push the texel value before the operands
4292#ifdef AMD_EXTENSIONS
4293 if (sampler.ms || cracked.lod) {
4294#else
4295 if (sampler.ms) {
4296#endif
John Kessenich149afc32018-08-14 13:31:43 -06004297 spv::IdImmediate texel = { true, *(opIt + 1) };
4298 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004299 } else {
4300 spv::IdImmediate texel = { true, *opIt };
4301 operands.push_back(texel);
4302 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004303
4304 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4305 if (sampler.ms) {
4306 mask = mask | spv::ImageOperandsSampleMask;
4307 }
4308#ifdef AMD_EXTENSIONS
4309 if (cracked.lod) {
4310 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4311 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4312 mask = mask | spv::ImageOperandsLodMask;
4313 }
4314#endif
4315 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4316 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
4317 if (mask) {
4318 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4319 operands.push_back(imageOperands);
4320 }
4321 if (mask & spv::ImageOperandsSampleMask) {
4322 spv::IdImmediate imageOperand = { true, *opIt++ };
4323 operands.push_back(imageOperand);
4324 }
4325#ifdef AMD_EXTENSIONS
4326 if (mask & spv::ImageOperandsLodMask) {
4327 spv::IdImmediate imageOperand = { true, *opIt++ };
4328 operands.push_back(imageOperand);
4329 }
4330#endif
4331 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
4332 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4333 operands.push_back(imageOperand);
4334 }
4335
John Kessenich56bab042015-09-16 10:54:31 -06004336 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004337 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004338 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004339 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004340#ifdef AMD_EXTENSIONS
4341 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
4342#else
Rex Xu5eafa472016-02-19 22:24:03 +08004343 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004344#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004345 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004346 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004347 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4348
Jeff Bolz36831c92018-09-05 10:11:41 -05004349 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004350 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004351 mask = mask | spv::ImageOperandsSampleMask;
4352 }
Rex Xu129799a2017-07-05 17:23:28 +08004353#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004354 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004355 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4356 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4357
Jeff Bolz36831c92018-09-05 10:11:41 -05004358 mask = mask | spv::ImageOperandsLodMask;
4359 }
4360#endif
4361 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4362 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4363 if (mask) {
4364 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004365 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004366 }
4367 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004368 spv::IdImmediate imageOperand = { true, *opIt++ };
4369 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004370 }
4371#ifdef AMD_EXTENSIONS
4372 if (mask & spv::ImageOperandsLodMask) {
4373 spv::IdImmediate imageOperand = { true, *opIt++ };
4374 operands.push_back(imageOperand);
4375 }
Rex Xu129799a2017-07-05 17:23:28 +08004376#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004377 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4378 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4379 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004380 }
4381
4382 // Create the return type that was a special structure
4383 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004384 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004385 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4386 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4387
4388 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4389
4390 // Decode the return type
4391 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4392 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004393 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004394 // Process image atomic operations
4395
4396 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4397 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004398 // For non-MS, the sample value should be 0
4399 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4400 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004401
Jeff Bolz36831c92018-09-05 10:11:41 -05004402 spv::Id resultTypeId;
4403 // imageAtomicStore has a void return type so base the pointer type on
4404 // the type of the value operand.
4405 if (node->getOp() == glslang::EOpImageAtomicStore) {
4406 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4407 } else {
4408 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4409 }
John Kessenich56bab042015-09-16 10:54:31 -06004410 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004411
4412 std::vector<spv::Id> operands;
4413 operands.push_back(pointer);
4414 for (; opIt != arguments.end(); ++opIt)
4415 operands.push_back(*opIt);
4416
John Kessenich8c8505c2016-07-26 12:50:38 -06004417 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004418 }
4419 }
4420
amhagan05506bb2017-06-13 16:53:02 -04004421#ifdef AMD_EXTENSIONS
4422 // Check for fragment mask functions other than queries
4423 if (cracked.fragMask) {
4424 assert(sampler.ms);
4425
4426 auto opIt = arguments.begin();
4427 std::vector<spv::Id> operands;
4428
4429 // Extract the image if necessary
4430 if (builder.isSampledImage(params.sampler))
4431 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4432
4433 operands.push_back(params.sampler);
4434 ++opIt;
4435
4436 if (sampler.isSubpass()) {
4437 // add on the (0,0) coordinate
4438 spv::Id zero = builder.makeIntConstant(0);
4439 std::vector<spv::Id> comps;
4440 comps.push_back(zero);
4441 comps.push_back(zero);
4442 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4443 }
4444
4445 for (; opIt != arguments.end(); ++opIt)
4446 operands.push_back(*opIt);
4447
4448 spv::Op fragMaskOp = spv::OpNop;
4449 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4450 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4451 else if (node->getOp() == glslang::EOpFragmentFetch)
4452 fragMaskOp = spv::OpFragmentFetchAMD;
4453
4454 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4455 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4456 return builder.createOp(fragMaskOp, resultType(), operands);
4457 }
4458#endif
4459
Rex Xufc618912015-09-09 16:42:49 +08004460 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004461 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004462#ifdef NV_EXTENSIONS
4463 bool imageFootprint = node->isImageFootprint();
4464#endif
4465
Rex Xu71519fe2015-11-11 15:35:47 +08004466 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4467
John Kessenichfc51d282015-08-19 13:34:18 -06004468 // check for bias argument
4469 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004470#ifdef AMD_EXTENSIONS
4471 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4472#else
Rex Xu71519fe2015-11-11 15:35:47 +08004473 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004474#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004475 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004476#ifdef AMD_EXTENSIONS
4477 if (cracked.gather)
4478 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004479
4480 if (f16ShadowCompare)
4481 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004482#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004483 if (cracked.offset)
4484 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004485#ifdef AMD_EXTENSIONS
4486 else if (cracked.offsets)
4487 ++nonBiasArgCount;
4488#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004489 if (cracked.grad)
4490 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004491 if (cracked.lodClamp)
4492 ++nonBiasArgCount;
4493 if (sparse)
4494 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004495#ifdef NV_EXTENSIONS
4496 if (imageFootprint)
4497 //Following three extra arguments
4498 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4499 nonBiasArgCount += 3;
4500#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004501 if ((int)arguments.size() > nonBiasArgCount)
4502 bias = true;
4503 }
4504
John Kessenicha5c33d62016-06-02 23:45:21 -06004505 // See if the sampler param should really be just the SPV image part
4506 if (cracked.fetch) {
4507 // a fetch needs to have the image extracted first
4508 if (builder.isSampledImage(params.sampler))
4509 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4510 }
4511
Rex Xu225e0fc2016-11-17 17:47:59 +08004512#ifdef AMD_EXTENSIONS
4513 if (cracked.gather) {
4514 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4515 if (bias || cracked.lod ||
4516 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4517 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004518 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004519 }
4520 }
4521#endif
4522
John Kessenichfc51d282015-08-19 13:34:18 -06004523 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004524
John Kessenichfc51d282015-08-19 13:34:18 -06004525 params.coords = arguments[1];
4526 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004527 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004528
4529 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004530#ifdef AMD_EXTENSIONS
4531 if (cubeCompare || f16ShadowCompare) {
4532#else
Rex Xu48edadf2015-12-31 16:11:41 +08004533 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004534#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004535 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004536 ++extraArgs;
4537 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004538 params.Dref = arguments[2];
4539 ++extraArgs;
4540 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004541 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004542 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004543 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004544 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004545 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004546 dRefComp = builder.getNumComponents(params.coords) - 1;
4547 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004548 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4549 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004550
4551 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004552 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004553 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004554 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004555 } else if (glslangIntermediate->getStage() != EShLangFragment
4556#ifdef NV_EXTENSIONS
4557 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4558 && !(glslangIntermediate->getStage() == EShLangCompute &&
4559 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4560#endif
4561 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004562 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4563 noImplicitLod = true;
4564 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004565
4566 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004567 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004568 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004569 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004570 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004571
4572 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004573 if (cracked.grad) {
4574 params.gradX = arguments[2 + extraArgs];
4575 params.gradY = arguments[3 + extraArgs];
4576 extraArgs += 2;
4577 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004578
4579 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004580 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004581 params.offset = arguments[2 + extraArgs];
4582 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004583 } else if (cracked.offsets) {
4584 params.offsets = arguments[2 + extraArgs];
4585 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004586 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004587
4588 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004589 if (cracked.lodClamp) {
4590 params.lodClamp = arguments[2 + extraArgs];
4591 ++extraArgs;
4592 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004593 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004594 if (sparse) {
4595 params.texelOut = arguments[2 + extraArgs];
4596 ++extraArgs;
4597 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004598
John Kessenich76d4dfc2016-06-16 12:43:23 -06004599 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004600 if (cracked.gather && ! sampler.shadow) {
4601 // default component is 0, if missing, otherwise an argument
4602 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004603 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004604 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004605 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004606 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004607 }
Chao Chen3a137962018-09-19 11:41:27 -07004608#ifdef NV_EXTENSIONS
4609 spv::Id resultStruct = spv::NoResult;
4610 if (imageFootprint) {
4611 //Following three extra arguments
4612 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4613 params.granularity = arguments[2 + extraArgs];
4614 params.coarse = arguments[3 + extraArgs];
4615 resultStruct = arguments[4 + extraArgs];
4616 extraArgs += 3;
4617 }
4618#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004619 // bias
4620 if (bias) {
4621 params.bias = arguments[2 + extraArgs];
4622 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004623 }
John Kessenichfc51d282015-08-19 13:34:18 -06004624
Chao Chen3a137962018-09-19 11:41:27 -07004625#ifdef NV_EXTENSIONS
4626 if (imageFootprint) {
4627 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4628 builder.addCapability(spv::CapabilityImageFootprintNV);
4629
4630
4631 //resultStructType(OpenGL type) contains 5 elements:
4632 //struct gl_TextureFootprint2DNV {
4633 // uvec2 anchor;
4634 // uvec2 offset;
4635 // uvec2 mask;
4636 // uint lod;
4637 // uint granularity;
4638 //};
4639 //or
4640 //struct gl_TextureFootprint3DNV {
4641 // uvec3 anchor;
4642 // uvec3 offset;
4643 // uvec2 mask;
4644 // uint lod;
4645 // uint granularity;
4646 //};
4647 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4648 assert(builder.isStructType(resultStructType));
4649
4650 //resType (SPIR-V type) contains 6 elements:
4651 //Member 0 must be a Boolean type scalar(LOD),
4652 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4653 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4654 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4655 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4656 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4657 std::vector<spv::Id> members;
4658 members.push_back(resultType());
4659 for (int i = 0; i < 5; i++) {
4660 members.push_back(builder.getContainedTypeId(resultStructType, i));
4661 }
4662 spv::Id resType = builder.makeStructType(members, "ResType");
4663
4664 //call ImageFootprintNV
4665 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
4666
4667 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4668 for (int i = 0; i < 5; i++) {
4669 builder.clearAccessChain();
4670 builder.setAccessChainLValue(resultStruct);
4671
4672 //Accessing to a struct we created, no coherent flag is set
4673 spv::Builder::AccessChain::CoherentFlags flags;
4674 flags.clear();
4675
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004676 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004677 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4678 }
4679 return builder.createCompositeExtract(res, resultType(), 0);
4680 }
4681#endif
4682
John Kessenich65336482016-06-16 14:06:26 -06004683 // projective component (might not to move)
4684 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4685 // are divided by the last component of P."
4686 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4687 // unused components will appear after all used components."
4688 if (cracked.proj) {
4689 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4690 int projTargetComp;
4691 switch (sampler.dim) {
4692 case glslang::Esd1D: projTargetComp = 1; break;
4693 case glslang::Esd2D: projTargetComp = 2; break;
4694 case glslang::EsdRect: projTargetComp = 2; break;
4695 default: projTargetComp = projSourceComp; break;
4696 }
4697 // copy the projective coordinate if we have to
4698 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004699 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004700 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4701 projSourceComp);
4702 params.coords = builder.createCompositeInsert(projComp, params.coords,
4703 builder.getTypeId(params.coords), projTargetComp);
4704 }
4705 }
4706
Jeff Bolz36831c92018-09-05 10:11:41 -05004707 // nonprivate
4708 if (imageType.getQualifier().nonprivate) {
4709 params.nonprivate = true;
4710 }
4711
4712 // volatile
4713 if (imageType.getQualifier().volatil) {
4714 params.volatil = true;
4715 }
4716
St0fFa1184dd2018-04-09 21:08:14 +02004717 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004718 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004719 );
LoopDawg4425f242018-02-18 11:40:01 -07004720
4721 if (components != node->getType().getVectorSize())
4722 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4723
4724 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004725}
4726
4727spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4728{
4729 // Grab the function's pointer from the previously created function
4730 spv::Function* function = functionMap[node->getName().c_str()];
4731 if (! function)
4732 return 0;
4733
4734 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4735 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4736
4737 // See comments in makeFunctions() for details about the semantics for parameter passing.
4738 //
4739 // These imply we need a four step process:
4740 // 1. Evaluate the arguments
4741 // 2. Allocate and make copies of in, out, and inout arguments
4742 // 3. Make the call
4743 // 4. Copy back the results
4744
John Kessenichd3ed90b2018-05-04 11:43:03 -06004745 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004746 std::vector<spv::Builder::AccessChain> lValues;
4747 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004748 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004749 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004750 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004751 // build l-value
4752 builder.clearAccessChain();
4753 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004754 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004755 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004756 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004757 // save l-value
4758 lValues.push_back(builder.getAccessChain());
4759 } else {
4760 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004761 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004762 }
4763 }
4764
4765 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4766 // copy the original into that space.
4767 //
4768 // Also, build up the list of actual arguments to pass in for the call
4769 int lValueCount = 0;
4770 int rValueCount = 0;
4771 std::vector<spv::Id> spvArgs;
4772 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4773 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004774 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004775 builder.setAccessChain(lValues[lValueCount]);
4776 arg = builder.accessChainGetLValue();
4777 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004778 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004779 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004780 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004781 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4782 // need to copy the input into output space
4783 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004784 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004785 builder.clearAccessChain();
4786 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004787 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004788 }
4789 ++lValueCount;
4790 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004791 // process r-value, which involves a copy for a type mismatch
4792 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4793 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4794 builder.clearAccessChain();
4795 builder.setAccessChainLValue(argCopy);
4796 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4797 arg = builder.createLoad(argCopy);
4798 } else
4799 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004800 ++rValueCount;
4801 }
4802 spvArgs.push_back(arg);
4803 }
4804
4805 // 3. Make the call.
4806 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004807 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004808
4809 // 4. Copy back out an "out" arguments.
4810 lValueCount = 0;
4811 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004812 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004813 ++lValueCount;
4814 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004815 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4816 spv::Id copy = builder.createLoad(spvArgs[a]);
4817 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004818 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004819 }
4820 ++lValueCount;
4821 }
4822 }
4823
4824 return result;
4825}
4826
4827// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004828spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004829 spv::Id typeId, spv::Id left, spv::Id right,
4830 glslang::TBasicType typeProxy, bool reduceComparison)
4831{
John Kessenich66011cb2018-03-06 16:12:04 -07004832 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4833 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004834 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004835
4836 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004837 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004838 bool comparison = false;
4839
4840 switch (op) {
4841 case glslang::EOpAdd:
4842 case glslang::EOpAddAssign:
4843 if (isFloat)
4844 binOp = spv::OpFAdd;
4845 else
4846 binOp = spv::OpIAdd;
4847 break;
4848 case glslang::EOpSub:
4849 case glslang::EOpSubAssign:
4850 if (isFloat)
4851 binOp = spv::OpFSub;
4852 else
4853 binOp = spv::OpISub;
4854 break;
4855 case glslang::EOpMul:
4856 case glslang::EOpMulAssign:
4857 if (isFloat)
4858 binOp = spv::OpFMul;
4859 else
4860 binOp = spv::OpIMul;
4861 break;
4862 case glslang::EOpVectorTimesScalar:
4863 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004864 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004865 if (builder.isVector(right))
4866 std::swap(left, right);
4867 assert(builder.isScalar(right));
4868 needMatchingVectors = false;
4869 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01004870 } else if (isFloat)
4871 binOp = spv::OpFMul;
4872 else
John Kessenichec43d0a2015-07-04 17:17:31 -06004873 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004874 break;
4875 case glslang::EOpVectorTimesMatrix:
4876 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004877 binOp = spv::OpVectorTimesMatrix;
4878 break;
4879 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004880 binOp = spv::OpMatrixTimesVector;
4881 break;
4882 case glslang::EOpMatrixTimesScalar:
4883 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004884 binOp = spv::OpMatrixTimesScalar;
4885 break;
4886 case glslang::EOpMatrixTimesMatrix:
4887 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004888 binOp = spv::OpMatrixTimesMatrix;
4889 break;
4890 case glslang::EOpOuterProduct:
4891 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004892 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004893 break;
4894
4895 case glslang::EOpDiv:
4896 case glslang::EOpDivAssign:
4897 if (isFloat)
4898 binOp = spv::OpFDiv;
4899 else if (isUnsigned)
4900 binOp = spv::OpUDiv;
4901 else
4902 binOp = spv::OpSDiv;
4903 break;
4904 case glslang::EOpMod:
4905 case glslang::EOpModAssign:
4906 if (isFloat)
4907 binOp = spv::OpFMod;
4908 else if (isUnsigned)
4909 binOp = spv::OpUMod;
4910 else
4911 binOp = spv::OpSMod;
4912 break;
4913 case glslang::EOpRightShift:
4914 case glslang::EOpRightShiftAssign:
4915 if (isUnsigned)
4916 binOp = spv::OpShiftRightLogical;
4917 else
4918 binOp = spv::OpShiftRightArithmetic;
4919 break;
4920 case glslang::EOpLeftShift:
4921 case glslang::EOpLeftShiftAssign:
4922 binOp = spv::OpShiftLeftLogical;
4923 break;
4924 case glslang::EOpAnd:
4925 case glslang::EOpAndAssign:
4926 binOp = spv::OpBitwiseAnd;
4927 break;
4928 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004929 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004930 binOp = spv::OpLogicalAnd;
4931 break;
4932 case glslang::EOpInclusiveOr:
4933 case glslang::EOpInclusiveOrAssign:
4934 binOp = spv::OpBitwiseOr;
4935 break;
4936 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004937 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004938 binOp = spv::OpLogicalOr;
4939 break;
4940 case glslang::EOpExclusiveOr:
4941 case glslang::EOpExclusiveOrAssign:
4942 binOp = spv::OpBitwiseXor;
4943 break;
4944 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004945 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004946 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004947 break;
4948
4949 case glslang::EOpLessThan:
4950 case glslang::EOpGreaterThan:
4951 case glslang::EOpLessThanEqual:
4952 case glslang::EOpGreaterThanEqual:
4953 case glslang::EOpEqual:
4954 case glslang::EOpNotEqual:
4955 case glslang::EOpVectorEqual:
4956 case glslang::EOpVectorNotEqual:
4957 comparison = true;
4958 break;
4959 default:
4960 break;
4961 }
4962
John Kessenich7c1aa102015-10-15 13:29:11 -06004963 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004964 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004965 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06004966 if (builder.isMatrix(left) || builder.isMatrix(right) ||
4967 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004968 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004969
4970 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004971 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004972 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004973
qining25262b32016-05-06 17:25:16 -04004974 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004975 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004976 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004977 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004978 }
4979
4980 if (! comparison)
4981 return 0;
4982
John Kessenich7c1aa102015-10-15 13:29:11 -06004983 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004984
John Kessenich4583b612016-08-07 19:14:22 -06004985 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004986 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4987 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004988 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004989 return result;
4990 }
John Kessenich140f3df2015-06-26 16:58:36 -06004991
4992 switch (op) {
4993 case glslang::EOpLessThan:
4994 if (isFloat)
4995 binOp = spv::OpFOrdLessThan;
4996 else if (isUnsigned)
4997 binOp = spv::OpULessThan;
4998 else
4999 binOp = spv::OpSLessThan;
5000 break;
5001 case glslang::EOpGreaterThan:
5002 if (isFloat)
5003 binOp = spv::OpFOrdGreaterThan;
5004 else if (isUnsigned)
5005 binOp = spv::OpUGreaterThan;
5006 else
5007 binOp = spv::OpSGreaterThan;
5008 break;
5009 case glslang::EOpLessThanEqual:
5010 if (isFloat)
5011 binOp = spv::OpFOrdLessThanEqual;
5012 else if (isUnsigned)
5013 binOp = spv::OpULessThanEqual;
5014 else
5015 binOp = spv::OpSLessThanEqual;
5016 break;
5017 case glslang::EOpGreaterThanEqual:
5018 if (isFloat)
5019 binOp = spv::OpFOrdGreaterThanEqual;
5020 else if (isUnsigned)
5021 binOp = spv::OpUGreaterThanEqual;
5022 else
5023 binOp = spv::OpSGreaterThanEqual;
5024 break;
5025 case glslang::EOpEqual:
5026 case glslang::EOpVectorEqual:
5027 if (isFloat)
5028 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005029 else if (isBool)
5030 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005031 else
5032 binOp = spv::OpIEqual;
5033 break;
5034 case glslang::EOpNotEqual:
5035 case glslang::EOpVectorNotEqual:
5036 if (isFloat)
5037 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005038 else if (isBool)
5039 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005040 else
5041 binOp = spv::OpINotEqual;
5042 break;
5043 default:
5044 break;
5045 }
5046
qining25262b32016-05-06 17:25:16 -04005047 if (binOp != spv::OpNop) {
5048 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005049 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005050 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005051 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005052 }
John Kessenich140f3df2015-06-26 16:58:36 -06005053
5054 return 0;
5055}
5056
John Kessenich04bb8a02015-12-12 12:28:14 -07005057//
5058// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5059// These can be any of:
5060//
5061// matrix * scalar
5062// scalar * matrix
5063// matrix * matrix linear algebraic
5064// matrix * vector
5065// vector * matrix
5066// matrix * matrix componentwise
5067// matrix op matrix op in {+, -, /}
5068// matrix op scalar op in {+, -, /}
5069// scalar op matrix op in {+, -, /}
5070//
John Kessenichead86222018-03-28 18:01:20 -06005071spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5072 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005073{
5074 bool firstClass = true;
5075
5076 // First, handle first-class matrix operations (* and matrix/scalar)
5077 switch (op) {
5078 case spv::OpFDiv:
5079 if (builder.isMatrix(left) && builder.isScalar(right)) {
5080 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005081 spv::Id resultType = builder.getTypeId(right);
5082 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005083 op = spv::OpMatrixTimesScalar;
5084 } else
5085 firstClass = false;
5086 break;
5087 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005088 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005089 std::swap(left, right);
5090 assert(builder.isScalar(right));
5091 break;
5092 case spv::OpVectorTimesMatrix:
5093 assert(builder.isVector(left));
5094 assert(builder.isMatrix(right));
5095 break;
5096 case spv::OpMatrixTimesVector:
5097 assert(builder.isMatrix(left));
5098 assert(builder.isVector(right));
5099 break;
5100 case spv::OpMatrixTimesMatrix:
5101 assert(builder.isMatrix(left));
5102 assert(builder.isMatrix(right));
5103 break;
5104 default:
5105 firstClass = false;
5106 break;
5107 }
5108
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005109 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5110 firstClass = true;
5111
qining25262b32016-05-06 17:25:16 -04005112 if (firstClass) {
5113 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005114 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005115 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005116 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005117 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005118
LoopDawg592860c2016-06-09 08:57:35 -06005119 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005120 // The result type of all of them is the same type as the (a) matrix operand.
5121 // The algorithm is to:
5122 // - break the matrix(es) into vectors
5123 // - smear any scalar to a vector
5124 // - do vector operations
5125 // - make a matrix out the vector results
5126 switch (op) {
5127 case spv::OpFAdd:
5128 case spv::OpFSub:
5129 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005130 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005131 case spv::OpFMul:
5132 {
5133 // one time set up...
5134 bool leftMat = builder.isMatrix(left);
5135 bool rightMat = builder.isMatrix(right);
5136 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5137 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5138 spv::Id scalarType = builder.getScalarTypeId(typeId);
5139 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5140 std::vector<spv::Id> results;
5141 spv::Id smearVec = spv::NoResult;
5142 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005143 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005144 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005145 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005146
5147 // do each vector op
5148 for (unsigned int c = 0; c < numCols; ++c) {
5149 std::vector<unsigned int> indexes;
5150 indexes.push_back(c);
5151 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5152 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005153 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005154 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005155 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005156 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005157 }
5158
5159 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005160 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005161 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005162 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005163 }
5164 default:
5165 assert(0);
5166 return spv::NoResult;
5167 }
5168}
5169
John Kessenichead86222018-03-28 18:01:20 -06005170spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
5171 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005172{
5173 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005174 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005175 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005176 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5177 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005178
5179 switch (op) {
5180 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005181 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005182 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005183 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005184 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005185 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005186 unaryOp = spv::OpSNegate;
5187 break;
5188
5189 case glslang::EOpLogicalNot:
5190 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005191 unaryOp = spv::OpLogicalNot;
5192 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005193 case glslang::EOpBitwiseNot:
5194 unaryOp = spv::OpNot;
5195 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005196
John Kessenich140f3df2015-06-26 16:58:36 -06005197 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005198 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005199 break;
5200 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005201 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005202 break;
5203 case glslang::EOpTranspose:
5204 unaryOp = spv::OpTranspose;
5205 break;
5206
5207 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005208 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005209 break;
5210 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005211 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005212 break;
5213 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005214 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005215 break;
5216 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005217 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005218 break;
5219 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005220 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005221 break;
5222 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005223 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005224 break;
5225 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005226 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005227 break;
5228 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005229 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005230 break;
5231
5232 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005233 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005234 break;
5235 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005236 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005237 break;
5238 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005239 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005240 break;
5241 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005242 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005243 break;
5244 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005245 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005246 break;
5247 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005248 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005249 break;
5250
5251 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005252 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005253 break;
5254 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005255 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005256 break;
5257
5258 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005259 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005260 break;
5261 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005262 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005263 break;
5264 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005265 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005266 break;
5267 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005268 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005269 break;
5270 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005271 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005272 break;
5273 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005274 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005275 break;
5276
5277 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005278 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005279 break;
5280 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005281 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005282 break;
5283 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005284 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005285 break;
5286 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005287 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005288 break;
5289 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005290 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005291 break;
5292 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005293 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005294 break;
5295
5296 case glslang::EOpIsNan:
5297 unaryOp = spv::OpIsNan;
5298 break;
5299 case glslang::EOpIsInf:
5300 unaryOp = spv::OpIsInf;
5301 break;
LoopDawg592860c2016-06-09 08:57:35 -06005302 case glslang::EOpIsFinite:
5303 unaryOp = spv::OpIsFinite;
5304 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005305
Rex Xucbc426e2015-12-15 16:03:10 +08005306 case glslang::EOpFloatBitsToInt:
5307 case glslang::EOpFloatBitsToUint:
5308 case glslang::EOpIntBitsToFloat:
5309 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005310 case glslang::EOpDoubleBitsToInt64:
5311 case glslang::EOpDoubleBitsToUint64:
5312 case glslang::EOpInt64BitsToDouble:
5313 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005314 case glslang::EOpFloat16BitsToInt16:
5315 case glslang::EOpFloat16BitsToUint16:
5316 case glslang::EOpInt16BitsToFloat16:
5317 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005318 unaryOp = spv::OpBitcast;
5319 break;
5320
John Kessenich140f3df2015-06-26 16:58:36 -06005321 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005322 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005323 break;
5324 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005325 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005326 break;
5327 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005328 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005329 break;
5330 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005331 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005332 break;
5333 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005334 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005335 break;
5336 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005337 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005338 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005339 case glslang::EOpPackSnorm4x8:
5340 libCall = spv::GLSLstd450PackSnorm4x8;
5341 break;
5342 case glslang::EOpUnpackSnorm4x8:
5343 libCall = spv::GLSLstd450UnpackSnorm4x8;
5344 break;
5345 case glslang::EOpPackUnorm4x8:
5346 libCall = spv::GLSLstd450PackUnorm4x8;
5347 break;
5348 case glslang::EOpUnpackUnorm4x8:
5349 libCall = spv::GLSLstd450UnpackUnorm4x8;
5350 break;
5351 case glslang::EOpPackDouble2x32:
5352 libCall = spv::GLSLstd450PackDouble2x32;
5353 break;
5354 case glslang::EOpUnpackDouble2x32:
5355 libCall = spv::GLSLstd450UnpackDouble2x32;
5356 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005357
Rex Xu8ff43de2016-04-22 16:51:45 +08005358 case glslang::EOpPackInt2x32:
5359 case glslang::EOpUnpackInt2x32:
5360 case glslang::EOpPackUint2x32:
5361 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005362 case glslang::EOpPack16:
5363 case glslang::EOpPack32:
5364 case glslang::EOpPack64:
5365 case glslang::EOpUnpack32:
5366 case glslang::EOpUnpack16:
5367 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005368 case glslang::EOpPackInt2x16:
5369 case glslang::EOpUnpackInt2x16:
5370 case glslang::EOpPackUint2x16:
5371 case glslang::EOpUnpackUint2x16:
5372 case glslang::EOpPackInt4x16:
5373 case glslang::EOpUnpackInt4x16:
5374 case glslang::EOpPackUint4x16:
5375 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005376 case glslang::EOpPackFloat2x16:
5377 case glslang::EOpUnpackFloat2x16:
5378 unaryOp = spv::OpBitcast;
5379 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005380
John Kessenich140f3df2015-06-26 16:58:36 -06005381 case glslang::EOpDPdx:
5382 unaryOp = spv::OpDPdx;
5383 break;
5384 case glslang::EOpDPdy:
5385 unaryOp = spv::OpDPdy;
5386 break;
5387 case glslang::EOpFwidth:
5388 unaryOp = spv::OpFwidth;
5389 break;
5390 case glslang::EOpDPdxFine:
5391 unaryOp = spv::OpDPdxFine;
5392 break;
5393 case glslang::EOpDPdyFine:
5394 unaryOp = spv::OpDPdyFine;
5395 break;
5396 case glslang::EOpFwidthFine:
5397 unaryOp = spv::OpFwidthFine;
5398 break;
5399 case glslang::EOpDPdxCoarse:
5400 unaryOp = spv::OpDPdxCoarse;
5401 break;
5402 case glslang::EOpDPdyCoarse:
5403 unaryOp = spv::OpDPdyCoarse;
5404 break;
5405 case glslang::EOpFwidthCoarse:
5406 unaryOp = spv::OpFwidthCoarse;
5407 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005408 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005409#ifdef AMD_EXTENSIONS
5410 if (typeProxy == glslang::EbtFloat16)
5411 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5412#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005413 libCall = spv::GLSLstd450InterpolateAtCentroid;
5414 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005415 case glslang::EOpAny:
5416 unaryOp = spv::OpAny;
5417 break;
5418 case glslang::EOpAll:
5419 unaryOp = spv::OpAll;
5420 break;
5421
5422 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005423 if (isFloat)
5424 libCall = spv::GLSLstd450FAbs;
5425 else
5426 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005427 break;
5428 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005429 if (isFloat)
5430 libCall = spv::GLSLstd450FSign;
5431 else
5432 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005433 break;
5434
John Kessenichfc51d282015-08-19 13:34:18 -06005435 case glslang::EOpAtomicCounterIncrement:
5436 case glslang::EOpAtomicCounterDecrement:
5437 case glslang::EOpAtomicCounter:
5438 {
5439 // Handle all of the atomics in one place, in createAtomicOperation()
5440 std::vector<spv::Id> operands;
5441 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005442 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005443 }
5444
John Kessenichfc51d282015-08-19 13:34:18 -06005445 case glslang::EOpBitFieldReverse:
5446 unaryOp = spv::OpBitReverse;
5447 break;
5448 case glslang::EOpBitCount:
5449 unaryOp = spv::OpBitCount;
5450 break;
5451 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005452 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005453 break;
5454 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005455 if (isUnsigned)
5456 libCall = spv::GLSLstd450FindUMsb;
5457 else
5458 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005459 break;
5460
Rex Xu574ab042016-04-14 16:53:07 +08005461 case glslang::EOpBallot:
5462 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005463 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005464 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005465 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005466#ifdef AMD_EXTENSIONS
5467 case glslang::EOpMinInvocations:
5468 case glslang::EOpMaxInvocations:
5469 case glslang::EOpAddInvocations:
5470 case glslang::EOpMinInvocationsNonUniform:
5471 case glslang::EOpMaxInvocationsNonUniform:
5472 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005473 case glslang::EOpMinInvocationsInclusiveScan:
5474 case glslang::EOpMaxInvocationsInclusiveScan:
5475 case glslang::EOpAddInvocationsInclusiveScan:
5476 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5477 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5478 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5479 case glslang::EOpMinInvocationsExclusiveScan:
5480 case glslang::EOpMaxInvocationsExclusiveScan:
5481 case glslang::EOpAddInvocationsExclusiveScan:
5482 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5483 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5484 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005485#endif
Rex Xu51596642016-09-21 18:56:12 +08005486 {
5487 std::vector<spv::Id> operands;
5488 operands.push_back(operand);
5489 return createInvocationsOperation(op, typeId, operands, typeProxy);
5490 }
John Kessenich66011cb2018-03-06 16:12:04 -07005491 case glslang::EOpSubgroupAll:
5492 case glslang::EOpSubgroupAny:
5493 case glslang::EOpSubgroupAllEqual:
5494 case glslang::EOpSubgroupBroadcastFirst:
5495 case glslang::EOpSubgroupBallot:
5496 case glslang::EOpSubgroupInverseBallot:
5497 case glslang::EOpSubgroupBallotBitCount:
5498 case glslang::EOpSubgroupBallotInclusiveBitCount:
5499 case glslang::EOpSubgroupBallotExclusiveBitCount:
5500 case glslang::EOpSubgroupBallotFindLSB:
5501 case glslang::EOpSubgroupBallotFindMSB:
5502 case glslang::EOpSubgroupAdd:
5503 case glslang::EOpSubgroupMul:
5504 case glslang::EOpSubgroupMin:
5505 case glslang::EOpSubgroupMax:
5506 case glslang::EOpSubgroupAnd:
5507 case glslang::EOpSubgroupOr:
5508 case glslang::EOpSubgroupXor:
5509 case glslang::EOpSubgroupInclusiveAdd:
5510 case glslang::EOpSubgroupInclusiveMul:
5511 case glslang::EOpSubgroupInclusiveMin:
5512 case glslang::EOpSubgroupInclusiveMax:
5513 case glslang::EOpSubgroupInclusiveAnd:
5514 case glslang::EOpSubgroupInclusiveOr:
5515 case glslang::EOpSubgroupInclusiveXor:
5516 case glslang::EOpSubgroupExclusiveAdd:
5517 case glslang::EOpSubgroupExclusiveMul:
5518 case glslang::EOpSubgroupExclusiveMin:
5519 case glslang::EOpSubgroupExclusiveMax:
5520 case glslang::EOpSubgroupExclusiveAnd:
5521 case glslang::EOpSubgroupExclusiveOr:
5522 case glslang::EOpSubgroupExclusiveXor:
5523 case glslang::EOpSubgroupQuadSwapHorizontal:
5524 case glslang::EOpSubgroupQuadSwapVertical:
5525 case glslang::EOpSubgroupQuadSwapDiagonal: {
5526 std::vector<spv::Id> operands;
5527 operands.push_back(operand);
5528 return createSubgroupOperation(op, typeId, operands, typeProxy);
5529 }
Rex Xu9d93a232016-05-05 12:30:44 +08005530#ifdef AMD_EXTENSIONS
5531 case glslang::EOpMbcnt:
5532 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5533 libCall = spv::MbcntAMD;
5534 break;
5535
5536 case glslang::EOpCubeFaceIndex:
5537 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5538 libCall = spv::CubeFaceIndexAMD;
5539 break;
5540
5541 case glslang::EOpCubeFaceCoord:
5542 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5543 libCall = spv::CubeFaceCoordAMD;
5544 break;
5545#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005546#ifdef NV_EXTENSIONS
5547 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005548 unaryOp = spv::OpGroupNonUniformPartitionNV;
5549 break;
5550#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005551 case glslang::EOpConstructReference:
5552 unaryOp = spv::OpBitcast;
5553 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005554 default:
5555 return 0;
5556 }
5557
5558 spv::Id id;
5559 if (libCall >= 0) {
5560 std::vector<spv::Id> args;
5561 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005562 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005563 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005564 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005565 }
John Kessenich140f3df2015-06-26 16:58:36 -06005566
John Kessenichead86222018-03-28 18:01:20 -06005567 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005568 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005569 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005570}
5571
John Kessenich7a53f762016-01-20 11:19:27 -07005572// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005573spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5574 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005575{
5576 // Handle unary operations vector by vector.
5577 // The result type is the same type as the original type.
5578 // The algorithm is to:
5579 // - break the matrix into vectors
5580 // - apply the operation to each vector
5581 // - make a matrix out the vector results
5582
5583 // get the types sorted out
5584 int numCols = builder.getNumColumns(operand);
5585 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005586 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5587 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005588 std::vector<spv::Id> results;
5589
5590 // do each vector op
5591 for (int c = 0; c < numCols; ++c) {
5592 std::vector<unsigned int> indexes;
5593 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005594 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5595 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005596 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005597 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005598 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005599 }
5600
5601 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005602 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005603 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005604 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005605}
5606
John Kessenichad7645f2018-06-04 19:11:25 -06005607// For converting integers where both the bitwidth and the signedness could
5608// change, but only do the width change here. The caller is still responsible
5609// for the signedness conversion.
5610spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005611{
John Kessenichad7645f2018-06-04 19:11:25 -06005612 // Get the result type width, based on the type to convert to.
5613 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005614 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005615 case glslang::EOpConvInt16ToUint8:
5616 case glslang::EOpConvIntToUint8:
5617 case glslang::EOpConvInt64ToUint8:
5618 case glslang::EOpConvUint16ToInt8:
5619 case glslang::EOpConvUintToInt8:
5620 case glslang::EOpConvUint64ToInt8:
5621 width = 8;
5622 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005623 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005624 case glslang::EOpConvIntToUint16:
5625 case glslang::EOpConvInt64ToUint16:
5626 case glslang::EOpConvUint8ToInt16:
5627 case glslang::EOpConvUintToInt16:
5628 case glslang::EOpConvUint64ToInt16:
5629 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005630 break;
5631 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005632 case glslang::EOpConvInt16ToUint:
5633 case glslang::EOpConvInt64ToUint:
5634 case glslang::EOpConvUint8ToInt:
5635 case glslang::EOpConvUint16ToInt:
5636 case glslang::EOpConvUint64ToInt:
5637 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005638 break;
5639 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005640 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005641 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005642 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005643 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005644 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005645 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005646 break;
5647
5648 default:
5649 assert(false && "Default missing");
5650 break;
5651 }
5652
John Kessenichad7645f2018-06-04 19:11:25 -06005653 // Get the conversion operation and result type,
5654 // based on the target width, but the source type.
5655 spv::Id type = spv::NoType;
5656 spv::Op convOp = spv::OpNop;
5657 switch(op) {
5658 case glslang::EOpConvInt8ToUint16:
5659 case glslang::EOpConvInt8ToUint:
5660 case glslang::EOpConvInt8ToUint64:
5661 case glslang::EOpConvInt16ToUint8:
5662 case glslang::EOpConvInt16ToUint:
5663 case glslang::EOpConvInt16ToUint64:
5664 case glslang::EOpConvIntToUint8:
5665 case glslang::EOpConvIntToUint16:
5666 case glslang::EOpConvIntToUint64:
5667 case glslang::EOpConvInt64ToUint8:
5668 case glslang::EOpConvInt64ToUint16:
5669 case glslang::EOpConvInt64ToUint:
5670 convOp = spv::OpSConvert;
5671 type = builder.makeIntType(width);
5672 break;
5673 default:
5674 convOp = spv::OpUConvert;
5675 type = builder.makeUintType(width);
5676 break;
5677 }
5678
John Kessenich66011cb2018-03-06 16:12:04 -07005679 if (vectorSize > 0)
5680 type = builder.makeVectorType(type, vectorSize);
5681
John Kessenichad7645f2018-06-04 19:11:25 -06005682 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005683}
5684
John Kessenichead86222018-03-28 18:01:20 -06005685spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5686 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005687{
5688 spv::Op convOp = spv::OpNop;
5689 spv::Id zero = 0;
5690 spv::Id one = 0;
5691
5692 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5693
5694 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005695 case glslang::EOpConvInt8ToBool:
5696 case glslang::EOpConvUint8ToBool:
5697 zero = builder.makeUint8Constant(0);
5698 zero = makeSmearedConstant(zero, vectorSize);
5699 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005700 case glslang::EOpConvInt16ToBool:
5701 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005702 zero = builder.makeUint16Constant(0);
5703 zero = makeSmearedConstant(zero, vectorSize);
5704 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5705 case glslang::EOpConvIntToBool:
5706 case glslang::EOpConvUintToBool:
5707 zero = builder.makeUintConstant(0);
5708 zero = makeSmearedConstant(zero, vectorSize);
5709 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5710 case glslang::EOpConvInt64ToBool:
5711 case glslang::EOpConvUint64ToBool:
5712 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005713 zero = makeSmearedConstant(zero, vectorSize);
5714 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5715
5716 case glslang::EOpConvFloatToBool:
5717 zero = builder.makeFloatConstant(0.0F);
5718 zero = makeSmearedConstant(zero, vectorSize);
5719 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5720
5721 case glslang::EOpConvDoubleToBool:
5722 zero = builder.makeDoubleConstant(0.0);
5723 zero = makeSmearedConstant(zero, vectorSize);
5724 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5725
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005726 case glslang::EOpConvFloat16ToBool:
5727 zero = builder.makeFloat16Constant(0.0F);
5728 zero = makeSmearedConstant(zero, vectorSize);
5729 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005730
John Kessenich140f3df2015-06-26 16:58:36 -06005731 case glslang::EOpConvBoolToFloat:
5732 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005733 zero = builder.makeFloatConstant(0.0F);
5734 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005735 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005736
John Kessenich140f3df2015-06-26 16:58:36 -06005737 case glslang::EOpConvBoolToDouble:
5738 convOp = spv::OpSelect;
5739 zero = builder.makeDoubleConstant(0.0);
5740 one = builder.makeDoubleConstant(1.0);
5741 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005742
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005743 case glslang::EOpConvBoolToFloat16:
5744 convOp = spv::OpSelect;
5745 zero = builder.makeFloat16Constant(0.0F);
5746 one = builder.makeFloat16Constant(1.0F);
5747 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005748
5749 case glslang::EOpConvBoolToInt8:
5750 zero = builder.makeInt8Constant(0);
5751 one = builder.makeInt8Constant(1);
5752 convOp = spv::OpSelect;
5753 break;
5754
5755 case glslang::EOpConvBoolToUint8:
5756 zero = builder.makeUint8Constant(0);
5757 one = builder.makeUint8Constant(1);
5758 convOp = spv::OpSelect;
5759 break;
5760
5761 case glslang::EOpConvBoolToInt16:
5762 zero = builder.makeInt16Constant(0);
5763 one = builder.makeInt16Constant(1);
5764 convOp = spv::OpSelect;
5765 break;
5766
5767 case glslang::EOpConvBoolToUint16:
5768 zero = builder.makeUint16Constant(0);
5769 one = builder.makeUint16Constant(1);
5770 convOp = spv::OpSelect;
5771 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005772
John Kessenich140f3df2015-06-26 16:58:36 -06005773 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005774 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005775 if (op == glslang::EOpConvBoolToInt64)
5776 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005777 else
5778 zero = builder.makeIntConstant(0);
5779
5780 if (op == glslang::EOpConvBoolToInt64)
5781 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005782 else
5783 one = builder.makeIntConstant(1);
5784
John Kessenich140f3df2015-06-26 16:58:36 -06005785 convOp = spv::OpSelect;
5786 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005787
John Kessenich140f3df2015-06-26 16:58:36 -06005788 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005789 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005790 if (op == glslang::EOpConvBoolToUint64)
5791 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005792 else
5793 zero = builder.makeUintConstant(0);
5794
5795 if (op == glslang::EOpConvBoolToUint64)
5796 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005797 else
5798 one = builder.makeUintConstant(1);
5799
John Kessenich140f3df2015-06-26 16:58:36 -06005800 convOp = spv::OpSelect;
5801 break;
5802
John Kessenich66011cb2018-03-06 16:12:04 -07005803 case glslang::EOpConvInt8ToFloat16:
5804 case glslang::EOpConvInt8ToFloat:
5805 case glslang::EOpConvInt8ToDouble:
5806 case glslang::EOpConvInt16ToFloat16:
5807 case glslang::EOpConvInt16ToFloat:
5808 case glslang::EOpConvInt16ToDouble:
5809 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005810 case glslang::EOpConvIntToFloat:
5811 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005812 case glslang::EOpConvInt64ToFloat:
5813 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005814 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005815 convOp = spv::OpConvertSToF;
5816 break;
5817
John Kessenich66011cb2018-03-06 16:12:04 -07005818 case glslang::EOpConvUint8ToFloat16:
5819 case glslang::EOpConvUint8ToFloat:
5820 case glslang::EOpConvUint8ToDouble:
5821 case glslang::EOpConvUint16ToFloat16:
5822 case glslang::EOpConvUint16ToFloat:
5823 case glslang::EOpConvUint16ToDouble:
5824 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005825 case glslang::EOpConvUintToFloat:
5826 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005827 case glslang::EOpConvUint64ToFloat:
5828 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005829 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005830 convOp = spv::OpConvertUToF;
5831 break;
5832
5833 case glslang::EOpConvDoubleToFloat:
5834 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005835 case glslang::EOpConvDoubleToFloat16:
5836 case glslang::EOpConvFloat16ToDouble:
5837 case glslang::EOpConvFloatToFloat16:
5838 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005839 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005840 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005841 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005842 break;
5843
John Kessenich66011cb2018-03-06 16:12:04 -07005844 case glslang::EOpConvFloat16ToInt8:
5845 case glslang::EOpConvFloatToInt8:
5846 case glslang::EOpConvDoubleToInt8:
5847 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005848 case glslang::EOpConvFloatToInt16:
5849 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005850 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005851 case glslang::EOpConvFloatToInt:
5852 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005853 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005854 case glslang::EOpConvFloatToInt64:
5855 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005856 convOp = spv::OpConvertFToS;
5857 break;
5858
John Kessenich66011cb2018-03-06 16:12:04 -07005859 case glslang::EOpConvUint8ToInt8:
5860 case glslang::EOpConvInt8ToUint8:
5861 case glslang::EOpConvUint16ToInt16:
5862 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005863 case glslang::EOpConvUintToInt:
5864 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005865 case glslang::EOpConvUint64ToInt64:
5866 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005867 if (builder.isInSpecConstCodeGenMode()) {
5868 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005869 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5870 zero = builder.makeUint8Constant(0);
5871 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005872 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005873 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5874 zero = builder.makeUint64Constant(0);
5875 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005876 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005877 }
qining189b2032016-04-12 23:16:20 -04005878 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005879 // Use OpIAdd, instead of OpBitcast to do the conversion when
5880 // generating for OpSpecConstantOp instruction.
5881 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5882 }
5883 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005884 convOp = spv::OpBitcast;
5885 break;
5886
John Kessenich66011cb2018-03-06 16:12:04 -07005887 case glslang::EOpConvFloat16ToUint8:
5888 case glslang::EOpConvFloatToUint8:
5889 case glslang::EOpConvDoubleToUint8:
5890 case glslang::EOpConvFloat16ToUint16:
5891 case glslang::EOpConvFloatToUint16:
5892 case glslang::EOpConvDoubleToUint16:
5893 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005894 case glslang::EOpConvFloatToUint:
5895 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005896 case glslang::EOpConvFloatToUint64:
5897 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005898 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005899 convOp = spv::OpConvertFToU;
5900 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005901
John Kessenich66011cb2018-03-06 16:12:04 -07005902 case glslang::EOpConvInt8ToInt16:
5903 case glslang::EOpConvInt8ToInt:
5904 case glslang::EOpConvInt8ToInt64:
5905 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005906 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005907 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005908 case glslang::EOpConvIntToInt8:
5909 case glslang::EOpConvIntToInt16:
5910 case glslang::EOpConvIntToInt64:
5911 case glslang::EOpConvInt64ToInt8:
5912 case glslang::EOpConvInt64ToInt16:
5913 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005914 convOp = spv::OpSConvert;
5915 break;
5916
John Kessenich66011cb2018-03-06 16:12:04 -07005917 case glslang::EOpConvUint8ToUint16:
5918 case glslang::EOpConvUint8ToUint:
5919 case glslang::EOpConvUint8ToUint64:
5920 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005921 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005922 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005923 case glslang::EOpConvUintToUint8:
5924 case glslang::EOpConvUintToUint16:
5925 case glslang::EOpConvUintToUint64:
5926 case glslang::EOpConvUint64ToUint8:
5927 case glslang::EOpConvUint64ToUint16:
5928 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005929 convOp = spv::OpUConvert;
5930 break;
5931
John Kessenich66011cb2018-03-06 16:12:04 -07005932 case glslang::EOpConvInt8ToUint16:
5933 case glslang::EOpConvInt8ToUint:
5934 case glslang::EOpConvInt8ToUint64:
5935 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005936 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005937 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005938 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005939 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005940 case glslang::EOpConvIntToUint64:
5941 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005942 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005943 case glslang::EOpConvInt64ToUint:
5944 case glslang::EOpConvUint8ToInt16:
5945 case glslang::EOpConvUint8ToInt:
5946 case glslang::EOpConvUint8ToInt64:
5947 case glslang::EOpConvUint16ToInt8:
5948 case glslang::EOpConvUint16ToInt:
5949 case glslang::EOpConvUint16ToInt64:
5950 case glslang::EOpConvUintToInt8:
5951 case glslang::EOpConvUintToInt16:
5952 case glslang::EOpConvUintToInt64:
5953 case glslang::EOpConvUint64ToInt8:
5954 case glslang::EOpConvUint64ToInt16:
5955 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005956 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005957 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005958
5959 if (builder.isInSpecConstCodeGenMode()) {
5960 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005961 switch(op) {
5962 case glslang::EOpConvInt16ToUint8:
5963 case glslang::EOpConvIntToUint8:
5964 case glslang::EOpConvInt64ToUint8:
5965 case glslang::EOpConvUint16ToInt8:
5966 case glslang::EOpConvUintToInt8:
5967 case glslang::EOpConvUint64ToInt8:
5968 zero = builder.makeUint8Constant(0);
5969 break;
5970 case glslang::EOpConvInt8ToUint16:
5971 case glslang::EOpConvIntToUint16:
5972 case glslang::EOpConvInt64ToUint16:
5973 case glslang::EOpConvUint8ToInt16:
5974 case glslang::EOpConvUintToInt16:
5975 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005976 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005977 break;
5978 case glslang::EOpConvInt8ToUint:
5979 case glslang::EOpConvInt16ToUint:
5980 case glslang::EOpConvInt64ToUint:
5981 case glslang::EOpConvUint8ToInt:
5982 case glslang::EOpConvUint16ToInt:
5983 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005984 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005985 break;
5986 case glslang::EOpConvInt8ToUint64:
5987 case glslang::EOpConvInt16ToUint64:
5988 case glslang::EOpConvIntToUint64:
5989 case glslang::EOpConvUint8ToInt64:
5990 case glslang::EOpConvUint16ToInt64:
5991 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005992 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005993 break;
5994 default:
5995 assert(false && "Default missing");
5996 break;
5997 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005998 zero = makeSmearedConstant(zero, vectorSize);
5999 // Use OpIAdd, instead of OpBitcast to do the conversion when
6000 // generating for OpSpecConstantOp instruction.
6001 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6002 }
6003 // For normal run-time conversion instruction, use OpBitcast.
6004 convOp = spv::OpBitcast;
6005 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006006 case glslang::EOpConvUint64ToPtr:
6007 convOp = spv::OpConvertUToPtr;
6008 break;
6009 case glslang::EOpConvPtrToUint64:
6010 convOp = spv::OpConvertPtrToU;
6011 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006012 default:
6013 break;
6014 }
6015
6016 spv::Id result = 0;
6017 if (convOp == spv::OpNop)
6018 return result;
6019
6020 if (convOp == spv::OpSelect) {
6021 zero = makeSmearedConstant(zero, vectorSize);
6022 one = makeSmearedConstant(one, vectorSize);
6023 result = builder.createTriOp(convOp, destType, operand, one, zero);
6024 } else
6025 result = builder.createUnaryOp(convOp, destType, operand);
6026
John Kessenichead86222018-03-28 18:01:20 -06006027 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006028 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006029 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006030}
6031
6032spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6033{
6034 if (vectorSize == 0)
6035 return constant;
6036
6037 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6038 std::vector<spv::Id> components;
6039 for (int c = 0; c < vectorSize; ++c)
6040 components.push_back(constant);
6041 return builder.makeCompositeConstant(vectorTypeId, components);
6042}
6043
John Kessenich426394d2015-07-23 10:22:48 -06006044// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07006045spv::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 -06006046{
6047 spv::Op opCode = spv::OpNop;
6048
6049 switch (op) {
6050 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006051 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006052 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006053 opCode = spv::OpAtomicIAdd;
6054 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006055 case glslang::EOpAtomicCounterSubtract:
6056 opCode = spv::OpAtomicISub;
6057 break;
John Kessenich426394d2015-07-23 10:22:48 -06006058 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006059 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006060 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006061 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006062 break;
6063 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006064 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006065 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006066 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006067 break;
6068 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006069 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006070 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006071 opCode = spv::OpAtomicAnd;
6072 break;
6073 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006074 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006075 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006076 opCode = spv::OpAtomicOr;
6077 break;
6078 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006079 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006080 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006081 opCode = spv::OpAtomicXor;
6082 break;
6083 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006084 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006085 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006086 opCode = spv::OpAtomicExchange;
6087 break;
6088 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006089 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006090 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006091 opCode = spv::OpAtomicCompareExchange;
6092 break;
6093 case glslang::EOpAtomicCounterIncrement:
6094 opCode = spv::OpAtomicIIncrement;
6095 break;
6096 case glslang::EOpAtomicCounterDecrement:
6097 opCode = spv::OpAtomicIDecrement;
6098 break;
6099 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006100 case glslang::EOpImageAtomicLoad:
6101 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006102 opCode = spv::OpAtomicLoad;
6103 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006104 case glslang::EOpAtomicStore:
6105 case glslang::EOpImageAtomicStore:
6106 opCode = spv::OpAtomicStore;
6107 break;
John Kessenich426394d2015-07-23 10:22:48 -06006108 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006109 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006110 break;
6111 }
6112
Rex Xue8fe8b02017-09-26 15:42:56 +08006113 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6114 builder.addCapability(spv::CapabilityInt64Atomics);
6115
John Kessenich426394d2015-07-23 10:22:48 -06006116 // Sort out the operands
6117 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006118 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006119 // - compare-exchange swaps the value and comparator
6120 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006121 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006122 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6123 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6124 spv::Id scopeId;
6125 if (glslangIntermediate->usingVulkanMemoryModel()) {
6126 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6127 } else {
6128 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6129 }
6130 // semantics default to relaxed
6131 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
6132 spv::Id semanticsId2 = semanticsId;
6133
6134 pointerId = operands[0];
6135 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6136 // no additional operands
6137 } else if (opCode == spv::OpAtomicCompareExchange) {
6138 compareId = operands[1];
6139 valueId = operands[2];
6140 if (operands.size() > 3) {
6141 scopeId = operands[3];
6142 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6143 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6144 }
6145 } else if (opCode == spv::OpAtomicLoad) {
6146 if (operands.size() > 1) {
6147 scopeId = operands[1];
6148 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6149 }
6150 } else {
6151 // atomic store or RMW
6152 valueId = operands[1];
6153 if (operands.size() > 2) {
6154 scopeId = operands[2];
6155 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6156 }
Rex Xu04db3f52015-09-16 11:44:02 +08006157 }
John Kessenich426394d2015-07-23 10:22:48 -06006158
Jeff Bolz36831c92018-09-05 10:11:41 -05006159 // Check for capabilities
6160 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
6161 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6162 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6163 }
John Kessenich426394d2015-07-23 10:22:48 -06006164
Jeff Bolz36831c92018-09-05 10:11:41 -05006165 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6166 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6167 }
John Kessenich48d6e792017-10-06 21:21:48 -06006168
Jeff Bolz36831c92018-09-05 10:11:41 -05006169 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6170 spvAtomicOperands.push_back(pointerId);
6171 spvAtomicOperands.push_back(scopeId);
6172 spvAtomicOperands.push_back(semanticsId);
6173 if (opCode == spv::OpAtomicCompareExchange) {
6174 spvAtomicOperands.push_back(semanticsId2);
6175 spvAtomicOperands.push_back(valueId);
6176 spvAtomicOperands.push_back(compareId);
6177 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6178 spvAtomicOperands.push_back(valueId);
6179 }
John Kessenich48d6e792017-10-06 21:21:48 -06006180
Jeff Bolz36831c92018-09-05 10:11:41 -05006181 if (opCode == spv::OpAtomicStore) {
6182 builder.createNoResultOp(opCode, spvAtomicOperands);
6183 return 0;
6184 } else {
6185 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6186
6187 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6188 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6189 if (op == glslang::EOpAtomicCounterDecrement)
6190 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6191
6192 return resultId;
6193 }
John Kessenich426394d2015-07-23 10:22:48 -06006194}
6195
John Kessenich91cef522016-05-05 16:45:40 -06006196// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006197spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006198{
Corentin Walleze7061422018-08-08 15:20:15 +02006199#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006200 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6201 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006202#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006203
Rex Xu51596642016-09-21 18:56:12 +08006204 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006205 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006206 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6207
chaocf200da82016-12-20 12:44:35 -08006208 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6209 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006210 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6211 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006212 } else if (op == glslang::EOpAnyInvocation ||
6213 op == glslang::EOpAllInvocations ||
6214 op == glslang::EOpAllInvocationsEqual) {
6215 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6216 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006217 } else {
6218 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006219#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006220 if (op == glslang::EOpMinInvocationsNonUniform ||
6221 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006222 op == glslang::EOpAddInvocationsNonUniform ||
6223 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6224 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6225 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6226 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6227 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6228 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006229 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006230#endif
Rex Xu51596642016-09-21 18:56:12 +08006231
Rex Xu9d93a232016-05-05 12:30:44 +08006232#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006233 switch (op) {
6234 case glslang::EOpMinInvocations:
6235 case glslang::EOpMaxInvocations:
6236 case glslang::EOpAddInvocations:
6237 case glslang::EOpMinInvocationsNonUniform:
6238 case glslang::EOpMaxInvocationsNonUniform:
6239 case glslang::EOpAddInvocationsNonUniform:
6240 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006241 break;
6242 case glslang::EOpMinInvocationsInclusiveScan:
6243 case glslang::EOpMaxInvocationsInclusiveScan:
6244 case glslang::EOpAddInvocationsInclusiveScan:
6245 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6246 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6247 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6248 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006249 break;
6250 case glslang::EOpMinInvocationsExclusiveScan:
6251 case glslang::EOpMaxInvocationsExclusiveScan:
6252 case glslang::EOpAddInvocationsExclusiveScan:
6253 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6254 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6255 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6256 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006257 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006258 default:
6259 break;
Rex Xu430ef402016-10-14 17:22:23 +08006260 }
John Kessenich149afc32018-08-14 13:31:43 -06006261 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6262 spvGroupOperands.push_back(scope);
6263 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006264 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006265 spvGroupOperands.push_back(groupOp);
6266 }
Rex Xu9d93a232016-05-05 12:30:44 +08006267#endif
Rex Xu51596642016-09-21 18:56:12 +08006268 }
6269
John Kessenich149afc32018-08-14 13:31:43 -06006270 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6271 spv::IdImmediate op = { true, *opIt };
6272 spvGroupOperands.push_back(op);
6273 }
John Kessenich91cef522016-05-05 16:45:40 -06006274
6275 switch (op) {
6276 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006277 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006278 break;
John Kessenich91cef522016-05-05 16:45:40 -06006279 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006280 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006281 break;
John Kessenich91cef522016-05-05 16:45:40 -06006282 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006283 opCode = spv::OpSubgroupAllEqualKHR;
6284 break;
Rex Xu51596642016-09-21 18:56:12 +08006285 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006286 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006287 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006288 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006289 break;
6290 case glslang::EOpReadFirstInvocation:
6291 opCode = spv::OpSubgroupFirstInvocationKHR;
6292 break;
6293 case glslang::EOpBallot:
6294 {
6295 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6296 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6297 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6298 //
6299 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6300 //
6301 spv::Id uintType = builder.makeUintType(32);
6302 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6303 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6304
6305 std::vector<spv::Id> components;
6306 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6307 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6308
6309 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6310 return builder.createUnaryOp(spv::OpBitcast, typeId,
6311 builder.createCompositeConstruct(uvec2Type, components));
6312 }
6313
Rex Xu9d93a232016-05-05 12:30:44 +08006314#ifdef AMD_EXTENSIONS
6315 case glslang::EOpMinInvocations:
6316 case glslang::EOpMaxInvocations:
6317 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006318 case glslang::EOpMinInvocationsInclusiveScan:
6319 case glslang::EOpMaxInvocationsInclusiveScan:
6320 case glslang::EOpAddInvocationsInclusiveScan:
6321 case glslang::EOpMinInvocationsExclusiveScan:
6322 case glslang::EOpMaxInvocationsExclusiveScan:
6323 case glslang::EOpAddInvocationsExclusiveScan:
6324 if (op == glslang::EOpMinInvocations ||
6325 op == glslang::EOpMinInvocationsInclusiveScan ||
6326 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006327 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006328 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006329 else {
6330 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006331 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006332 else
Rex Xu51596642016-09-21 18:56:12 +08006333 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006334 }
Rex Xu430ef402016-10-14 17:22:23 +08006335 } else if (op == glslang::EOpMaxInvocations ||
6336 op == glslang::EOpMaxInvocationsInclusiveScan ||
6337 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006338 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006339 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006340 else {
6341 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006342 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006343 else
Rex Xu51596642016-09-21 18:56:12 +08006344 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006345 }
6346 } else {
6347 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006348 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006349 else
Rex Xu51596642016-09-21 18:56:12 +08006350 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006351 }
6352
Rex Xu2bbbe062016-08-23 15:41:05 +08006353 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006354 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006355
6356 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006357 case glslang::EOpMinInvocationsNonUniform:
6358 case glslang::EOpMaxInvocationsNonUniform:
6359 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006360 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6361 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6362 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6363 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6364 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6365 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6366 if (op == glslang::EOpMinInvocationsNonUniform ||
6367 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6368 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006369 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006370 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006371 else {
6372 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006373 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006374 else
Rex Xu51596642016-09-21 18:56:12 +08006375 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006376 }
6377 }
Rex Xu430ef402016-10-14 17:22:23 +08006378 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6379 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6380 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006381 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006382 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006383 else {
6384 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006385 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006386 else
Rex Xu51596642016-09-21 18:56:12 +08006387 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006388 }
6389 }
6390 else {
6391 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006392 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006393 else
Rex Xu51596642016-09-21 18:56:12 +08006394 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006395 }
6396
Rex Xu2bbbe062016-08-23 15:41:05 +08006397 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006398 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006399
6400 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006401#endif
John Kessenich91cef522016-05-05 16:45:40 -06006402 default:
6403 logger->missingFunctionality("invocation operation");
6404 return spv::NoResult;
6405 }
Rex Xu51596642016-09-21 18:56:12 +08006406
6407 assert(opCode != spv::OpNop);
6408 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006409}
6410
Rex Xu2bbbe062016-08-23 15:41:05 +08006411// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006412spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6413 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006414{
Rex Xub7072052016-09-26 15:53:40 +08006415#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006416 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6417 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006418 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006419 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006420 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6421 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6422 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006423#else
6424 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6425 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006426 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6427 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006428#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006429
6430 // Handle group invocation operations scalar by scalar.
6431 // The result type is the same type as the original type.
6432 // The algorithm is to:
6433 // - break the vector into scalars
6434 // - apply the operation to each scalar
6435 // - make a vector out the scalar results
6436
6437 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006438 int numComponents = builder.getNumComponents(operands[0]);
6439 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006440 std::vector<spv::Id> results;
6441
6442 // do each scalar op
6443 for (int comp = 0; comp < numComponents; ++comp) {
6444 std::vector<unsigned int> indexes;
6445 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006446 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6447 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006448 if (op == spv::OpSubgroupReadInvocationKHR) {
6449 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006450 spv::IdImmediate operand = { true, operands[1] };
6451 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006452 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006453 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6454 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006455 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006456 spv::IdImmediate operand = { true, operands[1] };
6457 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006458 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006459 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6460 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006461 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006462 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006463 spvGroupOperands.push_back(scalar);
6464 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006465
Rex Xub7072052016-09-26 15:53:40 +08006466 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006467 }
6468
6469 // put the pieces together
6470 return builder.createCompositeConstruct(typeId, results);
6471}
Rex Xu2bbbe062016-08-23 15:41:05 +08006472
John Kessenich66011cb2018-03-06 16:12:04 -07006473// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006474spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6475 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006476{
6477 // Add the required capabilities.
6478 switch (op) {
6479 case glslang::EOpSubgroupElect:
6480 builder.addCapability(spv::CapabilityGroupNonUniform);
6481 break;
6482 case glslang::EOpSubgroupAll:
6483 case glslang::EOpSubgroupAny:
6484 case glslang::EOpSubgroupAllEqual:
6485 builder.addCapability(spv::CapabilityGroupNonUniform);
6486 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6487 break;
6488 case glslang::EOpSubgroupBroadcast:
6489 case glslang::EOpSubgroupBroadcastFirst:
6490 case glslang::EOpSubgroupBallot:
6491 case glslang::EOpSubgroupInverseBallot:
6492 case glslang::EOpSubgroupBallotBitExtract:
6493 case glslang::EOpSubgroupBallotBitCount:
6494 case glslang::EOpSubgroupBallotInclusiveBitCount:
6495 case glslang::EOpSubgroupBallotExclusiveBitCount:
6496 case glslang::EOpSubgroupBallotFindLSB:
6497 case glslang::EOpSubgroupBallotFindMSB:
6498 builder.addCapability(spv::CapabilityGroupNonUniform);
6499 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6500 break;
6501 case glslang::EOpSubgroupShuffle:
6502 case glslang::EOpSubgroupShuffleXor:
6503 builder.addCapability(spv::CapabilityGroupNonUniform);
6504 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6505 break;
6506 case glslang::EOpSubgroupShuffleUp:
6507 case glslang::EOpSubgroupShuffleDown:
6508 builder.addCapability(spv::CapabilityGroupNonUniform);
6509 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6510 break;
6511 case glslang::EOpSubgroupAdd:
6512 case glslang::EOpSubgroupMul:
6513 case glslang::EOpSubgroupMin:
6514 case glslang::EOpSubgroupMax:
6515 case glslang::EOpSubgroupAnd:
6516 case glslang::EOpSubgroupOr:
6517 case glslang::EOpSubgroupXor:
6518 case glslang::EOpSubgroupInclusiveAdd:
6519 case glslang::EOpSubgroupInclusiveMul:
6520 case glslang::EOpSubgroupInclusiveMin:
6521 case glslang::EOpSubgroupInclusiveMax:
6522 case glslang::EOpSubgroupInclusiveAnd:
6523 case glslang::EOpSubgroupInclusiveOr:
6524 case glslang::EOpSubgroupInclusiveXor:
6525 case glslang::EOpSubgroupExclusiveAdd:
6526 case glslang::EOpSubgroupExclusiveMul:
6527 case glslang::EOpSubgroupExclusiveMin:
6528 case glslang::EOpSubgroupExclusiveMax:
6529 case glslang::EOpSubgroupExclusiveAnd:
6530 case glslang::EOpSubgroupExclusiveOr:
6531 case glslang::EOpSubgroupExclusiveXor:
6532 builder.addCapability(spv::CapabilityGroupNonUniform);
6533 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6534 break;
6535 case glslang::EOpSubgroupClusteredAdd:
6536 case glslang::EOpSubgroupClusteredMul:
6537 case glslang::EOpSubgroupClusteredMin:
6538 case glslang::EOpSubgroupClusteredMax:
6539 case glslang::EOpSubgroupClusteredAnd:
6540 case glslang::EOpSubgroupClusteredOr:
6541 case glslang::EOpSubgroupClusteredXor:
6542 builder.addCapability(spv::CapabilityGroupNonUniform);
6543 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6544 break;
6545 case glslang::EOpSubgroupQuadBroadcast:
6546 case glslang::EOpSubgroupQuadSwapHorizontal:
6547 case glslang::EOpSubgroupQuadSwapVertical:
6548 case glslang::EOpSubgroupQuadSwapDiagonal:
6549 builder.addCapability(spv::CapabilityGroupNonUniform);
6550 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6551 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006552#ifdef NV_EXTENSIONS
6553 case glslang::EOpSubgroupPartitionedAdd:
6554 case glslang::EOpSubgroupPartitionedMul:
6555 case glslang::EOpSubgroupPartitionedMin:
6556 case glslang::EOpSubgroupPartitionedMax:
6557 case glslang::EOpSubgroupPartitionedAnd:
6558 case glslang::EOpSubgroupPartitionedOr:
6559 case glslang::EOpSubgroupPartitionedXor:
6560 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6561 case glslang::EOpSubgroupPartitionedInclusiveMul:
6562 case glslang::EOpSubgroupPartitionedInclusiveMin:
6563 case glslang::EOpSubgroupPartitionedInclusiveMax:
6564 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6565 case glslang::EOpSubgroupPartitionedInclusiveOr:
6566 case glslang::EOpSubgroupPartitionedInclusiveXor:
6567 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6568 case glslang::EOpSubgroupPartitionedExclusiveMul:
6569 case glslang::EOpSubgroupPartitionedExclusiveMin:
6570 case glslang::EOpSubgroupPartitionedExclusiveMax:
6571 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6572 case glslang::EOpSubgroupPartitionedExclusiveOr:
6573 case glslang::EOpSubgroupPartitionedExclusiveXor:
6574 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6575 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6576 break;
6577#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006578 default: assert(0 && "Unhandled subgroup operation!");
6579 }
6580
6581 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6582 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6583 const bool isBool = typeProxy == glslang::EbtBool;
6584
6585 spv::Op opCode = spv::OpNop;
6586
6587 // Figure out which opcode to use.
6588 switch (op) {
6589 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6590 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6591 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6592 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6593 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6594 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6595 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6596 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6597 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6598 case glslang::EOpSubgroupBallotBitCount:
6599 case glslang::EOpSubgroupBallotInclusiveBitCount:
6600 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6601 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6602 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6603 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6604 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6605 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6606 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6607 case glslang::EOpSubgroupAdd:
6608 case glslang::EOpSubgroupInclusiveAdd:
6609 case glslang::EOpSubgroupExclusiveAdd:
6610 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006611#ifdef NV_EXTENSIONS
6612 case glslang::EOpSubgroupPartitionedAdd:
6613 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6614 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6615#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006616 if (isFloat) {
6617 opCode = spv::OpGroupNonUniformFAdd;
6618 } else {
6619 opCode = spv::OpGroupNonUniformIAdd;
6620 }
6621 break;
6622 case glslang::EOpSubgroupMul:
6623 case glslang::EOpSubgroupInclusiveMul:
6624 case glslang::EOpSubgroupExclusiveMul:
6625 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006626#ifdef NV_EXTENSIONS
6627 case glslang::EOpSubgroupPartitionedMul:
6628 case glslang::EOpSubgroupPartitionedInclusiveMul:
6629 case glslang::EOpSubgroupPartitionedExclusiveMul:
6630#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006631 if (isFloat) {
6632 opCode = spv::OpGroupNonUniformFMul;
6633 } else {
6634 opCode = spv::OpGroupNonUniformIMul;
6635 }
6636 break;
6637 case glslang::EOpSubgroupMin:
6638 case glslang::EOpSubgroupInclusiveMin:
6639 case glslang::EOpSubgroupExclusiveMin:
6640 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006641#ifdef NV_EXTENSIONS
6642 case glslang::EOpSubgroupPartitionedMin:
6643 case glslang::EOpSubgroupPartitionedInclusiveMin:
6644 case glslang::EOpSubgroupPartitionedExclusiveMin:
6645#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006646 if (isFloat) {
6647 opCode = spv::OpGroupNonUniformFMin;
6648 } else if (isUnsigned) {
6649 opCode = spv::OpGroupNonUniformUMin;
6650 } else {
6651 opCode = spv::OpGroupNonUniformSMin;
6652 }
6653 break;
6654 case glslang::EOpSubgroupMax:
6655 case glslang::EOpSubgroupInclusiveMax:
6656 case glslang::EOpSubgroupExclusiveMax:
6657 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006658#ifdef NV_EXTENSIONS
6659 case glslang::EOpSubgroupPartitionedMax:
6660 case glslang::EOpSubgroupPartitionedInclusiveMax:
6661 case glslang::EOpSubgroupPartitionedExclusiveMax:
6662#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006663 if (isFloat) {
6664 opCode = spv::OpGroupNonUniformFMax;
6665 } else if (isUnsigned) {
6666 opCode = spv::OpGroupNonUniformUMax;
6667 } else {
6668 opCode = spv::OpGroupNonUniformSMax;
6669 }
6670 break;
6671 case glslang::EOpSubgroupAnd:
6672 case glslang::EOpSubgroupInclusiveAnd:
6673 case glslang::EOpSubgroupExclusiveAnd:
6674 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006675#ifdef NV_EXTENSIONS
6676 case glslang::EOpSubgroupPartitionedAnd:
6677 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6678 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6679#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006680 if (isBool) {
6681 opCode = spv::OpGroupNonUniformLogicalAnd;
6682 } else {
6683 opCode = spv::OpGroupNonUniformBitwiseAnd;
6684 }
6685 break;
6686 case glslang::EOpSubgroupOr:
6687 case glslang::EOpSubgroupInclusiveOr:
6688 case glslang::EOpSubgroupExclusiveOr:
6689 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006690#ifdef NV_EXTENSIONS
6691 case glslang::EOpSubgroupPartitionedOr:
6692 case glslang::EOpSubgroupPartitionedInclusiveOr:
6693 case glslang::EOpSubgroupPartitionedExclusiveOr:
6694#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006695 if (isBool) {
6696 opCode = spv::OpGroupNonUniformLogicalOr;
6697 } else {
6698 opCode = spv::OpGroupNonUniformBitwiseOr;
6699 }
6700 break;
6701 case glslang::EOpSubgroupXor:
6702 case glslang::EOpSubgroupInclusiveXor:
6703 case glslang::EOpSubgroupExclusiveXor:
6704 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006705#ifdef NV_EXTENSIONS
6706 case glslang::EOpSubgroupPartitionedXor:
6707 case glslang::EOpSubgroupPartitionedInclusiveXor:
6708 case glslang::EOpSubgroupPartitionedExclusiveXor:
6709#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006710 if (isBool) {
6711 opCode = spv::OpGroupNonUniformLogicalXor;
6712 } else {
6713 opCode = spv::OpGroupNonUniformBitwiseXor;
6714 }
6715 break;
6716 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6717 case glslang::EOpSubgroupQuadSwapHorizontal:
6718 case glslang::EOpSubgroupQuadSwapVertical:
6719 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6720 default: assert(0 && "Unhandled subgroup operation!");
6721 }
6722
John Kessenich149afc32018-08-14 13:31:43 -06006723 // get the right Group Operation
6724 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006725 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006726 default:
6727 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006728 case glslang::EOpSubgroupBallotBitCount:
6729 case glslang::EOpSubgroupAdd:
6730 case glslang::EOpSubgroupMul:
6731 case glslang::EOpSubgroupMin:
6732 case glslang::EOpSubgroupMax:
6733 case glslang::EOpSubgroupAnd:
6734 case glslang::EOpSubgroupOr:
6735 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006736 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006737 break;
6738 case glslang::EOpSubgroupBallotInclusiveBitCount:
6739 case glslang::EOpSubgroupInclusiveAdd:
6740 case glslang::EOpSubgroupInclusiveMul:
6741 case glslang::EOpSubgroupInclusiveMin:
6742 case glslang::EOpSubgroupInclusiveMax:
6743 case glslang::EOpSubgroupInclusiveAnd:
6744 case glslang::EOpSubgroupInclusiveOr:
6745 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006746 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006747 break;
6748 case glslang::EOpSubgroupBallotExclusiveBitCount:
6749 case glslang::EOpSubgroupExclusiveAdd:
6750 case glslang::EOpSubgroupExclusiveMul:
6751 case glslang::EOpSubgroupExclusiveMin:
6752 case glslang::EOpSubgroupExclusiveMax:
6753 case glslang::EOpSubgroupExclusiveAnd:
6754 case glslang::EOpSubgroupExclusiveOr:
6755 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006756 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006757 break;
6758 case glslang::EOpSubgroupClusteredAdd:
6759 case glslang::EOpSubgroupClusteredMul:
6760 case glslang::EOpSubgroupClusteredMin:
6761 case glslang::EOpSubgroupClusteredMax:
6762 case glslang::EOpSubgroupClusteredAnd:
6763 case glslang::EOpSubgroupClusteredOr:
6764 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006765 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006766 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006767#ifdef NV_EXTENSIONS
6768 case glslang::EOpSubgroupPartitionedAdd:
6769 case glslang::EOpSubgroupPartitionedMul:
6770 case glslang::EOpSubgroupPartitionedMin:
6771 case glslang::EOpSubgroupPartitionedMax:
6772 case glslang::EOpSubgroupPartitionedAnd:
6773 case glslang::EOpSubgroupPartitionedOr:
6774 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006775 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006776 break;
6777 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6778 case glslang::EOpSubgroupPartitionedInclusiveMul:
6779 case glslang::EOpSubgroupPartitionedInclusiveMin:
6780 case glslang::EOpSubgroupPartitionedInclusiveMax:
6781 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6782 case glslang::EOpSubgroupPartitionedInclusiveOr:
6783 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006784 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006785 break;
6786 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6787 case glslang::EOpSubgroupPartitionedExclusiveMul:
6788 case glslang::EOpSubgroupPartitionedExclusiveMin:
6789 case glslang::EOpSubgroupPartitionedExclusiveMax:
6790 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6791 case glslang::EOpSubgroupPartitionedExclusiveOr:
6792 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006793 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006794 break;
6795#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006796 }
6797
John Kessenich149afc32018-08-14 13:31:43 -06006798 // build the instruction
6799 std::vector<spv::IdImmediate> spvGroupOperands;
6800
6801 // Every operation begins with the Execution Scope operand.
6802 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6803 spvGroupOperands.push_back(executionScope);
6804
6805 // Next, for all operations that use a Group Operation, push that as an operand.
6806 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006807 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006808 spvGroupOperands.push_back(groupOperand);
6809 }
6810
John Kessenich66011cb2018-03-06 16:12:04 -07006811 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006812 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6813 spv::IdImmediate operand = { true, *opIt };
6814 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006815 }
6816
6817 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006818 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006819 switch (op) {
6820 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006821 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6822 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6823 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6824 }
6825 if (directionId != spv::NoResult) {
6826 spv::IdImmediate direction = { true, directionId };
6827 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006828 }
6829
6830 return builder.createOp(opCode, typeId, spvGroupOperands);
6831}
6832
John Kessenich5e4b1242015-08-06 22:53:06 -06006833spv::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 -06006834{
John Kessenich66011cb2018-03-06 16:12:04 -07006835 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6836 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006837
John Kessenich140f3df2015-06-26 16:58:36 -06006838 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006839 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006840 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006841 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006842 spv::Id typeId0 = 0;
6843 if (consumedOperands > 0)
6844 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006845 spv::Id typeId1 = 0;
6846 if (consumedOperands > 1)
6847 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006848 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006849
6850 switch (op) {
6851 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006852 if (isFloat)
6853 libCall = spv::GLSLstd450FMin;
6854 else if (isUnsigned)
6855 libCall = spv::GLSLstd450UMin;
6856 else
6857 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006858 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006859 break;
6860 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006861 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006862 break;
6863 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006864 if (isFloat)
6865 libCall = spv::GLSLstd450FMax;
6866 else if (isUnsigned)
6867 libCall = spv::GLSLstd450UMax;
6868 else
6869 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006870 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006871 break;
6872 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006873 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006874 break;
6875 case glslang::EOpDot:
6876 opCode = spv::OpDot;
6877 break;
6878 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006879 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006880 break;
6881
6882 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006883 if (isFloat)
6884 libCall = spv::GLSLstd450FClamp;
6885 else if (isUnsigned)
6886 libCall = spv::GLSLstd450UClamp;
6887 else
6888 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006889 builder.promoteScalar(precision, operands.front(), operands[1]);
6890 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006891 break;
6892 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006893 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6894 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006895 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006896 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006897 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006898 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006899 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006900 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006901 break;
6902 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006903 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006904 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006905 break;
6906 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006907 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006908 builder.promoteScalar(precision, operands[0], operands[2]);
6909 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006910 break;
6911
6912 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006913 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006914 break;
6915 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006916 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006917 break;
6918 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006919 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006920 break;
6921 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006922 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006923 break;
6924 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006925 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006926 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006927 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006928#ifdef AMD_EXTENSIONS
6929 if (typeProxy == glslang::EbtFloat16)
6930 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6931#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006932 libCall = spv::GLSLstd450InterpolateAtSample;
6933 break;
6934 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006935#ifdef AMD_EXTENSIONS
6936 if (typeProxy == glslang::EbtFloat16)
6937 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6938#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006939 libCall = spv::GLSLstd450InterpolateAtOffset;
6940 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006941 case glslang::EOpAddCarry:
6942 opCode = spv::OpIAddCarry;
6943 typeId = builder.makeStructResultType(typeId0, typeId0);
6944 consumedOperands = 2;
6945 break;
6946 case glslang::EOpSubBorrow:
6947 opCode = spv::OpISubBorrow;
6948 typeId = builder.makeStructResultType(typeId0, typeId0);
6949 consumedOperands = 2;
6950 break;
6951 case glslang::EOpUMulExtended:
6952 opCode = spv::OpUMulExtended;
6953 typeId = builder.makeStructResultType(typeId0, typeId0);
6954 consumedOperands = 2;
6955 break;
6956 case glslang::EOpIMulExtended:
6957 opCode = spv::OpSMulExtended;
6958 typeId = builder.makeStructResultType(typeId0, typeId0);
6959 consumedOperands = 2;
6960 break;
6961 case glslang::EOpBitfieldExtract:
6962 if (isUnsigned)
6963 opCode = spv::OpBitFieldUExtract;
6964 else
6965 opCode = spv::OpBitFieldSExtract;
6966 break;
6967 case glslang::EOpBitfieldInsert:
6968 opCode = spv::OpBitFieldInsert;
6969 break;
6970
6971 case glslang::EOpFma:
6972 libCall = spv::GLSLstd450Fma;
6973 break;
6974 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006975 {
6976 libCall = spv::GLSLstd450FrexpStruct;
6977 assert(builder.isPointerType(typeId1));
6978 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006979 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006980#ifdef AMD_EXTENSIONS
6981 if (width == 16)
6982 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6983 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6984#endif
Rex Xu470026f2017-03-29 17:12:40 +08006985 if (builder.getNumComponents(operands[0]) == 1)
6986 frexpIntType = builder.makeIntegerType(width, true);
6987 else
6988 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6989 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6990 consumedOperands = 1;
6991 }
John Kessenich55e7d112015-11-15 21:33:39 -07006992 break;
6993 case glslang::EOpLdexp:
6994 libCall = spv::GLSLstd450Ldexp;
6995 break;
6996
Rex Xu574ab042016-04-14 16:53:07 +08006997 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006998 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006999
John Kessenich66011cb2018-03-06 16:12:04 -07007000 case glslang::EOpSubgroupBroadcast:
7001 case glslang::EOpSubgroupBallotBitExtract:
7002 case glslang::EOpSubgroupShuffle:
7003 case glslang::EOpSubgroupShuffleXor:
7004 case glslang::EOpSubgroupShuffleUp:
7005 case glslang::EOpSubgroupShuffleDown:
7006 case glslang::EOpSubgroupClusteredAdd:
7007 case glslang::EOpSubgroupClusteredMul:
7008 case glslang::EOpSubgroupClusteredMin:
7009 case glslang::EOpSubgroupClusteredMax:
7010 case glslang::EOpSubgroupClusteredAnd:
7011 case glslang::EOpSubgroupClusteredOr:
7012 case glslang::EOpSubgroupClusteredXor:
7013 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007014#ifdef NV_EXTENSIONS
7015 case glslang::EOpSubgroupPartitionedAdd:
7016 case glslang::EOpSubgroupPartitionedMul:
7017 case glslang::EOpSubgroupPartitionedMin:
7018 case glslang::EOpSubgroupPartitionedMax:
7019 case glslang::EOpSubgroupPartitionedAnd:
7020 case glslang::EOpSubgroupPartitionedOr:
7021 case glslang::EOpSubgroupPartitionedXor:
7022 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7023 case glslang::EOpSubgroupPartitionedInclusiveMul:
7024 case glslang::EOpSubgroupPartitionedInclusiveMin:
7025 case glslang::EOpSubgroupPartitionedInclusiveMax:
7026 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7027 case glslang::EOpSubgroupPartitionedInclusiveOr:
7028 case glslang::EOpSubgroupPartitionedInclusiveXor:
7029 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7030 case glslang::EOpSubgroupPartitionedExclusiveMul:
7031 case glslang::EOpSubgroupPartitionedExclusiveMin:
7032 case glslang::EOpSubgroupPartitionedExclusiveMax:
7033 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7034 case glslang::EOpSubgroupPartitionedExclusiveOr:
7035 case glslang::EOpSubgroupPartitionedExclusiveXor:
7036#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007037 return createSubgroupOperation(op, typeId, operands, typeProxy);
7038
Rex Xu9d93a232016-05-05 12:30:44 +08007039#ifdef AMD_EXTENSIONS
7040 case glslang::EOpSwizzleInvocations:
7041 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7042 libCall = spv::SwizzleInvocationsAMD;
7043 break;
7044 case glslang::EOpSwizzleInvocationsMasked:
7045 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7046 libCall = spv::SwizzleInvocationsMaskedAMD;
7047 break;
7048 case glslang::EOpWriteInvocation:
7049 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7050 libCall = spv::WriteInvocationAMD;
7051 break;
7052
7053 case glslang::EOpMin3:
7054 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7055 if (isFloat)
7056 libCall = spv::FMin3AMD;
7057 else {
7058 if (isUnsigned)
7059 libCall = spv::UMin3AMD;
7060 else
7061 libCall = spv::SMin3AMD;
7062 }
7063 break;
7064 case glslang::EOpMax3:
7065 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7066 if (isFloat)
7067 libCall = spv::FMax3AMD;
7068 else {
7069 if (isUnsigned)
7070 libCall = spv::UMax3AMD;
7071 else
7072 libCall = spv::SMax3AMD;
7073 }
7074 break;
7075 case glslang::EOpMid3:
7076 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7077 if (isFloat)
7078 libCall = spv::FMid3AMD;
7079 else {
7080 if (isUnsigned)
7081 libCall = spv::UMid3AMD;
7082 else
7083 libCall = spv::SMid3AMD;
7084 }
7085 break;
7086
7087 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007088 if (typeProxy == glslang::EbtFloat16)
7089 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007090 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7091 libCall = spv::InterpolateAtVertexAMD;
7092 break;
7093#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007094 case glslang::EOpBarrier:
7095 {
7096 // This is for the extended controlBarrier function, with four operands.
7097 // The unextended barrier() goes through createNoArgOperation.
7098 assert(operands.size() == 4);
7099 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7100 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7101 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7102 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7103 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7104 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7105 }
7106 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7107 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7108 }
7109 return 0;
7110 }
7111 break;
7112 case glslang::EOpMemoryBarrier:
7113 {
7114 // This is for the extended memoryBarrier function, with three operands.
7115 // The unextended memoryBarrier() goes through createNoArgOperation.
7116 assert(operands.size() == 3);
7117 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7118 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7119 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7120 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7121 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7122 }
7123 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7124 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7125 }
7126 return 0;
7127 }
7128 break;
Chao Chen3c366992018-09-19 11:41:59 -07007129
7130#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007131 case glslang::EOpReportIntersectionNV:
7132 {
7133 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007134 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007135 }
7136 break;
7137 case glslang::EOpTraceNV:
7138 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007139 builder.createNoResultOp(spv::OpTraceNV, operands);
7140 return 0;
7141 }
7142 break;
7143 case glslang::EOpExecuteCallableNV:
7144 {
7145 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007146 return 0;
7147 }
7148 break;
Chao Chen3c366992018-09-19 11:41:59 -07007149 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7150 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7151 return 0;
7152#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007153 case glslang::EOpCooperativeMatrixMulAdd:
7154 opCode = spv::OpCooperativeMatrixMulAddNV;
7155 break;
7156
John Kessenich140f3df2015-06-26 16:58:36 -06007157 default:
7158 return 0;
7159 }
7160
7161 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007162 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007163 // Use an extended instruction from the standard library.
7164 // Construct the call arguments, without modifying the original operands vector.
7165 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7166 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007167 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007168 } else if (opCode == spv::OpDot && !isFloat) {
7169 // int dot(int, int)
7170 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7171 const int componentCount = builder.getNumComponents(operands[0]);
7172 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7173 builder.setPrecision(mulOp, precision);
7174 id = builder.createCompositeExtract(mulOp, typeId, 0);
7175 for (int i = 1; i < componentCount; ++i) {
7176 builder.setPrecision(id, precision);
7177 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7178 }
John Kessenich2359bd02015-12-06 19:29:11 -07007179 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007180 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007181 case 0:
7182 // should all be handled by visitAggregate and createNoArgOperation
7183 assert(0);
7184 return 0;
7185 case 1:
7186 // should all be handled by createUnaryOperation
7187 assert(0);
7188 return 0;
7189 case 2:
7190 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7191 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007192 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007193 // anything 3 or over doesn't have l-value operands, so all should be consumed
7194 assert(consumedOperands == operands.size());
7195 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007196 break;
7197 }
7198 }
7199
John Kessenich55e7d112015-11-15 21:33:39 -07007200 // Decode the return types that were structures
7201 switch (op) {
7202 case glslang::EOpAddCarry:
7203 case glslang::EOpSubBorrow:
7204 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7205 id = builder.createCompositeExtract(id, typeId0, 0);
7206 break;
7207 case glslang::EOpUMulExtended:
7208 case glslang::EOpIMulExtended:
7209 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7210 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7211 break;
7212 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007213 {
7214 assert(operands.size() == 2);
7215 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7216 // "exp" is floating-point type (from HLSL intrinsic)
7217 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7218 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7219 builder.createStore(member1, operands[1]);
7220 } else
7221 // "exp" is integer type (from GLSL built-in function)
7222 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7223 id = builder.createCompositeExtract(id, typeId0, 0);
7224 }
John Kessenich55e7d112015-11-15 21:33:39 -07007225 break;
7226 default:
7227 break;
7228 }
7229
John Kessenich32cfd492016-02-02 12:37:46 -07007230 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007231}
7232
Rex Xu9d93a232016-05-05 12:30:44 +08007233// Intrinsics with no arguments (or no return value, and no precision).
7234spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007235{
Jeff Bolz36831c92018-09-05 10:11:41 -05007236 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7237 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007238
7239 switch (op) {
7240 case glslang::EOpEmitVertex:
7241 builder.createNoResultOp(spv::OpEmitVertex);
7242 return 0;
7243 case glslang::EOpEndPrimitive:
7244 builder.createNoResultOp(spv::OpEndPrimitive);
7245 return 0;
7246 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007247 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007248 if (glslangIntermediate->usingVulkanMemoryModel()) {
7249 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7250 spv::MemorySemanticsOutputMemoryKHRMask |
7251 spv::MemorySemanticsAcquireReleaseMask);
7252 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7253 } else {
7254 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7255 }
John Kessenich82979362017-12-11 04:02:24 -07007256 } else {
7257 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7258 spv::MemorySemanticsWorkgroupMemoryMask |
7259 spv::MemorySemanticsAcquireReleaseMask);
7260 }
John Kessenich140f3df2015-06-26 16:58:36 -06007261 return 0;
7262 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007263 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7264 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007265 return 0;
7266 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007267 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7268 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007269 return 0;
7270 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007271 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7272 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007273 return 0;
7274 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007275 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7276 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007277 return 0;
7278 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007279 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7280 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007281 return 0;
7282 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007283 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7284 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007285 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007286 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007287 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007288 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007289 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007290 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007291 case glslang::EOpDeviceMemoryBarrier:
7292 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7293 spv::MemorySemanticsImageMemoryMask |
7294 spv::MemorySemanticsAcquireReleaseMask);
7295 return 0;
7296 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7297 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7298 spv::MemorySemanticsImageMemoryMask |
7299 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007300 return 0;
7301 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007302 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7303 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007304 return 0;
7305 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007306 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7307 spv::MemorySemanticsWorkgroupMemoryMask |
7308 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007309 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007310 case glslang::EOpSubgroupBarrier:
7311 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7312 spv::MemorySemanticsAcquireReleaseMask);
7313 return spv::NoResult;
7314 case glslang::EOpSubgroupMemoryBarrier:
7315 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7316 spv::MemorySemanticsAcquireReleaseMask);
7317 return spv::NoResult;
7318 case glslang::EOpSubgroupMemoryBarrierBuffer:
7319 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7320 spv::MemorySemanticsAcquireReleaseMask);
7321 return spv::NoResult;
7322 case glslang::EOpSubgroupMemoryBarrierImage:
7323 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7324 spv::MemorySemanticsAcquireReleaseMask);
7325 return spv::NoResult;
7326 case glslang::EOpSubgroupMemoryBarrierShared:
7327 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7328 spv::MemorySemanticsAcquireReleaseMask);
7329 return spv::NoResult;
7330 case glslang::EOpSubgroupElect: {
7331 std::vector<spv::Id> operands;
7332 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7333 }
Rex Xu9d93a232016-05-05 12:30:44 +08007334#ifdef AMD_EXTENSIONS
7335 case glslang::EOpTime:
7336 {
7337 std::vector<spv::Id> args; // Dummy arguments
7338 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7339 return builder.setPrecision(id, precision);
7340 }
7341#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007342#ifdef NV_EXTENSIONS
7343 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007344 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007345 return 0;
7346 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007347 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007348 return 0;
7349#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007350 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007351 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007352 return 0;
7353 }
7354}
7355
7356spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7357{
John Kessenich2f273362015-07-18 22:34:27 -06007358 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007359 spv::Id id;
7360 if (symbolValues.end() != iter) {
7361 id = iter->second;
7362 return id;
7363 }
7364
7365 // it was not found, create it
7366 id = createSpvVariable(symbol);
7367 symbolValues[symbol->getId()] = id;
7368
Rex Xuc884b4a2016-06-29 15:03:44 +08007369 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007370 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7371 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7372 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007373#ifdef NV_EXTENSIONS
7374 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7375#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007376 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007377 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007378 if (symbol->getQualifier().hasIndex())
7379 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7380 if (symbol->getQualifier().hasComponent())
7381 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007382 // atomic counters use this:
7383 if (symbol->getQualifier().hasOffset())
7384 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007385 }
7386
scygan2c864272016-05-18 18:09:17 +02007387 if (symbol->getQualifier().hasLocation())
7388 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007389 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007390 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007391 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007392 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007393 }
John Kessenich140f3df2015-06-26 16:58:36 -06007394 if (symbol->getQualifier().hasSet())
7395 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007396 else if (IsDescriptorResource(symbol->getType())) {
7397 // default to 0
7398 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7399 }
John Kessenich140f3df2015-06-26 16:58:36 -06007400 if (symbol->getQualifier().hasBinding())
7401 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007402 else if (IsDescriptorResource(symbol->getType())) {
7403 // default to 0
7404 builder.addDecoration(id, spv::DecorationBinding, 0);
7405 }
John Kessenich6c292d32016-02-15 20:58:50 -07007406 if (symbol->getQualifier().hasAttachment())
7407 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007408 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007409 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007410 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007411 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007412 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7413 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7414 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7415 }
7416 if (symbol->getQualifier().hasXfbOffset())
7417 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007418 }
7419
Rex Xu1da878f2016-02-21 20:59:01 +08007420 if (symbol->getType().isImage()) {
7421 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007422 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007423 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007424 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007425 }
7426
John Kessenich140f3df2015-06-26 16:58:36 -06007427 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007428 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007429 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007430 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007431
John Kessenich5611c6d2018-04-05 11:25:02 -06007432 // nonuniform
7433 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7434
John Kessenichecba76f2017-01-06 00:34:48 -07007435#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007436 if (builtIn == spv::BuiltInSampleMask) {
7437 spv::Decoration decoration;
7438 // GL_NV_sample_mask_override_coverage extension
7439 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007440 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007441 else
7442 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007443 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007444 if (decoration != spv::DecorationMax) {
7445 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7446 }
7447 }
chaoc771d89f2017-01-13 01:10:53 -08007448 else if (builtIn == spv::BuiltInLayer) {
7449 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007450 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007451 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007452 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7453 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7454 }
John Kessenichb41bff62017-08-11 13:07:17 -06007455 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007456 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7457 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007458 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7459 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7460 }
7461 }
7462
chaoc6e5acae2016-12-20 13:28:52 -08007463 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007464 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007465 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007466 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7467 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007468 if (symbol->getQualifier().pervertexNV) {
7469 builder.addDecoration(id, spv::DecorationPerVertexNV);
7470 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7471 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7472 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007473#endif
7474
John Kessenich5d610ee2018-03-07 18:05:55 -07007475 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7476 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7477 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7478 symbol->getType().getQualifier().semanticName);
7479 }
7480
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007481 if (symbol->getBasicType() == glslang::EbtReference) {
7482 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7483 }
7484
John Kessenich140f3df2015-06-26 16:58:36 -06007485 return id;
7486}
7487
Chao Chen3c366992018-09-19 11:41:59 -07007488#ifdef NV_EXTENSIONS
7489// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7490void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7491{
7492 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007493 if (qualifier.perPrimitiveNV) {
7494 // Need to add capability/extension for fragment shader.
7495 // Mesh shader already adds this by default.
7496 if (glslangIntermediate->getStage() == EShLangFragment) {
7497 builder.addCapability(spv::CapabilityMeshShadingNV);
7498 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7499 }
Chao Chen3c366992018-09-19 11:41:59 -07007500 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007501 }
Chao Chen3c366992018-09-19 11:41:59 -07007502 if (qualifier.perViewNV)
7503 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7504 if (qualifier.perTaskNV)
7505 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7506 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007507 if (qualifier.perPrimitiveNV) {
7508 // Need to add capability/extension for fragment shader.
7509 // Mesh shader already adds this by default.
7510 if (glslangIntermediate->getStage() == EShLangFragment) {
7511 builder.addCapability(spv::CapabilityMeshShadingNV);
7512 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7513 }
Chao Chen3c366992018-09-19 11:41:59 -07007514 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007515 }
Chao Chen3c366992018-09-19 11:41:59 -07007516 if (qualifier.perViewNV)
7517 builder.addDecoration(id, spv::DecorationPerViewNV);
7518 if (qualifier.perTaskNV)
7519 builder.addDecoration(id, spv::DecorationPerTaskNV);
7520 }
7521}
7522#endif
7523
John Kessenich55e7d112015-11-15 21:33:39 -07007524// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007525// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007526//
7527// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7528//
7529// Recursively walk the nodes. The nodes form a tree whose leaves are
7530// regular constants, which themselves are trees that createSpvConstant()
7531// recursively walks. So, this function walks the "top" of the tree:
7532// - emit specialization constant-building instructions for specConstant
7533// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007534spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007535{
John Kessenich7cc0e282016-03-20 00:46:02 -06007536 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007537
qining4f4bb812016-04-03 23:55:17 -04007538 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007539 if (! node.getQualifier().specConstant) {
7540 // hand off to the non-spec-constant path
7541 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7542 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007543 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007544 nextConst, false);
7545 }
7546
7547 // We now know we have a specialization constant to build
7548
John Kessenichd94c0032016-05-30 19:29:40 -06007549 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007550 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7551 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7552 std::vector<spv::Id> dimConstId;
7553 for (int dim = 0; dim < 3; ++dim) {
7554 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7555 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007556 if (specConst) {
7557 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7558 glslangIntermediate->getLocalSizeSpecId(dim));
7559 }
qining4f4bb812016-04-03 23:55:17 -04007560 }
7561 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7562 }
7563
7564 // An AST node labelled as specialization constant should be a symbol node.
7565 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7566 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007567 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007568 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007569 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7570 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7571 // will set the builder into spec constant op instruction generating mode.
7572 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007573 result = accessChainLoad(sub_tree->getType());
7574 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007575 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007576 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007577 } else {
7578 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007579 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007580 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007581 builder.addName(result, sn->getName().c_str());
7582 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007583 }
qining4f4bb812016-04-03 23:55:17 -04007584
7585 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7586 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007587 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007588 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007589}
7590
John Kessenich140f3df2015-06-26 16:58:36 -06007591// Use 'consts' as the flattened glslang source of scalar constants to recursively
7592// build the aggregate SPIR-V constant.
7593//
7594// If there are not enough elements present in 'consts', 0 will be substituted;
7595// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7596//
qining08408382016-03-21 09:51:37 -04007597spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007598{
7599 // vector of constants for SPIR-V
7600 std::vector<spv::Id> spvConsts;
7601
7602 // Type is used for struct and array constants
7603 spv::Id typeId = convertGlslangToSpvType(glslangType);
7604
7605 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007606 glslang::TType elementType(glslangType, 0);
7607 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007608 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007609 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007610 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007611 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007612 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007613 } else if (glslangType.isCoopMat()) {
7614 glslang::TType componentType(glslangType.getBasicType());
7615 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007616 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007617 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7618 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007619 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007620 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007621 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7622 bool zero = nextConst >= consts.size();
7623 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007624 case glslang::EbtInt8:
7625 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7626 break;
7627 case glslang::EbtUint8:
7628 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7629 break;
7630 case glslang::EbtInt16:
7631 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7632 break;
7633 case glslang::EbtUint16:
7634 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7635 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007636 case glslang::EbtInt:
7637 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7638 break;
7639 case glslang::EbtUint:
7640 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7641 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007642 case glslang::EbtInt64:
7643 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7644 break;
7645 case glslang::EbtUint64:
7646 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7647 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007648 case glslang::EbtFloat:
7649 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7650 break;
7651 case glslang::EbtDouble:
7652 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7653 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007654 case glslang::EbtFloat16:
7655 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7656 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007657 case glslang::EbtBool:
7658 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7659 break;
7660 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007661 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007662 break;
7663 }
7664 ++nextConst;
7665 }
7666 } else {
7667 // we have a non-aggregate (scalar) constant
7668 bool zero = nextConst >= consts.size();
7669 spv::Id scalar = 0;
7670 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007671 case glslang::EbtInt8:
7672 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7673 break;
7674 case glslang::EbtUint8:
7675 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7676 break;
7677 case glslang::EbtInt16:
7678 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7679 break;
7680 case glslang::EbtUint16:
7681 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7682 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007683 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007684 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007685 break;
7686 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007687 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007688 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007689 case glslang::EbtInt64:
7690 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7691 break;
7692 case glslang::EbtUint64:
7693 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7694 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007695 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007696 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007697 break;
7698 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007699 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007700 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007701 case glslang::EbtFloat16:
7702 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7703 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007704 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007705 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007706 break;
7707 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007708 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007709 break;
7710 }
7711 ++nextConst;
7712 return scalar;
7713 }
7714
7715 return builder.makeCompositeConstant(typeId, spvConsts);
7716}
7717
John Kessenich7c1aa102015-10-15 13:29:11 -06007718// Return true if the node is a constant or symbol whose reading has no
7719// non-trivial observable cost or effect.
7720bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7721{
7722 // don't know what this is
7723 if (node == nullptr)
7724 return false;
7725
7726 // a constant is safe
7727 if (node->getAsConstantUnion() != nullptr)
7728 return true;
7729
7730 // not a symbol means non-trivial
7731 if (node->getAsSymbolNode() == nullptr)
7732 return false;
7733
7734 // a symbol, depends on what's being read
7735 switch (node->getType().getQualifier().storage) {
7736 case glslang::EvqTemporary:
7737 case glslang::EvqGlobal:
7738 case glslang::EvqIn:
7739 case glslang::EvqInOut:
7740 case glslang::EvqConst:
7741 case glslang::EvqConstReadOnly:
7742 case glslang::EvqUniform:
7743 return true;
7744 default:
7745 return false;
7746 }
qining25262b32016-05-06 17:25:16 -04007747}
John Kessenich7c1aa102015-10-15 13:29:11 -06007748
7749// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007750// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007751// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007752// Return true if trivial.
7753bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7754{
7755 if (node == nullptr)
7756 return false;
7757
John Kessenich84cc15f2017-05-24 16:44:47 -06007758 // count non scalars as trivial, as well as anything coming from HLSL
7759 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007760 return true;
7761
John Kessenich7c1aa102015-10-15 13:29:11 -06007762 // symbols and constants are trivial
7763 if (isTrivialLeaf(node))
7764 return true;
7765
7766 // otherwise, it needs to be a simple operation or one or two leaf nodes
7767
7768 // not a simple operation
7769 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7770 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7771 if (binaryNode == nullptr && unaryNode == nullptr)
7772 return false;
7773
7774 // not on leaf nodes
7775 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7776 return false;
7777
7778 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7779 return false;
7780 }
7781
7782 switch (node->getAsOperator()->getOp()) {
7783 case glslang::EOpLogicalNot:
7784 case glslang::EOpConvIntToBool:
7785 case glslang::EOpConvUintToBool:
7786 case glslang::EOpConvFloatToBool:
7787 case glslang::EOpConvDoubleToBool:
7788 case glslang::EOpEqual:
7789 case glslang::EOpNotEqual:
7790 case glslang::EOpLessThan:
7791 case glslang::EOpGreaterThan:
7792 case glslang::EOpLessThanEqual:
7793 case glslang::EOpGreaterThanEqual:
7794 case glslang::EOpIndexDirect:
7795 case glslang::EOpIndexDirectStruct:
7796 case glslang::EOpLogicalXor:
7797 case glslang::EOpAny:
7798 case glslang::EOpAll:
7799 return true;
7800 default:
7801 return false;
7802 }
7803}
7804
7805// Emit short-circuiting code, where 'right' is never evaluated unless
7806// the left side is true (for &&) or false (for ||).
7807spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7808{
7809 spv::Id boolTypeId = builder.makeBoolType();
7810
7811 // emit left operand
7812 builder.clearAccessChain();
7813 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007814 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007815
7816 // Operands to accumulate OpPhi operands
7817 std::vector<spv::Id> phiOperands;
7818 // accumulate left operand's phi information
7819 phiOperands.push_back(leftId);
7820 phiOperands.push_back(builder.getBuildPoint()->getId());
7821
7822 // Make the two kinds of operation symmetric with a "!"
7823 // || => emit "if (! left) result = right"
7824 // && => emit "if ( left) result = right"
7825 //
7826 // TODO: this runtime "not" for || could be avoided by adding functionality
7827 // to 'builder' to have an "else" without an "then"
7828 if (op == glslang::EOpLogicalOr)
7829 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7830
7831 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007832 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007833
7834 // emit right operand as the "then" part of the "if"
7835 builder.clearAccessChain();
7836 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007837 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007838
7839 // accumulate left operand's phi information
7840 phiOperands.push_back(rightId);
7841 phiOperands.push_back(builder.getBuildPoint()->getId());
7842
7843 // finish the "if"
7844 ifBuilder.makeEndIf();
7845
7846 // phi together the two results
7847 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7848}
7849
Frank Henigman541f7bb2018-01-16 00:18:26 -05007850#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007851// Return type Id of the imported set of extended instructions corresponds to the name.
7852// Import this set if it has not been imported yet.
7853spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7854{
7855 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7856 return extBuiltinMap[name];
7857 else {
Rex Xu51596642016-09-21 18:56:12 +08007858 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007859 spv::Id extBuiltins = builder.import(name);
7860 extBuiltinMap[name] = extBuiltins;
7861 return extBuiltins;
7862 }
7863}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007864#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007865
John Kessenich140f3df2015-06-26 16:58:36 -06007866}; // end anonymous namespace
7867
7868namespace glslang {
7869
John Kessenich68d78fd2015-07-12 19:28:10 -06007870void GetSpirvVersion(std::string& version)
7871{
John Kessenich9e55f632015-07-15 10:03:39 -06007872 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007873 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007874 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007875 version = buf;
7876}
7877
John Kessenicha372a3e2017-11-02 22:32:14 -06007878// For low-order part of the generator's magic number. Bump up
7879// when there is a change in the style (e.g., if SSA form changes,
7880// or a different instruction sequence to do something gets used).
7881int GetSpirvGeneratorVersion()
7882{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007883 // return 1; // start
7884 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007885 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007886 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007887 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007888 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7889 // versions 4 and 6 each generate OpArrayLength as it has long been done
7890 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007891}
7892
John Kessenich140f3df2015-06-26 16:58:36 -06007893// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007894void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007895{
7896 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007897 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007898 if (out.fail())
7899 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007900 for (int i = 0; i < (int)spirv.size(); ++i) {
7901 unsigned int word = spirv[i];
7902 out.write((const char*)&word, 4);
7903 }
7904 out.close();
7905}
7906
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007907// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007908void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007909{
7910 std::ofstream out;
7911 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007912 if (out.fail())
7913 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007914 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007915 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007916 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007917 if (varName != nullptr) {
7918 out << "\t #pragma once" << std::endl;
7919 out << "const uint32_t " << varName << "[] = {" << std::endl;
7920 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007921 const int WORDS_PER_LINE = 8;
7922 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7923 out << "\t";
7924 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7925 const unsigned int word = spirv[i + j];
7926 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7927 if (i + j + 1 < (int)spirv.size()) {
7928 out << ",";
7929 }
7930 }
7931 out << std::endl;
7932 }
Flavio15017db2017-02-15 14:29:33 -08007933 if (varName != nullptr) {
7934 out << "};";
7935 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007936 out.close();
7937}
7938
John Kessenich140f3df2015-06-26 16:58:36 -06007939//
7940// Set up the glslang traversal
7941//
John Kessenich4e11b612018-08-30 16:56:59 -06007942void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007943{
Lei Zhang17535f72016-05-04 15:55:59 -04007944 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007945 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007946}
7947
John Kessenich4e11b612018-08-30 16:56:59 -06007948void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007949 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007950{
John Kessenich140f3df2015-06-26 16:58:36 -06007951 TIntermNode* root = intermediate.getTreeRoot();
7952
7953 if (root == 0)
7954 return;
7955
John Kessenich4e11b612018-08-30 16:56:59 -06007956 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007957 if (options == nullptr)
7958 options = &defaultOptions;
7959
John Kessenich4e11b612018-08-30 16:56:59 -06007960 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007961
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007962 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007963 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007964 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007965 it.dumpSpv(spirv);
7966
GregFfb03a552018-03-29 11:49:14 -06007967#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007968 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7969 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007970 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007971 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007972
John Kessenich4e11b612018-08-30 16:56:59 -06007973 if (options->validate)
7974 SpirvToolsValidate(intermediate, spirv, logger);
7975
John Kessenich717c80a2018-08-23 15:17:10 -06007976 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007977 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007978
GregFcd1f1692017-09-21 18:40:22 -06007979#endif
7980
John Kessenich4e11b612018-08-30 16:56:59 -06007981 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06007982}
7983
7984}; // end namespace glslang