blob: fe06c834d94aafa8d6779e9b24ea7f2f5045a07f [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
John Kessenich121853f2017-05-31 17:11:16 -0600212 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600213 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600214 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700215 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600216 int sequenceDepth;
217
Lei Zhang17535f72016-05-04 15:55:59 -0400218 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400219
John Kessenich140f3df2015-06-26 16:58:36 -0600220 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
221 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700222 bool inEntryPoint;
223 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700224 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 -0700225 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600226 const glslang::TIntermediate* glslangIntermediate;
227 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800228 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600229
John Kessenich2f273362015-07-18 22:34:27 -0600230 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600231 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600232 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700233 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700234 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
235 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600236 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700237 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600238 // Map pointee types for EbtReference to their forward pointers
239 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich140f3df2015-06-26 16:58:36 -0600240};
241
242//
243// Helper functions for translating glslang representations to SPIR-V enumerants.
244//
245
246// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700247spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600248{
John Kessenich66e2faf2016-03-12 18:34:36 -0700249 switch (source) {
250 case glslang::EShSourceGlsl:
251 switch (profile) {
252 case ENoProfile:
253 case ECoreProfile:
254 case ECompatibilityProfile:
255 return spv::SourceLanguageGLSL;
256 case EEsProfile:
257 return spv::SourceLanguageESSL;
258 default:
259 return spv::SourceLanguageUnknown;
260 }
261 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600262 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600263 default:
264 return spv::SourceLanguageUnknown;
265 }
266}
267
268// Translate glslang language (stage) to SPIR-V execution model.
269spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
270{
271 switch (stage) {
272 case EShLangVertex: return spv::ExecutionModelVertex;
273 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
274 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
275 case EShLangGeometry: return spv::ExecutionModelGeometry;
276 case EShLangFragment: return spv::ExecutionModelFragment;
277 case EShLangCompute: return spv::ExecutionModelGLCompute;
Chao Chen3c366992018-09-19 11:41:59 -0700278#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -0700279 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
280 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
281 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
282 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
283 case EShLangMissNV: return spv::ExecutionModelMissNV;
284 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700285 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
286 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
287#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600288 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700289 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600290 return spv::ExecutionModelFragment;
291 }
292}
293
John Kessenich140f3df2015-06-26 16:58:36 -0600294// Translate glslang sampler type to SPIR-V dimensionality.
295spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
296{
297 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700298 case glslang::Esd1D: return spv::Dim1D;
299 case glslang::Esd2D: return spv::Dim2D;
300 case glslang::Esd3D: return spv::Dim3D;
301 case glslang::EsdCube: return spv::DimCube;
302 case glslang::EsdRect: return spv::DimRect;
303 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700304 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600305 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700306 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600307 return spv::Dim2D;
308 }
309}
310
John Kessenichf6640762016-08-01 19:44:00 -0600311// Translate glslang precision to SPIR-V precision decorations.
312spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600313{
John Kessenichf6640762016-08-01 19:44:00 -0600314 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700315 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600316 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600317 default:
318 return spv::NoPrecision;
319 }
320}
321
John Kessenichf6640762016-08-01 19:44:00 -0600322// Translate glslang type to SPIR-V precision decorations.
323spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
324{
325 return TranslatePrecisionDecoration(type.getQualifier().precision);
326}
327
John Kessenich140f3df2015-06-26 16:58:36 -0600328// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600329spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600330{
331 if (type.getBasicType() == glslang::EbtBlock) {
332 switch (type.getQualifier().storage) {
333 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600334 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600335 case glslang::EvqVaryingIn: return spv::DecorationBlock;
336 case glslang::EvqVaryingOut: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700337#ifdef NV_EXTENSIONS
338 case glslang::EvqPayloadNV: return spv::DecorationBlock;
339 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
340 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700341 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
342 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700343#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600344 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700345 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600346 break;
347 }
348 }
349
John Kessenich4016e382016-07-15 11:53:56 -0600350 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600351}
352
Rex Xu1da878f2016-02-21 20:59:01 +0800353// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500354void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800355{
Jeff Bolz36831c92018-09-05 10:11:41 -0500356 if (!useVulkanMemoryModel) {
357 if (qualifier.coherent)
358 memory.push_back(spv::DecorationCoherent);
359 if (qualifier.volatil) {
360 memory.push_back(spv::DecorationVolatile);
361 memory.push_back(spv::DecorationCoherent);
362 }
John Kessenich14b85d32018-06-04 15:36:03 -0600363 }
Rex Xu1da878f2016-02-21 20:59:01 +0800364 if (qualifier.restrict)
365 memory.push_back(spv::DecorationRestrict);
366 if (qualifier.readonly)
367 memory.push_back(spv::DecorationNonWritable);
368 if (qualifier.writeonly)
369 memory.push_back(spv::DecorationNonReadable);
370}
371
John Kessenich140f3df2015-06-26 16:58:36 -0600372// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700373spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600374{
375 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700376 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600377 case glslang::ElmRowMajor:
378 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700379 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600380 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700381 default:
382 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600383 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600384 }
385 } else {
386 switch (type.getBasicType()) {
387 default:
John Kessenich4016e382016-07-15 11:53:56 -0600388 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600389 break;
390 case glslang::EbtBlock:
391 switch (type.getQualifier().storage) {
392 case glslang::EvqUniform:
393 case glslang::EvqBuffer:
394 switch (type.getQualifier().layoutPacking) {
395 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600396 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
397 default:
John Kessenich4016e382016-07-15 11:53:56 -0600398 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600399 }
400 case glslang::EvqVaryingIn:
401 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700402 if (type.getQualifier().isTaskMemory()) {
403 switch (type.getQualifier().layoutPacking) {
404 case glslang::ElpShared: return spv::DecorationGLSLShared;
405 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
406 default: break;
407 }
408 } else {
409 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
410 }
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
Chao Chenb50c02e2018-09-19 11:42:24 -0700412#ifdef NV_EXTENSIONS
413 case glslang::EvqPayloadNV:
414 case glslang::EvqPayloadInNV:
415 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700416 case glslang::EvqCallableDataNV:
417 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700418 return spv::DecorationMax;
419#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600420 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700421 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600422 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600423 }
424 }
425 }
426}
427
428// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600429// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700430// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800431spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600432{
Rex Xubbceed72016-05-21 09:40:44 +0800433 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700434 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600435 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800436 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700437 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700438 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600439 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800440#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800441 else if (qualifier.explicitInterp) {
442 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800443 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800444 }
Rex Xu9d93a232016-05-05 12:30:44 +0800445#endif
Rex Xubbceed72016-05-21 09:40:44 +0800446 else
John Kessenich4016e382016-07-15 11:53:56 -0600447 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800448}
449
450// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600451// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800452// should be applied.
453spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
454{
455 if (qualifier.patch)
456 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700457 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600458 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700459 else if (qualifier.sample) {
460 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600461 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700462 } else
John Kessenich4016e382016-07-15 11:53:56 -0600463 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600464}
465
John Kessenich92187592016-02-01 13:45:25 -0700466// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700467spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600468{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700469 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600470 return spv::DecorationInvariant;
471 else
John Kessenich4016e382016-07-15 11:53:56 -0600472 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600473}
474
qining9220dbb2016-05-04 17:34:38 -0400475// If glslang type is noContraction, return SPIR-V NoContraction decoration.
476spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
477{
478 if (qualifier.noContraction)
479 return spv::DecorationNoContraction;
480 else
John Kessenich4016e382016-07-15 11:53:56 -0600481 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400482}
483
John Kessenich5611c6d2018-04-05 11:25:02 -0600484// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
485spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
486{
487 if (qualifier.isNonUniform()) {
488 builder.addExtension("SPV_EXT_descriptor_indexing");
489 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
490 return spv::DecorationNonUniformEXT;
491 } else
492 return spv::DecorationMax;
493}
494
Jeff Bolz36831c92018-09-05 10:11:41 -0500495spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
496{
497 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
498 return spv::MemoryAccessMaskNone;
499 }
500 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
501 if (coherentFlags.volatil ||
502 coherentFlags.coherent ||
503 coherentFlags.devicecoherent ||
504 coherentFlags.queuefamilycoherent ||
505 coherentFlags.workgroupcoherent ||
506 coherentFlags.subgroupcoherent) {
507 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
508 spv::MemoryAccessMakePointerVisibleKHRMask;
509 }
510 if (coherentFlags.nonprivate) {
511 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
512 }
513 if (coherentFlags.volatil) {
514 mask = mask | spv::MemoryAccessVolatileMask;
515 }
516 if (mask != spv::MemoryAccessMaskNone) {
517 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
518 }
519 return mask;
520}
521
522spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
523{
524 if (!glslangIntermediate->usingVulkanMemoryModel()) {
525 return spv::ImageOperandsMaskNone;
526 }
527 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
528 if (coherentFlags.volatil ||
529 coherentFlags.coherent ||
530 coherentFlags.devicecoherent ||
531 coherentFlags.queuefamilycoherent ||
532 coherentFlags.workgroupcoherent ||
533 coherentFlags.subgroupcoherent) {
534 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
535 spv::ImageOperandsMakeTexelVisibleKHRMask;
536 }
537 if (coherentFlags.nonprivate) {
538 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
539 }
540 if (coherentFlags.volatil) {
541 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
542 }
543 if (mask != spv::ImageOperandsMaskNone) {
544 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
545 }
546 return mask;
547}
548
549spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
550{
551 spv::Builder::AccessChain::CoherentFlags flags;
552 flags.coherent = type.getQualifier().coherent;
553 flags.devicecoherent = type.getQualifier().devicecoherent;
554 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
555 // shared variables are implicitly workgroupcoherent in GLSL.
556 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
557 type.getQualifier().storage == glslang::EvqShared;
558 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600559 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500560 // *coherent variables are implicitly nonprivate in GLSL
561 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500562 flags.subgroupcoherent ||
563 flags.workgroupcoherent ||
564 flags.queuefamilycoherent ||
565 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600566 flags.coherent ||
567 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500568 flags.isImage = type.getBasicType() == glslang::EbtSampler;
569 return flags;
570}
571
572spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
573{
574 spv::Scope scope;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600575 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500576 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
577 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
578 } else if (coherentFlags.devicecoherent) {
579 scope = spv::ScopeDevice;
580 } else if (coherentFlags.queuefamilycoherent) {
581 scope = spv::ScopeQueueFamilyKHR;
582 } else if (coherentFlags.workgroupcoherent) {
583 scope = spv::ScopeWorkgroup;
584 } else if (coherentFlags.subgroupcoherent) {
585 scope = spv::ScopeSubgroup;
586 } else {
587 scope = spv::ScopeMax;
588 }
589 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
590 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
591 }
592 return scope;
593}
594
David Netoa901ffe2016-06-08 14:11:40 +0100595// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
596// associated capabilities when required. For some built-in variables, a capability
597// is generated only when using the variable in an executable instruction, but not when
598// just declaring a struct member variable with it. This is true for PointSize,
599// ClipDistance, and CullDistance.
600spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600601{
602 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700603 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600604 // Defer adding the capability until the built-in is actually used.
605 if (! memberDeclaration) {
606 switch (glslangIntermediate->getStage()) {
607 case EShLangGeometry:
608 builder.addCapability(spv::CapabilityGeometryPointSize);
609 break;
610 case EShLangTessControl:
611 case EShLangTessEvaluation:
612 builder.addCapability(spv::CapabilityTessellationPointSize);
613 break;
614 default:
615 break;
616 }
John Kessenich92187592016-02-01 13:45:25 -0700617 }
618 return spv::BuiltInPointSize;
619
John Kessenichebb50532016-05-16 19:22:05 -0600620 // These *Distance capabilities logically belong here, but if the member is declared and
621 // then never used, consumers of SPIR-V prefer the capability not be declared.
622 // They are now generated when used, rather than here when declared.
623 // Potentially, the specification should be more clear what the minimum
624 // use needed is to trigger the capability.
625 //
John Kessenich92187592016-02-01 13:45:25 -0700626 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100627 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800628 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700629 return spv::BuiltInClipDistance;
630
631 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100632 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800633 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700634 return spv::BuiltInCullDistance;
635
636 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600637 builder.addCapability(spv::CapabilityMultiViewport);
638 if (glslangIntermediate->getStage() == EShLangVertex ||
639 glslangIntermediate->getStage() == EShLangTessControl ||
640 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800641
John Kessenichba6a3c22017-09-13 13:22:50 -0600642 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
643 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800644 }
John Kessenich92187592016-02-01 13:45:25 -0700645 return spv::BuiltInViewportIndex;
646
John Kessenich5e801132016-02-15 11:09:46 -0700647 case glslang::EbvSampleId:
648 builder.addCapability(spv::CapabilitySampleRateShading);
649 return spv::BuiltInSampleId;
650
651 case glslang::EbvSamplePosition:
652 builder.addCapability(spv::CapabilitySampleRateShading);
653 return spv::BuiltInSamplePosition;
654
655 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700656 return spv::BuiltInSampleMask;
657
John Kessenich78a45572016-07-08 14:05:15 -0600658 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700659#ifdef NV_EXTENSIONS
660 if (glslangIntermediate->getStage() == EShLangMeshNV) {
661 return spv::BuiltInLayer;
662 }
663#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600664 builder.addCapability(spv::CapabilityGeometry);
665 if (glslangIntermediate->getStage() == EShLangVertex ||
666 glslangIntermediate->getStage() == EShLangTessControl ||
667 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800668
John Kessenichba6a3c22017-09-13 13:22:50 -0600669 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
670 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800671 }
John Kessenich78a45572016-07-08 14:05:15 -0600672 return spv::BuiltInLayer;
673
John Kessenich140f3df2015-06-26 16:58:36 -0600674 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600675 case glslang::EbvVertexId: return spv::BuiltInVertexId;
676 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700677 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
678 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800679
John Kessenichda581a22015-10-14 14:10:30 -0600680 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700681 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800682 builder.addCapability(spv::CapabilityDrawParameters);
683 return spv::BuiltInBaseVertex;
684
John Kessenichda581a22015-10-14 14:10:30 -0600685 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700686 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800687 builder.addCapability(spv::CapabilityDrawParameters);
688 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200689
John Kessenichda581a22015-10-14 14:10:30 -0600690 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700691 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800692 builder.addCapability(spv::CapabilityDrawParameters);
693 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200694
695 case glslang::EbvPrimitiveId:
696 if (glslangIntermediate->getStage() == EShLangFragment)
697 builder.addCapability(spv::CapabilityGeometry);
698 return spv::BuiltInPrimitiveId;
699
Rex Xu37cdcee2017-06-29 17:46:34 +0800700 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800701 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
702 builder.addCapability(spv::CapabilityStencilExportEXT);
703 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800704
John Kessenich140f3df2015-06-26 16:58:36 -0600705 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600706 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
707 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
708 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
709 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
710 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
711 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
712 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600713 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
714 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
715 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
716 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
717 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
718 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
719 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
720 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800721
Rex Xu574ab042016-04-14 16:53:07 +0800722 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800723 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800724 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
725 return spv::BuiltInSubgroupSize;
726
Rex Xu574ab042016-04-14 16:53:07 +0800727 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800728 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800729 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
730 return spv::BuiltInSubgroupLocalInvocationId;
731
Rex Xu574ab042016-04-14 16:53:07 +0800732 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800733 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
734 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
735 return spv::BuiltInSubgroupEqMaskKHR;
736
Rex Xu574ab042016-04-14 16:53:07 +0800737 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800738 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
739 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
740 return spv::BuiltInSubgroupGeMaskKHR;
741
Rex Xu574ab042016-04-14 16:53:07 +0800742 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800743 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
744 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
745 return spv::BuiltInSubgroupGtMaskKHR;
746
Rex Xu574ab042016-04-14 16:53:07 +0800747 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800748 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
749 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
750 return spv::BuiltInSubgroupLeMaskKHR;
751
Rex Xu574ab042016-04-14 16:53:07 +0800752 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800753 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
754 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
755 return spv::BuiltInSubgroupLtMaskKHR;
756
John Kessenich66011cb2018-03-06 16:12:04 -0700757 case glslang::EbvNumSubgroups:
758 builder.addCapability(spv::CapabilityGroupNonUniform);
759 return spv::BuiltInNumSubgroups;
760
761 case glslang::EbvSubgroupID:
762 builder.addCapability(spv::CapabilityGroupNonUniform);
763 return spv::BuiltInSubgroupId;
764
765 case glslang::EbvSubgroupSize2:
766 builder.addCapability(spv::CapabilityGroupNonUniform);
767 return spv::BuiltInSubgroupSize;
768
769 case glslang::EbvSubgroupInvocation2:
770 builder.addCapability(spv::CapabilityGroupNonUniform);
771 return spv::BuiltInSubgroupLocalInvocationId;
772
773 case glslang::EbvSubgroupEqMask2:
774 builder.addCapability(spv::CapabilityGroupNonUniform);
775 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
776 return spv::BuiltInSubgroupEqMask;
777
778 case glslang::EbvSubgroupGeMask2:
779 builder.addCapability(spv::CapabilityGroupNonUniform);
780 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
781 return spv::BuiltInSubgroupGeMask;
782
783 case glslang::EbvSubgroupGtMask2:
784 builder.addCapability(spv::CapabilityGroupNonUniform);
785 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
786 return spv::BuiltInSubgroupGtMask;
787
788 case glslang::EbvSubgroupLeMask2:
789 builder.addCapability(spv::CapabilityGroupNonUniform);
790 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
791 return spv::BuiltInSubgroupLeMask;
792
793 case glslang::EbvSubgroupLtMask2:
794 builder.addCapability(spv::CapabilityGroupNonUniform);
795 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
796 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800797#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800798 case glslang::EbvBaryCoordNoPersp:
799 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
800 return spv::BuiltInBaryCoordNoPerspAMD;
801
802 case glslang::EbvBaryCoordNoPerspCentroid:
803 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
804 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
805
806 case glslang::EbvBaryCoordNoPerspSample:
807 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
808 return spv::BuiltInBaryCoordNoPerspSampleAMD;
809
810 case glslang::EbvBaryCoordSmooth:
811 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
812 return spv::BuiltInBaryCoordSmoothAMD;
813
814 case glslang::EbvBaryCoordSmoothCentroid:
815 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
816 return spv::BuiltInBaryCoordSmoothCentroidAMD;
817
818 case glslang::EbvBaryCoordSmoothSample:
819 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
820 return spv::BuiltInBaryCoordSmoothSampleAMD;
821
822 case glslang::EbvBaryCoordPullModel:
823 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
824 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800825#endif
chaoc771d89f2017-01-13 01:10:53 -0800826
John Kessenich6c8aaac2017-02-27 01:20:51 -0700827 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700828 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700829 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700830 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700831
832 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700833 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700834 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700835 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700836
Daniel Koch5154db52018-11-26 10:01:58 -0500837 case glslang::EbvFragSizeEXT:
838 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
839 builder.addCapability(spv::CapabilityFragmentDensityEXT);
840 return spv::BuiltInFragSizeEXT;
841
842 case glslang::EbvFragInvocationCountEXT:
843 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
844 builder.addCapability(spv::CapabilityFragmentDensityEXT);
845 return spv::BuiltInFragInvocationCountEXT;
846
chaoc771d89f2017-01-13 01:10:53 -0800847#ifdef NV_EXTENSIONS
848 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800849 if (!memberDeclaration) {
850 builder.addExtension(spv::E_SPV_NV_viewport_array2);
851 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
852 }
chaoc771d89f2017-01-13 01:10:53 -0800853 return spv::BuiltInViewportMaskNV;
854 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800855 if (!memberDeclaration) {
856 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
857 builder.addCapability(spv::CapabilityShaderStereoViewNV);
858 }
chaoc771d89f2017-01-13 01:10:53 -0800859 return spv::BuiltInSecondaryPositionNV;
860 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800861 if (!memberDeclaration) {
862 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
863 builder.addCapability(spv::CapabilityShaderStereoViewNV);
864 }
chaoc771d89f2017-01-13 01:10:53 -0800865 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800866 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800867 if (!memberDeclaration) {
868 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
869 builder.addCapability(spv::CapabilityPerViewAttributesNV);
870 }
chaocdf3956c2017-02-14 14:52:34 -0800871 return spv::BuiltInPositionPerViewNV;
872 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800873 if (!memberDeclaration) {
874 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
875 builder.addCapability(spv::CapabilityPerViewAttributesNV);
876 }
chaocdf3956c2017-02-14 14:52:34 -0800877 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700878 case glslang::EbvFragFullyCoveredNV:
879 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
880 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
881 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700882 case glslang::EbvFragmentSizeNV:
883 builder.addExtension(spv::E_SPV_NV_shading_rate);
884 builder.addCapability(spv::CapabilityShadingRateNV);
885 return spv::BuiltInFragmentSizeNV;
886 case glslang::EbvInvocationsPerPixelNV:
887 builder.addExtension(spv::E_SPV_NV_shading_rate);
888 builder.addCapability(spv::CapabilityShadingRateNV);
889 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700890
891 // raytracing
892 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700893 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700894 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700895 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700896 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700897 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700898 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700899 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700900 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700901 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700902 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700903 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700904 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700905 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700906 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700907 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700908 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700909 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700910 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700911 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700912 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700913 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700914 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700915 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700916 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700917 return spv::BuiltInWorldToObjectNV;
918 case glslang::EbvIncomingRayFlagsNV:
919 return spv::BuiltInIncomingRayFlagsNV;
Chao Chen9eada4b2018-09-19 11:39:56 -0700920 case glslang::EbvBaryCoordNV:
921 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
922 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
923 return spv::BuiltInBaryCoordNV;
924 case glslang::EbvBaryCoordNoPerspNV:
925 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
926 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
927 return spv::BuiltInBaryCoordNoPerspNV;
Chao Chen3c366992018-09-19 11:41:59 -0700928 case glslang::EbvTaskCountNV:
929 return spv::BuiltInTaskCountNV;
930 case glslang::EbvPrimitiveCountNV:
931 return spv::BuiltInPrimitiveCountNV;
932 case glslang::EbvPrimitiveIndicesNV:
933 return spv::BuiltInPrimitiveIndicesNV;
934 case glslang::EbvClipDistancePerViewNV:
935 return spv::BuiltInClipDistancePerViewNV;
936 case glslang::EbvCullDistancePerViewNV:
937 return spv::BuiltInCullDistancePerViewNV;
938 case glslang::EbvLayerPerViewNV:
939 return spv::BuiltInLayerPerViewNV;
940 case glslang::EbvMeshViewCountNV:
941 return spv::BuiltInMeshViewCountNV;
942 case glslang::EbvMeshViewIndicesNV:
943 return spv::BuiltInMeshViewIndicesNV;
chaoc771d89f2017-01-13 01:10:53 -0800944#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800945 default:
946 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600947 }
948}
949
Rex Xufc618912015-09-09 16:42:49 +0800950// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700951spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800952{
953 assert(type.getBasicType() == glslang::EbtSampler);
954
John Kessenich5d0fa972016-02-15 11:57:00 -0700955 // Check for capabilities
956 switch (type.getQualifier().layoutFormat) {
957 case glslang::ElfRg32f:
958 case glslang::ElfRg16f:
959 case glslang::ElfR11fG11fB10f:
960 case glslang::ElfR16f:
961 case glslang::ElfRgba16:
962 case glslang::ElfRgb10A2:
963 case glslang::ElfRg16:
964 case glslang::ElfRg8:
965 case glslang::ElfR16:
966 case glslang::ElfR8:
967 case glslang::ElfRgba16Snorm:
968 case glslang::ElfRg16Snorm:
969 case glslang::ElfRg8Snorm:
970 case glslang::ElfR16Snorm:
971 case glslang::ElfR8Snorm:
972
973 case glslang::ElfRg32i:
974 case glslang::ElfRg16i:
975 case glslang::ElfRg8i:
976 case glslang::ElfR16i:
977 case glslang::ElfR8i:
978
979 case glslang::ElfRgb10a2ui:
980 case glslang::ElfRg32ui:
981 case glslang::ElfRg16ui:
982 case glslang::ElfRg8ui:
983 case glslang::ElfR16ui:
984 case glslang::ElfR8ui:
985 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
986 break;
987
988 default:
989 break;
990 }
991
992 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800993 switch (type.getQualifier().layoutFormat) {
994 case glslang::ElfNone: return spv::ImageFormatUnknown;
995 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
996 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
997 case glslang::ElfR32f: return spv::ImageFormatR32f;
998 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
999 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1000 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1001 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1002 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1003 case glslang::ElfR16f: return spv::ImageFormatR16f;
1004 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1005 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1006 case glslang::ElfRg16: return spv::ImageFormatRg16;
1007 case glslang::ElfRg8: return spv::ImageFormatRg8;
1008 case glslang::ElfR16: return spv::ImageFormatR16;
1009 case glslang::ElfR8: return spv::ImageFormatR8;
1010 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1011 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1012 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1013 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1014 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1015 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1016 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1017 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1018 case glslang::ElfR32i: return spv::ImageFormatR32i;
1019 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1020 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1021 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1022 case glslang::ElfR16i: return spv::ImageFormatR16i;
1023 case glslang::ElfR8i: return spv::ImageFormatR8i;
1024 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1025 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1026 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1027 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1028 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1029 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1030 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1031 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1032 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1033 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001034 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001035 }
1036}
1037
John Kesseniche18fd202018-01-30 11:01:39 -07001038spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001039{
John Kesseniche18fd202018-01-30 11:01:39 -07001040 if (selectionNode.getFlatten())
1041 return spv::SelectionControlFlattenMask;
1042 if (selectionNode.getDontFlatten())
1043 return spv::SelectionControlDontFlattenMask;
1044 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001045}
1046
John Kesseniche18fd202018-01-30 11:01:39 -07001047spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001048{
John Kesseniche18fd202018-01-30 11:01:39 -07001049 if (switchNode.getFlatten())
1050 return spv::SelectionControlFlattenMask;
1051 if (switchNode.getDontFlatten())
1052 return spv::SelectionControlDontFlattenMask;
1053 return spv::SelectionControlMaskNone;
1054}
1055
John Kessenicha2858d92018-01-31 08:11:18 -07001056// return a non-0 dependency if the dependency argument must be set
1057spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
1058 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -07001059{
1060 spv::LoopControlMask control = spv::LoopControlMaskNone;
1061
1062 if (loopNode.getDontUnroll())
1063 control = control | spv::LoopControlDontUnrollMask;
1064 if (loopNode.getUnroll())
1065 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001066 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001067 control = control | spv::LoopControlDependencyInfiniteMask;
1068 else if (loopNode.getLoopDependency() > 0) {
1069 control = control | spv::LoopControlDependencyLengthMask;
1070 dependencyLength = loopNode.getLoopDependency();
1071 }
John Kesseniche18fd202018-01-30 11:01:39 -07001072
1073 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001074}
1075
John Kessenicha5c5fb62017-05-05 05:09:58 -06001076// Translate glslang type to SPIR-V storage class.
1077spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1078{
1079 if (type.getQualifier().isPipeInput())
1080 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001081 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001082 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001083
1084 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1085 type.getQualifier().storage == glslang::EvqUniform) {
1086 if (type.getBasicType() == glslang::EbtAtomicUint)
1087 return spv::StorageClassAtomicCounter;
1088 if (type.containsOpaque())
1089 return spv::StorageClassUniformConstant;
1090 }
1091
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001092#ifdef NV_EXTENSIONS
1093 if (type.getQualifier().isUniformOrBuffer() &&
1094 type.getQualifier().layoutShaderRecordNV) {
1095 return spv::StorageClassShaderRecordBufferNV;
1096 }
1097#endif
1098
John Kessenichbed4e4f2017-09-08 02:38:07 -06001099 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001100 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001101 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001102 }
1103
1104 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001105 if (type.getQualifier().layoutPushConstant)
1106 return spv::StorageClassPushConstant;
1107 if (type.getBasicType() == glslang::EbtBlock)
1108 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001109 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001110 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001111
1112 switch (type.getQualifier().storage) {
1113 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1114 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1115 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1116 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001117#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001118 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1119 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1120 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1121 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1122 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001123#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001124 default:
1125 assert(0);
1126 break;
1127 }
1128
1129 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001130}
1131
John Kessenich5611c6d2018-04-05 11:25:02 -06001132// Add capabilities pertaining to how an array is indexed.
1133void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1134 const glslang::TType& indexType)
1135{
1136 if (indexType.getQualifier().isNonUniform()) {
1137 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001138 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001139 if (baseType.getBasicType() == glslang::EbtSampler) {
1140 if (baseType.getQualifier().hasAttachment())
1141 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1142 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1143 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1144 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1145 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1146 else if (baseType.isImage())
1147 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1148 else if (baseType.isTexture())
1149 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1150 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1151 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1152 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1153 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1154 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1155 }
1156 } else {
1157 // assume a dynamically uniform index
1158 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001159 if (baseType.getQualifier().hasAttachment()) {
1160 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001161 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001162 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1163 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001164 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001165 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1166 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001167 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001168 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001169 }
1170 }
1171}
1172
qining25262b32016-05-06 17:25:16 -04001173// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001174// descriptor set.
1175bool IsDescriptorResource(const glslang::TType& type)
1176{
John Kessenichf7497e22016-03-08 21:36:22 -07001177 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001178 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001179 return type.getQualifier().isUniformOrBuffer() &&
1180#ifdef NV_EXTENSIONS
1181 ! type.getQualifier().layoutShaderRecordNV &&
1182#endif
1183 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001184
1185 // non block...
1186 // basically samplerXXX/subpass/sampler/texture are all included
1187 // if they are the global-scope-class, not the function parameter
1188 // (or local, if they ever exist) class.
1189 if (type.getBasicType() == glslang::EbtSampler)
1190 return type.getQualifier().isUniformOrBuffer();
1191
1192 // None of the above.
1193 return false;
1194}
1195
John Kesseniche0b6cad2015-12-24 10:30:13 -07001196void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1197{
1198 if (child.layoutMatrix == glslang::ElmNone)
1199 child.layoutMatrix = parent.layoutMatrix;
1200
1201 if (parent.invariant)
1202 child.invariant = true;
1203 if (parent.nopersp)
1204 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001205#ifdef AMD_EXTENSIONS
1206 if (parent.explicitInterp)
1207 child.explicitInterp = true;
1208#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001209 if (parent.flat)
1210 child.flat = true;
1211 if (parent.centroid)
1212 child.centroid = true;
1213 if (parent.patch)
1214 child.patch = true;
1215 if (parent.sample)
1216 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001217 if (parent.coherent)
1218 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001219 if (parent.devicecoherent)
1220 child.devicecoherent = true;
1221 if (parent.queuefamilycoherent)
1222 child.queuefamilycoherent = true;
1223 if (parent.workgroupcoherent)
1224 child.workgroupcoherent = true;
1225 if (parent.subgroupcoherent)
1226 child.subgroupcoherent = true;
1227 if (parent.nonprivate)
1228 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001229 if (parent.volatil)
1230 child.volatil = true;
1231 if (parent.restrict)
1232 child.restrict = true;
1233 if (parent.readonly)
1234 child.readonly = true;
1235 if (parent.writeonly)
1236 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001237#ifdef NV_EXTENSIONS
1238 if (parent.perPrimitiveNV)
1239 child.perPrimitiveNV = true;
1240 if (parent.perViewNV)
1241 child.perViewNV = true;
1242 if (parent.perTaskNV)
1243 child.perTaskNV = true;
1244#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001245}
1246
John Kessenichf2b7f332016-09-01 17:05:23 -06001247bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001248{
John Kessenich7b9fa252016-01-21 18:56:57 -07001249 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001250 // - struct members might inherit from a struct declaration
1251 // (note that non-block structs don't explicitly inherit,
1252 // only implicitly, meaning no decoration involved)
1253 // - affect decorations on the struct members
1254 // (note smooth does not, and expecting something like volatile
1255 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001256 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001257 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001258}
1259
John Kessenich140f3df2015-06-26 16:58:36 -06001260//
1261// Implement the TGlslangToSpvTraverser class.
1262//
1263
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001264TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001265 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1266 : TIntermTraverser(true, false, true),
1267 options(options),
1268 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001269 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001270 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001271 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001272 glslangIntermediate(glslangIntermediate)
1273{
1274 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1275
1276 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001277 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1278 glslangIntermediate->getVersion());
1279
John Kessenich121853f2017-05-31 17:11:16 -06001280 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001281 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001282 builder.setSourceFile(glslangIntermediate->getSourceFile());
1283
1284 // Set the source shader's text. If for SPV version 1.0, include
1285 // a preamble in comments stating the OpModuleProcessed instructions.
1286 // Otherwise, emit those as actual instructions.
1287 std::string text;
1288 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1289 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001290 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001291 text.append("// OpModuleProcessed ");
1292 text.append(processes[p]);
1293 text.append("\n");
1294 } else
1295 builder.addModuleProcessed(processes[p]);
1296 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001297 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001298 text.append("#line 1\n");
1299 text.append(glslangIntermediate->getSourceText());
1300 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001301 // Pass name and text for all included files
1302 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1303 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1304 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001305 }
John Kessenich140f3df2015-06-26 16:58:36 -06001306 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001307
1308 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1309 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1310
1311 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1312 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1313 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1314 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1315 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001316 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001317 memoryModel = spv::MemoryModelVulkanKHR;
1318 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001319 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001320 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001321 builder.setMemoryModel(addressingModel, memoryModel);
1322
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001323 if (glslangIntermediate->usingVariablePointers()) {
1324 builder.addCapability(spv::CapabilityVariablePointers);
1325 }
1326
John Kessenicheee9d532016-09-19 18:09:30 -06001327 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1328 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001329
1330 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001331 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1332 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001333 builder.addSourceExtension(it->c_str());
1334
1335 // Add the top-level modes for this shader.
1336
John Kessenich92187592016-02-01 13:45:25 -07001337 if (glslangIntermediate->getXfbMode()) {
1338 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001339 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001340 }
John Kessenich140f3df2015-06-26 16:58:36 -06001341
1342 unsigned int mode;
1343 switch (glslangIntermediate->getStage()) {
1344 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001345 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001346 break;
1347
steve-lunarge7412492017-03-23 11:56:07 -06001348 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001349 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001350 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001351
steve-lunarge7412492017-03-23 11:56:07 -06001352 glslang::TLayoutGeometry primitive;
1353
1354 if (glslangIntermediate->getStage() == EShLangTessControl) {
1355 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1356 primitive = glslangIntermediate->getOutputPrimitive();
1357 } else {
1358 primitive = glslangIntermediate->getInputPrimitive();
1359 }
1360
1361 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001362 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1363 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1364 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001365 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001366 }
John Kessenich4016e382016-07-15 11:53:56 -06001367 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001368 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1369
John Kesseniche6903322015-10-13 16:29:02 -06001370 switch (glslangIntermediate->getVertexSpacing()) {
1371 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1372 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1373 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001374 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001375 }
John Kessenich4016e382016-07-15 11:53:56 -06001376 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001377 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1378
1379 switch (glslangIntermediate->getVertexOrder()) {
1380 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1381 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; 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 if (glslangIntermediate->getPointMode())
1388 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001389 break;
1390
1391 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001392 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001393 switch (glslangIntermediate->getInputPrimitive()) {
1394 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1395 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1396 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001397 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001398 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001399 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001400 }
John Kessenich4016e382016-07-15 11:53:56 -06001401 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001402 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001403
John Kessenich140f3df2015-06-26 16:58:36 -06001404 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1405
1406 switch (glslangIntermediate->getOutputPrimitive()) {
1407 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1408 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1409 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001410 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001411 }
John Kessenich4016e382016-07-15 11:53:56 -06001412 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001413 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1414 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1415 break;
1416
1417 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001418 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001419 if (glslangIntermediate->getPixelCenterInteger())
1420 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001421
John Kessenich140f3df2015-06-26 16:58:36 -06001422 if (glslangIntermediate->getOriginUpperLeft())
1423 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001424 else
1425 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001426
1427 if (glslangIntermediate->getEarlyFragmentTests())
1428 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1429
chaocc1204522017-06-30 17:14:30 -07001430 if (glslangIntermediate->getPostDepthCoverage()) {
1431 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1432 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1433 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1434 }
1435
John Kesseniche6903322015-10-13 16:29:02 -06001436 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001437 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1438 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001439 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001440 }
John Kessenich4016e382016-07-15 11:53:56 -06001441 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001442 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1443
1444 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1445 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001446 break;
1447
1448 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001449 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001450 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1451 glslangIntermediate->getLocalSize(1),
1452 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001453#ifdef NV_EXTENSIONS
1454 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1455 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1456 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1457 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1458 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1459 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1460 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1461 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1462 }
1463#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001464 break;
1465
Chao Chen3c366992018-09-19 11:41:59 -07001466#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001467 case EShLangRayGenNV:
1468 case EShLangIntersectNV:
1469 case EShLangAnyHitNV:
1470 case EShLangClosestHitNV:
1471 case EShLangMissNV:
1472 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001473 builder.addCapability(spv::CapabilityRayTracingNV);
1474 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001475 break;
Chao Chen3c366992018-09-19 11:41:59 -07001476 case EShLangTaskNV:
1477 case EShLangMeshNV:
1478 builder.addCapability(spv::CapabilityMeshShadingNV);
1479 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1480 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1481 glslangIntermediate->getLocalSize(1),
1482 glslangIntermediate->getLocalSize(2));
1483 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1484 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1485 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1486
1487 switch (glslangIntermediate->getOutputPrimitive()) {
1488 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1489 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1490 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1491 default: mode = spv::ExecutionModeMax; break;
1492 }
1493 if (mode != spv::ExecutionModeMax)
1494 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1495 }
1496 break;
1497#endif
1498
John Kessenich140f3df2015-06-26 16:58:36 -06001499 default:
1500 break;
1501 }
John Kessenich140f3df2015-06-26 16:58:36 -06001502}
1503
John Kessenichfca82622016-11-26 13:23:20 -07001504// Finish creating SPV, after the traversal is complete.
1505void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001506{
John Kessenichf04c51b2018-08-03 15:56:12 -06001507 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001508 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001509 builder.setBuildPoint(shaderEntry->getLastBlock());
1510 builder.leaveFunction();
1511 }
1512
John Kessenich7ba63412015-12-20 17:37:07 -07001513 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001514 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1515 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001516
John Kessenichf04c51b2018-08-03 15:56:12 -06001517 // Add capabilities, extensions, remove unneeded decorations, etc.,
1518 // based on the resulting SPIR-V.
1519 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001520}
1521
John Kessenichfca82622016-11-26 13:23:20 -07001522// Write the SPV into 'out'.
1523void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001524{
John Kessenichfca82622016-11-26 13:23:20 -07001525 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001526}
1527
1528//
1529// Implement the traversal functions.
1530//
1531// Return true from interior nodes to have the external traversal
1532// continue on to children. Return false if children were
1533// already processed.
1534//
1535
1536//
qining25262b32016-05-06 17:25:16 -04001537// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001538// - uniform/input reads
1539// - output writes
1540// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1541// - something simple that degenerates into the last bullet
1542//
1543void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1544{
qining75d1d802016-04-06 14:42:01 -04001545 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1546 if (symbol->getType().getQualifier().isSpecConstant())
1547 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1548
John Kessenich140f3df2015-06-26 16:58:36 -06001549 // getSymbolId() will set up all the IO decorations on the first call.
1550 // Formal function parameters were mapped during makeFunctions().
1551 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001552
1553 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1554 if (builder.isPointer(id)) {
1555 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001556 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1557 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1558 iOSet.insert(id);
1559 }
John Kessenich7ba63412015-12-20 17:37:07 -07001560 }
1561
1562 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001563 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001564 // Prepare to generate code for the access
1565
1566 // L-value chains will be computed left to right. We're on the symbol now,
1567 // which is the left-most part of the access chain, so now is "clear" time,
1568 // followed by setting the base.
1569 builder.clearAccessChain();
1570
1571 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001572 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001573 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001574 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001575 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001576 // These are also pure R-values.
1577 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001578 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001579 builder.setAccessChainRValue(id);
1580 else
1581 builder.setAccessChainLValue(id);
1582 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001583
1584 // Process linkage-only nodes for any special additional interface work.
1585 if (linkageOnly) {
1586 if (glslangIntermediate->getHlslFunctionality1()) {
1587 // Map implicit counter buffers to their originating buffers, which should have been
1588 // seen by now, given earlier pruning of unused counters, and preservation of order
1589 // of declaration.
1590 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1591 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1592 // Save possible originating buffers for counter buffers, keyed by
1593 // making the potential counter-buffer name.
1594 std::string keyName = symbol->getName().c_str();
1595 keyName = glslangIntermediate->addCounterBufferName(keyName);
1596 counterOriginator[keyName] = symbol;
1597 } else {
1598 // Handle a counter buffer, by finding the saved originating buffer.
1599 std::string keyName = symbol->getName().c_str();
1600 auto it = counterOriginator.find(keyName);
1601 if (it != counterOriginator.end()) {
1602 id = getSymbolId(it->second);
1603 if (id != spv::NoResult) {
1604 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001605 if (counterId != spv::NoResult) {
1606 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001607 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001608 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001609 }
1610 }
1611 }
1612 }
1613 }
1614 }
John Kessenich140f3df2015-06-26 16:58:36 -06001615}
1616
1617bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1618{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001619 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001620
qining40887662016-04-03 22:20:42 -04001621 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1622 if (node->getType().getQualifier().isSpecConstant())
1623 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1624
John Kessenich140f3df2015-06-26 16:58:36 -06001625 // First, handle special cases
1626 switch (node->getOp()) {
1627 case glslang::EOpAssign:
1628 case glslang::EOpAddAssign:
1629 case glslang::EOpSubAssign:
1630 case glslang::EOpMulAssign:
1631 case glslang::EOpVectorTimesMatrixAssign:
1632 case glslang::EOpVectorTimesScalarAssign:
1633 case glslang::EOpMatrixTimesScalarAssign:
1634 case glslang::EOpMatrixTimesMatrixAssign:
1635 case glslang::EOpDivAssign:
1636 case glslang::EOpModAssign:
1637 case glslang::EOpAndAssign:
1638 case glslang::EOpInclusiveOrAssign:
1639 case glslang::EOpExclusiveOrAssign:
1640 case glslang::EOpLeftShiftAssign:
1641 case glslang::EOpRightShiftAssign:
1642 // A bin-op assign "a += b" means the same thing as "a = a + b"
1643 // where a is evaluated before b. For a simple assignment, GLSL
1644 // says to evaluate the left before the right. So, always, left
1645 // node then right node.
1646 {
1647 // get the left l-value, save it away
1648 builder.clearAccessChain();
1649 node->getLeft()->traverse(this);
1650 spv::Builder::AccessChain lValue = builder.getAccessChain();
1651
1652 // evaluate the right
1653 builder.clearAccessChain();
1654 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001655 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001656
1657 if (node->getOp() != glslang::EOpAssign) {
1658 // the left is also an r-value
1659 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001660 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001661
1662 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001663 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001664 TranslateNoContractionDecoration(node->getType().getQualifier()),
1665 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001666 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001667 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1668 node->getType().getBasicType());
1669
1670 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001671 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001672 }
1673
1674 // store the result
1675 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001676 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001677
1678 // assignments are expressions having an rValue after they are evaluated...
1679 builder.clearAccessChain();
1680 builder.setAccessChainRValue(rValue);
1681 }
1682 return false;
1683 case glslang::EOpIndexDirect:
1684 case glslang::EOpIndexDirectStruct:
1685 {
1686 // Get the left part of the access chain.
1687 node->getLeft()->traverse(this);
1688
1689 // Add the next element in the chain
1690
David Netoa901ffe2016-06-08 14:11:40 +01001691 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001692 if (! node->getLeft()->getType().isArray() &&
1693 node->getLeft()->getType().isVector() &&
1694 node->getOp() == glslang::EOpIndexDirect) {
1695 // This is essentially a hard-coded vector swizzle of size 1,
1696 // so short circuit the access-chain stuff with a swizzle.
1697 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001698 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001699 int dummySize;
1700 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1701 TranslateCoherent(node->getLeft()->getType()),
1702 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001703 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001704
1705 // Load through a block reference is performed with a dot operator that
1706 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1707 // do a load and reset the access chain.
1708 if (node->getLeft()->getBasicType() == glslang::EbtReference &&
1709 !node->getLeft()->getType().isArray() &&
1710 node->getOp() == glslang::EOpIndexDirectStruct)
1711 {
1712 spv::Id left = accessChainLoad(node->getLeft()->getType());
1713 builder.clearAccessChain();
1714 builder.setAccessChainLValue(left);
1715 }
1716
David Netoa901ffe2016-06-08 14:11:40 +01001717 int spvIndex = glslangIndex;
1718 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1719 node->getOp() == glslang::EOpIndexDirectStruct)
1720 {
1721 // This may be, e.g., an anonymous block-member selection, which generally need
1722 // index remapping due to hidden members in anonymous blocks.
1723 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1724 assert(remapper.size() > 0);
1725 spvIndex = remapper[glslangIndex];
1726 }
John Kessenichebb50532016-05-16 19:22:05 -06001727
David Netoa901ffe2016-06-08 14:11:40 +01001728 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001729 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001730
1731 // Add capabilities here for accessing PointSize and clip/cull distance.
1732 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001733 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001734 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001735 }
1736 }
1737 return false;
1738 case glslang::EOpIndexIndirect:
1739 {
1740 // Structure or array or vector indirection.
1741 // Will use native SPIR-V access-chain for struct and array indirection;
1742 // matrices are arrays of vectors, so will also work for a matrix.
1743 // Will use the access chain's 'component' for variable index into a vector.
1744
1745 // This adapter is building access chains left to right.
1746 // Set up the access chain to the left.
1747 node->getLeft()->traverse(this);
1748
1749 // save it so that computing the right side doesn't trash it
1750 spv::Builder::AccessChain partial = builder.getAccessChain();
1751
1752 // compute the next index in the chain
1753 builder.clearAccessChain();
1754 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001755 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001756
John Kessenich5611c6d2018-04-05 11:25:02 -06001757 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1758
John Kessenich140f3df2015-06-26 16:58:36 -06001759 // restore the saved access chain
1760 builder.setAccessChain(partial);
1761
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001762 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1763 int dummySize;
1764 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1765 TranslateCoherent(node->getLeft()->getType()),
1766 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1767 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001768 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001769 }
1770 return false;
1771 case glslang::EOpVectorSwizzle:
1772 {
1773 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001774 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001775 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001776 int dummySize;
1777 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1778 TranslateCoherent(node->getLeft()->getType()),
1779 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001780 }
1781 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001782 case glslang::EOpMatrixSwizzle:
1783 logger->missingFunctionality("matrix swizzle");
1784 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001785 case glslang::EOpLogicalOr:
1786 case glslang::EOpLogicalAnd:
1787 {
1788
1789 // These may require short circuiting, but can sometimes be done as straight
1790 // binary operations. The right operand must be short circuited if it has
1791 // side effects, and should probably be if it is complex.
1792 if (isTrivial(node->getRight()->getAsTyped()))
1793 break; // handle below as a normal binary operation
1794 // otherwise, we need to do dynamic short circuiting on the right operand
1795 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1796 builder.clearAccessChain();
1797 builder.setAccessChainRValue(result);
1798 }
1799 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001800 default:
1801 break;
1802 }
1803
1804 // Assume generic binary op...
1805
John Kessenich32cfd492016-02-02 12:37:46 -07001806 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001807 builder.clearAccessChain();
1808 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001809 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001810
John Kessenich32cfd492016-02-02 12:37:46 -07001811 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001812 builder.clearAccessChain();
1813 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001814 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001815
John Kessenich32cfd492016-02-02 12:37:46 -07001816 // get result
John Kessenichead86222018-03-28 18:01:20 -06001817 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001818 TranslateNoContractionDecoration(node->getType().getQualifier()),
1819 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001820 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001821 convertGlslangToSpvType(node->getType()), left, right,
1822 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001823
John Kessenich50e57562015-12-21 21:21:11 -07001824 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001825 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001826 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001827 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001828 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001829 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001830 return false;
1831 }
John Kessenich140f3df2015-06-26 16:58:36 -06001832}
1833
1834bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1835{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001836 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001837
qining40887662016-04-03 22:20:42 -04001838 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1839 if (node->getType().getQualifier().isSpecConstant())
1840 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1841
John Kessenichfc51d282015-08-19 13:34:18 -06001842 spv::Id result = spv::NoResult;
1843
1844 // try texturing first
1845 result = createImageTextureFunctionCall(node);
1846 if (result != spv::NoResult) {
1847 builder.clearAccessChain();
1848 builder.setAccessChainRValue(result);
1849
1850 return false; // done with this node
1851 }
1852
1853 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001854
1855 if (node->getOp() == glslang::EOpArrayLength) {
1856 // Quite special; won't want to evaluate the operand.
1857
John Kessenich5611c6d2018-04-05 11:25:02 -06001858 // Currently, the front-end does not allow .length() on an array until it is sized,
1859 // except for the last block membeor of an SSBO.
1860 // TODO: If this changes, link-time sized arrays might show up here, and need their
1861 // size extracted.
1862
John Kessenichc9a80832015-09-12 12:17:44 -06001863 // Normal .length() would have been constant folded by the front-end.
1864 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001865 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001866
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001867 spv::Id length;
1868 if (node->getOperand()->getType().isCoopMat()) {
1869 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1870
1871 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
1872 assert(builder.isCooperativeMatrixType(typeId));
1873
1874 length = builder.createCooperativeMatrixLength(typeId);
1875 } else {
1876 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1877 block->traverse(this);
1878 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1879 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
1880 }
John Kessenichc9a80832015-09-12 12:17:44 -06001881
John Kessenich8c869672018-11-28 07:01:37 -07001882 // GLSL semantics say the result of .length() is an int, while SPIR-V says
1883 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
1884 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001885 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
1886 if (builder.isInSpecConstCodeGenMode()) {
1887 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
1888 } else {
1889 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
1890 }
1891 }
John Kessenich8c869672018-11-28 07:01:37 -07001892
John Kessenichc9a80832015-09-12 12:17:44 -06001893 builder.clearAccessChain();
1894 builder.setAccessChainRValue(length);
1895
1896 return false;
1897 }
1898
John Kessenichfc51d282015-08-19 13:34:18 -06001899 // Start by evaluating the operand
1900
John Kessenich8c8505c2016-07-26 12:50:38 -06001901 // Does it need a swizzle inversion? If so, evaluation is inverted;
1902 // operate first on the swizzle base, then apply the swizzle.
1903 spv::Id invertedType = spv::NoType;
1904 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1905 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1906 invertedType = getInvertedSwizzleType(*node->getOperand());
1907
John Kessenich140f3df2015-06-26 16:58:36 -06001908 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001909 if (invertedType != spv::NoType)
1910 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1911 else
1912 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001913
Rex Xufc618912015-09-09 16:42:49 +08001914 spv::Id operand = spv::NoResult;
1915
1916 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1917 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001918 node->getOp() == glslang::EOpAtomicCounter ||
1919 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001920 operand = builder.accessChainGetLValue(); // Special case l-value operands
1921 else
John Kessenich32cfd492016-02-02 12:37:46 -07001922 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001923
John Kessenichead86222018-03-28 18:01:20 -06001924 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001925 TranslateNoContractionDecoration(node->getType().getQualifier()),
1926 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001927
1928 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001929 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001930 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001931
1932 // if not, then possibly an operation
1933 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001934 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001935
1936 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001937 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001938 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001939 builder.addDecoration(result, decorations.nonUniform);
1940 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001941
John Kessenich140f3df2015-06-26 16:58:36 -06001942 builder.clearAccessChain();
1943 builder.setAccessChainRValue(result);
1944
1945 return false; // done with this node
1946 }
1947
1948 // it must be a special case, check...
1949 switch (node->getOp()) {
1950 case glslang::EOpPostIncrement:
1951 case glslang::EOpPostDecrement:
1952 case glslang::EOpPreIncrement:
1953 case glslang::EOpPreDecrement:
1954 {
1955 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001956 spv::Id one = 0;
1957 if (node->getBasicType() == glslang::EbtFloat)
1958 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001959 else if (node->getBasicType() == glslang::EbtDouble)
1960 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001961 else if (node->getBasicType() == glslang::EbtFloat16)
1962 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001963 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1964 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001965 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1966 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001967 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1968 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001969 else
1970 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001971 glslang::TOperator op;
1972 if (node->getOp() == glslang::EOpPreIncrement ||
1973 node->getOp() == glslang::EOpPostIncrement)
1974 op = glslang::EOpAdd;
1975 else
1976 op = glslang::EOpSub;
1977
John Kessenichead86222018-03-28 18:01:20 -06001978 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001979 convertGlslangToSpvType(node->getType()), operand, one,
1980 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001981 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001982
1983 // The result of operation is always stored, but conditionally the
1984 // consumed result. The consumed result is always an r-value.
1985 builder.accessChainStore(result);
1986 builder.clearAccessChain();
1987 if (node->getOp() == glslang::EOpPreIncrement ||
1988 node->getOp() == glslang::EOpPreDecrement)
1989 builder.setAccessChainRValue(result);
1990 else
1991 builder.setAccessChainRValue(operand);
1992 }
1993
1994 return false;
1995
1996 case glslang::EOpEmitStreamVertex:
1997 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1998 return false;
1999 case glslang::EOpEndStreamPrimitive:
2000 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2001 return false;
2002
2003 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002004 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002005 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002006 }
John Kessenich140f3df2015-06-26 16:58:36 -06002007}
2008
2009bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2010{
qining27e04a02016-04-14 16:40:20 -04002011 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2012 if (node->getType().getQualifier().isSpecConstant())
2013 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2014
John Kessenichfc51d282015-08-19 13:34:18 -06002015 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002016 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2017 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002018
2019 // try texturing
2020 result = createImageTextureFunctionCall(node);
2021 if (result != spv::NoResult) {
2022 builder.clearAccessChain();
2023 builder.setAccessChainRValue(result);
2024
2025 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05002026 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08002027#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05002028 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08002029#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05002030 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002031 // "imageStore" is a special case, which has no result
2032 return false;
2033 }
John Kessenichfc51d282015-08-19 13:34:18 -06002034
John Kessenich140f3df2015-06-26 16:58:36 -06002035 glslang::TOperator binOp = glslang::EOpNull;
2036 bool reduceComparison = true;
2037 bool isMatrix = false;
2038 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002039 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002040
2041 assert(node->getOp());
2042
John Kessenichf6640762016-08-01 19:44:00 -06002043 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002044
2045 switch (node->getOp()) {
2046 case glslang::EOpSequence:
2047 {
2048 if (preVisit)
2049 ++sequenceDepth;
2050 else
2051 --sequenceDepth;
2052
2053 if (sequenceDepth == 1) {
2054 // If this is the parent node of all the functions, we want to see them
2055 // early, so all call points have actual SPIR-V functions to reference.
2056 // In all cases, still let the traverser visit the children for us.
2057 makeFunctions(node->getAsAggregate()->getSequence());
2058
John Kessenich6fccb3c2016-09-19 16:01:41 -06002059 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002060 // anything else gets there, so visit out of order, doing them all now.
2061 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2062
John Kessenich6a60c2f2016-12-08 21:01:59 -07002063 // 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 -06002064 // so do them manually.
2065 visitFunctions(node->getAsAggregate()->getSequence());
2066
2067 return false;
2068 }
2069
2070 return true;
2071 }
2072 case glslang::EOpLinkerObjects:
2073 {
2074 if (visit == glslang::EvPreVisit)
2075 linkageOnly = true;
2076 else
2077 linkageOnly = false;
2078
2079 return true;
2080 }
2081 case glslang::EOpComma:
2082 {
2083 // processing from left to right naturally leaves the right-most
2084 // lying around in the access chain
2085 glslang::TIntermSequence& glslangOperands = node->getSequence();
2086 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2087 glslangOperands[i]->traverse(this);
2088
2089 return false;
2090 }
2091 case glslang::EOpFunction:
2092 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002093 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002094 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002095 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002096 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002097 } else {
2098 handleFunctionEntry(node);
2099 }
2100 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002101 if (inEntryPoint)
2102 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002103 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002104 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002105 }
2106
2107 return true;
2108 case glslang::EOpParameters:
2109 // Parameters will have been consumed by EOpFunction processing, but not
2110 // the body, so we still visited the function node's children, making this
2111 // child redundant.
2112 return false;
2113 case glslang::EOpFunctionCall:
2114 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002115 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002116 if (node->isUserDefined())
2117 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002118 // 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 -07002119 if (result) {
2120 builder.clearAccessChain();
2121 builder.setAccessChainRValue(result);
2122 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002123 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002124
2125 return false;
2126 }
2127 case glslang::EOpConstructMat2x2:
2128 case glslang::EOpConstructMat2x3:
2129 case glslang::EOpConstructMat2x4:
2130 case glslang::EOpConstructMat3x2:
2131 case glslang::EOpConstructMat3x3:
2132 case glslang::EOpConstructMat3x4:
2133 case glslang::EOpConstructMat4x2:
2134 case glslang::EOpConstructMat4x3:
2135 case glslang::EOpConstructMat4x4:
2136 case glslang::EOpConstructDMat2x2:
2137 case glslang::EOpConstructDMat2x3:
2138 case glslang::EOpConstructDMat2x4:
2139 case glslang::EOpConstructDMat3x2:
2140 case glslang::EOpConstructDMat3x3:
2141 case glslang::EOpConstructDMat3x4:
2142 case glslang::EOpConstructDMat4x2:
2143 case glslang::EOpConstructDMat4x3:
2144 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002145 case glslang::EOpConstructIMat2x2:
2146 case glslang::EOpConstructIMat2x3:
2147 case glslang::EOpConstructIMat2x4:
2148 case glslang::EOpConstructIMat3x2:
2149 case glslang::EOpConstructIMat3x3:
2150 case glslang::EOpConstructIMat3x4:
2151 case glslang::EOpConstructIMat4x2:
2152 case glslang::EOpConstructIMat4x3:
2153 case glslang::EOpConstructIMat4x4:
2154 case glslang::EOpConstructUMat2x2:
2155 case glslang::EOpConstructUMat2x3:
2156 case glslang::EOpConstructUMat2x4:
2157 case glslang::EOpConstructUMat3x2:
2158 case glslang::EOpConstructUMat3x3:
2159 case glslang::EOpConstructUMat3x4:
2160 case glslang::EOpConstructUMat4x2:
2161 case glslang::EOpConstructUMat4x3:
2162 case glslang::EOpConstructUMat4x4:
2163 case glslang::EOpConstructBMat2x2:
2164 case glslang::EOpConstructBMat2x3:
2165 case glslang::EOpConstructBMat2x4:
2166 case glslang::EOpConstructBMat3x2:
2167 case glslang::EOpConstructBMat3x3:
2168 case glslang::EOpConstructBMat3x4:
2169 case glslang::EOpConstructBMat4x2:
2170 case glslang::EOpConstructBMat4x3:
2171 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002172 case glslang::EOpConstructF16Mat2x2:
2173 case glslang::EOpConstructF16Mat2x3:
2174 case glslang::EOpConstructF16Mat2x4:
2175 case glslang::EOpConstructF16Mat3x2:
2176 case glslang::EOpConstructF16Mat3x3:
2177 case glslang::EOpConstructF16Mat3x4:
2178 case glslang::EOpConstructF16Mat4x2:
2179 case glslang::EOpConstructF16Mat4x3:
2180 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002181 isMatrix = true;
2182 // fall through
2183 case glslang::EOpConstructFloat:
2184 case glslang::EOpConstructVec2:
2185 case glslang::EOpConstructVec3:
2186 case glslang::EOpConstructVec4:
2187 case glslang::EOpConstructDouble:
2188 case glslang::EOpConstructDVec2:
2189 case glslang::EOpConstructDVec3:
2190 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002191 case glslang::EOpConstructFloat16:
2192 case glslang::EOpConstructF16Vec2:
2193 case glslang::EOpConstructF16Vec3:
2194 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002195 case glslang::EOpConstructBool:
2196 case glslang::EOpConstructBVec2:
2197 case glslang::EOpConstructBVec3:
2198 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002199 case glslang::EOpConstructInt8:
2200 case glslang::EOpConstructI8Vec2:
2201 case glslang::EOpConstructI8Vec3:
2202 case glslang::EOpConstructI8Vec4:
2203 case glslang::EOpConstructUint8:
2204 case glslang::EOpConstructU8Vec2:
2205 case glslang::EOpConstructU8Vec3:
2206 case glslang::EOpConstructU8Vec4:
2207 case glslang::EOpConstructInt16:
2208 case glslang::EOpConstructI16Vec2:
2209 case glslang::EOpConstructI16Vec3:
2210 case glslang::EOpConstructI16Vec4:
2211 case glslang::EOpConstructUint16:
2212 case glslang::EOpConstructU16Vec2:
2213 case glslang::EOpConstructU16Vec3:
2214 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002215 case glslang::EOpConstructInt:
2216 case glslang::EOpConstructIVec2:
2217 case glslang::EOpConstructIVec3:
2218 case glslang::EOpConstructIVec4:
2219 case glslang::EOpConstructUint:
2220 case glslang::EOpConstructUVec2:
2221 case glslang::EOpConstructUVec3:
2222 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002223 case glslang::EOpConstructInt64:
2224 case glslang::EOpConstructI64Vec2:
2225 case glslang::EOpConstructI64Vec3:
2226 case glslang::EOpConstructI64Vec4:
2227 case glslang::EOpConstructUint64:
2228 case glslang::EOpConstructU64Vec2:
2229 case glslang::EOpConstructU64Vec3:
2230 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002231 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002232 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002233 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002234 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002235 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002236 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002237 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002238 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002239 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002240 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002241 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002242 else if (node->getOp() == glslang::EOpConstructStruct ||
2243 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2244 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002245 std::vector<spv::Id> constituents;
2246 for (int c = 0; c < (int)arguments.size(); ++c)
2247 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002248 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002249 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002250 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002251 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002252 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002253
2254 builder.clearAccessChain();
2255 builder.setAccessChainRValue(constructed);
2256
2257 return false;
2258 }
2259
2260 // These six are component-wise compares with component-wise results.
2261 // Forward on to createBinaryOperation(), requesting a vector result.
2262 case glslang::EOpLessThan:
2263 case glslang::EOpGreaterThan:
2264 case glslang::EOpLessThanEqual:
2265 case glslang::EOpGreaterThanEqual:
2266 case glslang::EOpVectorEqual:
2267 case glslang::EOpVectorNotEqual:
2268 {
2269 // Map the operation to a binary
2270 binOp = node->getOp();
2271 reduceComparison = false;
2272 switch (node->getOp()) {
2273 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2274 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2275 default: binOp = node->getOp(); break;
2276 }
2277
2278 break;
2279 }
2280 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002281 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002282 binOp = glslang::EOpMul;
2283 break;
2284 case glslang::EOpOuterProduct:
2285 // two vectors multiplied to make a matrix
2286 binOp = glslang::EOpOuterProduct;
2287 break;
2288 case glslang::EOpDot:
2289 {
qining25262b32016-05-06 17:25:16 -04002290 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002291 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002292 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002293 binOp = glslang::EOpMul;
2294 break;
2295 }
2296 case glslang::EOpMod:
2297 // when an aggregate, this is the floating-point mod built-in function,
2298 // which can be emitted by the one in createBinaryOperation()
2299 binOp = glslang::EOpMod;
2300 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002301 case glslang::EOpEmitVertex:
2302 case glslang::EOpEndPrimitive:
2303 case glslang::EOpBarrier:
2304 case glslang::EOpMemoryBarrier:
2305 case glslang::EOpMemoryBarrierAtomicCounter:
2306 case glslang::EOpMemoryBarrierBuffer:
2307 case glslang::EOpMemoryBarrierImage:
2308 case glslang::EOpMemoryBarrierShared:
2309 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002310 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002311 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002312 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002313 case glslang::EOpWorkgroupMemoryBarrier:
2314 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002315 case glslang::EOpSubgroupBarrier:
2316 case glslang::EOpSubgroupMemoryBarrier:
2317 case glslang::EOpSubgroupMemoryBarrierBuffer:
2318 case glslang::EOpSubgroupMemoryBarrierImage:
2319 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002320 noReturnValue = true;
2321 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2322 break;
2323
Jeff Bolz36831c92018-09-05 10:11:41 -05002324 case glslang::EOpAtomicStore:
2325 noReturnValue = true;
2326 // fallthrough
2327 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002328 case glslang::EOpAtomicAdd:
2329 case glslang::EOpAtomicMin:
2330 case glslang::EOpAtomicMax:
2331 case glslang::EOpAtomicAnd:
2332 case glslang::EOpAtomicOr:
2333 case glslang::EOpAtomicXor:
2334 case glslang::EOpAtomicExchange:
2335 case glslang::EOpAtomicCompSwap:
2336 atomic = true;
2337 break;
2338
John Kessenich0d0c6d32017-07-23 16:08:26 -06002339 case glslang::EOpAtomicCounterAdd:
2340 case glslang::EOpAtomicCounterSubtract:
2341 case glslang::EOpAtomicCounterMin:
2342 case glslang::EOpAtomicCounterMax:
2343 case glslang::EOpAtomicCounterAnd:
2344 case glslang::EOpAtomicCounterOr:
2345 case glslang::EOpAtomicCounterXor:
2346 case glslang::EOpAtomicCounterExchange:
2347 case glslang::EOpAtomicCounterCompSwap:
2348 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2349 builder.addCapability(spv::CapabilityAtomicStorageOps);
2350 atomic = true;
2351 break;
2352
Chao Chen3c366992018-09-19 11:41:59 -07002353#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002354 case glslang::EOpIgnoreIntersectionNV:
2355 case glslang::EOpTerminateRayNV:
2356 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002357 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002358 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2359 noReturnValue = true;
2360 break;
2361#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002362 case glslang::EOpCooperativeMatrixLoad:
2363 case glslang::EOpCooperativeMatrixStore:
2364 noReturnValue = true;
2365 break;
Chao Chen3c366992018-09-19 11:41:59 -07002366
John Kessenich140f3df2015-06-26 16:58:36 -06002367 default:
2368 break;
2369 }
2370
2371 //
2372 // See if it maps to a regular operation.
2373 //
John Kessenich140f3df2015-06-26 16:58:36 -06002374 if (binOp != glslang::EOpNull) {
2375 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2376 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2377 assert(left && right);
2378
2379 builder.clearAccessChain();
2380 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002381 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002382
2383 builder.clearAccessChain();
2384 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002385 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002386
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002387 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002388 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002389 TranslateNoContractionDecoration(node->getType().getQualifier()),
2390 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002391 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002392 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002393 left->getType().getBasicType(), reduceComparison);
2394
2395 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002396 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002397 builder.clearAccessChain();
2398 builder.setAccessChainRValue(result);
2399
2400 return false;
2401 }
2402
John Kessenich426394d2015-07-23 10:22:48 -06002403 //
2404 // Create the list of operands.
2405 //
John Kessenich140f3df2015-06-26 16:58:36 -06002406 glslang::TIntermSequence& glslangOperands = node->getSequence();
2407 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002408 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002409 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002410 // special case l-value operands; there are just a few
2411 bool lvalue = false;
2412 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002413 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002414 case glslang::EOpModf:
2415 if (arg == 1)
2416 lvalue = true;
2417 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002418 case glslang::EOpInterpolateAtSample:
2419 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002420#ifdef AMD_EXTENSIONS
2421 case glslang::EOpInterpolateAtVertex:
2422#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002423 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002424 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002425
2426 // Does it need a swizzle inversion? If so, evaluation is inverted;
2427 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002428 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002429 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2430 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2431 }
Rex Xu7a26c172015-12-08 17:12:09 +08002432 break;
Rex Xud4782c12015-09-06 16:30:11 +08002433 case glslang::EOpAtomicAdd:
2434 case glslang::EOpAtomicMin:
2435 case glslang::EOpAtomicMax:
2436 case glslang::EOpAtomicAnd:
2437 case glslang::EOpAtomicOr:
2438 case glslang::EOpAtomicXor:
2439 case glslang::EOpAtomicExchange:
2440 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002441 case glslang::EOpAtomicLoad:
2442 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002443 case glslang::EOpAtomicCounterAdd:
2444 case glslang::EOpAtomicCounterSubtract:
2445 case glslang::EOpAtomicCounterMin:
2446 case glslang::EOpAtomicCounterMax:
2447 case glslang::EOpAtomicCounterAnd:
2448 case glslang::EOpAtomicCounterOr:
2449 case glslang::EOpAtomicCounterXor:
2450 case glslang::EOpAtomicCounterExchange:
2451 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002452 if (arg == 0)
2453 lvalue = true;
2454 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002455 case glslang::EOpAddCarry:
2456 case glslang::EOpSubBorrow:
2457 if (arg == 2)
2458 lvalue = true;
2459 break;
2460 case glslang::EOpUMulExtended:
2461 case glslang::EOpIMulExtended:
2462 if (arg >= 2)
2463 lvalue = true;
2464 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002465 case glslang::EOpCooperativeMatrixLoad:
2466 if (arg == 0 || arg == 1)
2467 lvalue = true;
2468 break;
2469 case glslang::EOpCooperativeMatrixStore:
2470 if (arg == 1)
2471 lvalue = true;
2472 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002473 default:
2474 break;
2475 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002476 builder.clearAccessChain();
2477 if (invertedType != spv::NoType && arg == 0)
2478 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2479 else
2480 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002481
2482 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2483 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2484
2485 if (arg == 1) {
2486 // fold "element" parameter into the access chain
2487 spv::Builder::AccessChain save = builder.getAccessChain();
2488 builder.clearAccessChain();
2489 glslangOperands[2]->traverse(this);
2490
2491 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2492
2493 builder.setAccessChain(save);
2494
2495 // Point to the first element of the array.
2496 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002497 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002498
2499 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2500 unsigned int alignment = builder.getAccessChain().alignment;
2501
2502 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2503 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2504 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2505 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2506 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2507 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2508 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2509 }
2510
2511 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2512
2513 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2514 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2515 }
2516
2517 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2518 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2519 }
2520 } else if (arg == 2) {
2521 continue;
2522 }
2523 }
2524
John Kessenich140f3df2015-06-26 16:58:36 -06002525 if (lvalue)
2526 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002527 else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002528 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002529 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002530 }
John Kessenich140f3df2015-06-26 16:58:36 -06002531 }
John Kessenich426394d2015-07-23 10:22:48 -06002532
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002533 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002534 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2535 std::vector<spv::IdImmediate> idImmOps;
2536
2537 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2538 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2539 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2540 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2541 // get the pointee type
2542 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2543 assert(builder.isCooperativeMatrixType(typeId));
2544 // do the op
2545 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2546 // store the result to the pointer (out param 'm')
2547 builder.createStore(result, operands[0]);
2548 result = 0;
2549 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2550 std::vector<spv::IdImmediate> idImmOps;
2551
2552 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2553 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2554 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2555 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2556 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2557
2558 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2559 result = 0;
2560 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002561 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002562 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002563 } else {
2564 // Pass through to generic operations.
2565 switch (glslangOperands.size()) {
2566 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002567 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002568 break;
2569 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002570 {
2571 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002572 TranslateNoContractionDecoration(node->getType().getQualifier()),
2573 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002574 result = createUnaryOperation(
2575 node->getOp(), decorations,
2576 resultType(), operands.front(),
2577 glslangOperands[0]->getAsTyped()->getBasicType());
2578 }
John Kessenich426394d2015-07-23 10:22:48 -06002579 break;
2580 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002581 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002582 break;
2583 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002584 if (invertedType)
2585 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002586 }
2587
2588 if (noReturnValue)
2589 return false;
2590
2591 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002592 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002593 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002594 } else {
2595 builder.clearAccessChain();
2596 builder.setAccessChainRValue(result);
2597 return false;
2598 }
2599}
2600
John Kessenich433e9ff2017-01-26 20:31:11 -07002601// This path handles both if-then-else and ?:
2602// The if-then-else has a node type of void, while
2603// ?: has either a void or a non-void node type
2604//
2605// Leaving the result, when not void:
2606// GLSL only has r-values as the result of a :?, but
2607// if we have an l-value, that can be more efficient if it will
2608// become the base of a complex r-value expression, because the
2609// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002610bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2611{
John Kessenich4bee5312018-02-20 21:29:05 -07002612 // See if it simple and safe, or required, to execute both sides.
2613 // Crucially, side effects must be either semantically required or avoided,
2614 // and there are performance trade-offs.
2615 // Return true if required or a good idea (and safe) to execute both sides,
2616 // false otherwise.
2617 const auto bothSidesPolicy = [&]() -> bool {
2618 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002619 if (node->getTrueBlock() == nullptr ||
2620 node->getFalseBlock() == nullptr)
2621 return false;
2622
John Kessenich4bee5312018-02-20 21:29:05 -07002623 // required? (unless we write additional code to look for side effects
2624 // and make performance trade-offs if none are present)
2625 if (!node->getShortCircuit())
2626 return true;
2627
2628 // if not required to execute both, decide based on performance/practicality...
2629
2630 // see if OpSelect can handle it
2631 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2632 node->getBasicType() == glslang::EbtVoid)
2633 return false;
2634
John Kessenich433e9ff2017-01-26 20:31:11 -07002635 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2636 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2637
2638 // return true if a single operand to ? : is okay for OpSelect
2639 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002640 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002641 };
2642
2643 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2644 operandOkay(node->getFalseBlock()->getAsTyped());
2645 };
2646
John Kessenich4bee5312018-02-20 21:29:05 -07002647 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2648 // emit the condition before doing anything with selection
2649 node->getCondition()->traverse(this);
2650 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2651
2652 // Find a way of executing both sides and selecting the right result.
2653 const auto executeBothSides = [&]() -> void {
2654 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002655 node->getTrueBlock()->traverse(this);
2656 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2657 node->getFalseBlock()->traverse(this);
2658 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2659
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002660 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002661
John Kessenich4bee5312018-02-20 21:29:05 -07002662 // done if void
2663 if (node->getBasicType() == glslang::EbtVoid)
2664 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002665
John Kessenich4bee5312018-02-20 21:29:05 -07002666 // emit code to select between trueValue and falseValue
2667
2668 // see if OpSelect can handle it
2669 if (node->getType().isScalar() || node->getType().isVector()) {
2670 // Emit OpSelect for this selection.
2671
2672 // smear condition to vector, if necessary (AST is always scalar)
2673 if (builder.isVector(trueValue))
2674 condition = builder.smearScalar(spv::NoPrecision, condition,
2675 builder.makeVectorType(builder.makeBoolType(),
2676 builder.getNumComponents(trueValue)));
2677
2678 // OpSelect
2679 result = builder.createTriOp(spv::OpSelect,
2680 convertGlslangToSpvType(node->getType()), condition,
2681 trueValue, falseValue);
2682
2683 builder.clearAccessChain();
2684 builder.setAccessChainRValue(result);
2685 } else {
2686 // We need control flow to select the result.
2687 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2688 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2689
2690 // Selection control:
2691 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2692
2693 // make an "if" based on the value created by the condition
2694 spv::Builder::If ifBuilder(condition, control, builder);
2695
2696 // emit the "then" statement
2697 builder.createStore(trueValue, result);
2698 ifBuilder.makeBeginElse();
2699 // emit the "else" statement
2700 builder.createStore(falseValue, result);
2701
2702 // finish off the control flow
2703 ifBuilder.makeEndIf();
2704
2705 builder.clearAccessChain();
2706 builder.setAccessChainLValue(result);
2707 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002708 };
2709
John Kessenich4bee5312018-02-20 21:29:05 -07002710 // Execute the one side needed, as per the condition
2711 const auto executeOneSide = [&]() {
2712 // Always emit control flow.
2713 if (node->getBasicType() != glslang::EbtVoid)
2714 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002715
John Kessenich4bee5312018-02-20 21:29:05 -07002716 // Selection control:
2717 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2718
2719 // make an "if" based on the value created by the condition
2720 spv::Builder::If ifBuilder(condition, control, builder);
2721
2722 // emit the "then" statement
2723 if (node->getTrueBlock() != nullptr) {
2724 node->getTrueBlock()->traverse(this);
2725 if (result != spv::NoResult)
2726 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2727 }
2728
2729 if (node->getFalseBlock() != nullptr) {
2730 ifBuilder.makeBeginElse();
2731 // emit the "else" statement
2732 node->getFalseBlock()->traverse(this);
2733 if (result != spv::NoResult)
2734 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2735 }
2736
2737 // finish off the control flow
2738 ifBuilder.makeEndIf();
2739
2740 if (result != spv::NoResult) {
2741 builder.clearAccessChain();
2742 builder.setAccessChainLValue(result);
2743 }
2744 };
2745
2746 // Try for OpSelect (or a requirement to execute both sides)
2747 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002748 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2749 if (node->getType().getQualifier().isSpecConstant())
2750 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002751 executeBothSides();
2752 } else
2753 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002754
2755 return false;
2756}
2757
2758bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2759{
2760 // emit and get the condition before doing anything with switch
2761 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002762 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002763
Rex Xu57e65922017-07-04 23:23:40 +08002764 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002765 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002766
John Kessenich140f3df2015-06-26 16:58:36 -06002767 // browse the children to sort out code segments
2768 int defaultSegment = -1;
2769 std::vector<TIntermNode*> codeSegments;
2770 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2771 std::vector<int> caseValues;
2772 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2773 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2774 TIntermNode* child = *c;
2775 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002776 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002777 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002778 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002779 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2780 } else
2781 codeSegments.push_back(child);
2782 }
2783
qining25262b32016-05-06 17:25:16 -04002784 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002785 // statements between the last case and the end of the switch statement
2786 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2787 (int)codeSegments.size() == defaultSegment)
2788 codeSegments.push_back(nullptr);
2789
2790 // make the switch statement
2791 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002792 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002793
2794 // emit all the code in the segments
2795 breakForLoop.push(false);
2796 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2797 builder.nextSwitchSegment(segmentBlocks, s);
2798 if (codeSegments[s])
2799 codeSegments[s]->traverse(this);
2800 else
2801 builder.addSwitchBreak();
2802 }
2803 breakForLoop.pop();
2804
2805 builder.endSwitch(segmentBlocks);
2806
2807 return false;
2808}
2809
2810void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2811{
2812 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002813 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002814
2815 builder.clearAccessChain();
2816 builder.setAccessChainRValue(constant);
2817}
2818
2819bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2820{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002821 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002822 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002823
2824 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002825 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2826 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002827
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002828 // Spec requires back edges to target header blocks, and every header block
2829 // must dominate its merge block. Make a header block first to ensure these
2830 // conditions are met. By definition, it will contain OpLoopMerge, followed
2831 // by a block-ending branch. But we don't want to put any other body/test
2832 // instructions in it, since the body/test may have arbitrary instructions,
2833 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002834 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002835 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002836 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002837 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002838 spv::Block& test = builder.makeNewBlock();
2839 builder.createBranch(&test);
2840
2841 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002842 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002843 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002844 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2845
2846 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002847 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002848 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002849 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002850 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002851 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002852
2853 builder.setBuildPoint(&blocks.continue_target);
2854 if (node->getTerminal())
2855 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002856 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002857 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002858 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002859 builder.createBranch(&blocks.body);
2860
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002861 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002862 builder.setBuildPoint(&blocks.body);
2863 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002864 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002865 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002866 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002867
2868 builder.setBuildPoint(&blocks.continue_target);
2869 if (node->getTerminal())
2870 node->getTerminal()->traverse(this);
2871 if (node->getTest()) {
2872 node->getTest()->traverse(this);
2873 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002874 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002875 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002876 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002877 // TODO: unless there was a break/return/discard instruction
2878 // somewhere in the body, this is an infinite loop, so we should
2879 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002880 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002881 }
John Kessenich140f3df2015-06-26 16:58:36 -06002882 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002883 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002884 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002885 return false;
2886}
2887
2888bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2889{
2890 if (node->getExpression())
2891 node->getExpression()->traverse(this);
2892
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002893 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002894
John Kessenich140f3df2015-06-26 16:58:36 -06002895 switch (node->getFlowOp()) {
2896 case glslang::EOpKill:
2897 builder.makeDiscard();
2898 break;
2899 case glslang::EOpBreak:
2900 if (breakForLoop.top())
2901 builder.createLoopExit();
2902 else
2903 builder.addSwitchBreak();
2904 break;
2905 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002906 builder.createLoopContinue();
2907 break;
2908 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002909 if (node->getExpression()) {
2910 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2911 spv::Id returnId = accessChainLoad(glslangReturnType);
2912 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2913 builder.clearAccessChain();
2914 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2915 builder.setAccessChainLValue(copyId);
2916 multiTypeStore(glslangReturnType, returnId);
2917 returnId = builder.createLoad(copyId);
2918 }
2919 builder.makeReturn(false, returnId);
2920 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002921 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002922
2923 builder.clearAccessChain();
2924 break;
2925
2926 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002927 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002928 break;
2929 }
2930
2931 return false;
2932}
2933
2934spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2935{
qining25262b32016-05-06 17:25:16 -04002936 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002937 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002938 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002939 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05002940 spv::Id result = createSpvConstant(*node);
2941 if (result != spv::NoResult)
2942 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06002943 }
2944
2945 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002946 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002947 spv::Id spvType = convertGlslangToSpvType(node->getType());
2948
Rex Xucabbb782017-03-24 13:41:14 +08002949 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2950 node->getType().containsBasicType(glslang::EbtInt16) ||
2951 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002952 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002953 switch (storageClass) {
2954 case spv::StorageClassInput:
2955 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002956 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002957 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002958 break;
2959 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002960 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002961 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002962 break;
2963 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002964 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002965 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2966 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002967 else
2968 builder.addCapability(spv::CapabilityStorageUniform16);
2969 break;
2970 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002971 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06002972 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2973 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2974 break;
2975 default:
2976 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002977 }
2978 }
Rex Xuf89ad982017-04-07 23:22:33 +08002979
John Kessenich312dcfb2018-07-03 13:19:51 -06002980 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2981 node->getType().containsBasicType(glslang::EbtUint8);
2982 if (contains8BitType) {
2983 if (storageClass == spv::StorageClassPushConstant) {
2984 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2985 builder.addCapability(spv::CapabilityStoragePushConstant8);
2986 } else if (storageClass == spv::StorageClassUniform) {
2987 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2988 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01002989 } else if (storageClass == spv::StorageClassStorageBuffer) {
2990 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2991 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
John Kessenich312dcfb2018-07-03 13:19:51 -06002992 }
2993 }
2994
John Kessenich140f3df2015-06-26 16:58:36 -06002995 const char* name = node->getName().c_str();
2996 if (glslang::IsAnonymous(name))
2997 name = "";
2998
2999 return builder.createVariable(storageClass, spvType, name);
3000}
3001
3002// Return type Id of the sampled type.
3003spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3004{
3005 switch (sampler.type) {
3006 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003007#ifdef AMD_EXTENSIONS
3008 case glslang::EbtFloat16:
3009 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3010 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3011 return builder.makeFloatType(16);
3012#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003013 case glslang::EbtInt: return builder.makeIntType(32);
3014 case glslang::EbtUint: return builder.makeUintType(32);
3015 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003016 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003017 return builder.makeFloatType(32);
3018 }
3019}
3020
John Kessenich8c8505c2016-07-26 12:50:38 -06003021// If node is a swizzle operation, return the type that should be used if
3022// the swizzle base is first consumed by another operation, before the swizzle
3023// is applied.
3024spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3025{
John Kessenichecba76f2017-01-06 00:34:48 -07003026 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003027 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3028 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3029 else
3030 return spv::NoType;
3031}
3032
3033// When inverting a swizzle with a parent op, this function
3034// will apply the swizzle operation to a completed parent operation.
3035spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3036{
3037 std::vector<unsigned> swizzle;
3038 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3039 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3040}
3041
John Kessenich8c8505c2016-07-26 12:50:38 -06003042// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3043void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3044{
3045 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3046 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3047 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3048}
3049
John Kessenich3ac051e2015-12-20 11:29:16 -07003050// Convert from a glslang type to an SPV type, by calling into a
3051// recursive version of this function. This establishes the inherited
3052// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003053spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003054{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003055 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003056}
3057
3058// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003059// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003060// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003061spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003062 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3063 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003064{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003065 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003066
3067 switch (type.getBasicType()) {
3068 case glslang::EbtVoid:
3069 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003070 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003071 break;
3072 case glslang::EbtFloat:
3073 spvType = builder.makeFloatType(32);
3074 break;
3075 case glslang::EbtDouble:
3076 spvType = builder.makeFloatType(64);
3077 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003078 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003079 spvType = builder.makeFloatType(16);
3080 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003081 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003082 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3083 // a 32-bit int where non-0 means true.
3084 if (explicitLayout != glslang::ElpNone)
3085 spvType = builder.makeUintType(32);
3086 else
3087 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003088 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003089 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003090 spvType = builder.makeIntType(8);
3091 break;
3092 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003093 spvType = builder.makeUintType(8);
3094 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003095 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003096 spvType = builder.makeIntType(16);
3097 break;
3098 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003099 spvType = builder.makeUintType(16);
3100 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003101 case glslang::EbtInt:
3102 spvType = builder.makeIntType(32);
3103 break;
3104 case glslang::EbtUint:
3105 spvType = builder.makeUintType(32);
3106 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003107 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003108 spvType = builder.makeIntType(64);
3109 break;
3110 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003111 spvType = builder.makeUintType(64);
3112 break;
John Kessenich426394d2015-07-23 10:22:48 -06003113 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003114 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003115 spvType = builder.makeUintType(32);
3116 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003117#ifdef NV_EXTENSIONS
3118 case glslang::EbtAccStructNV:
3119 spvType = builder.makeAccelerationStructureNVType();
3120 break;
3121#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003122 case glslang::EbtSampler:
3123 {
3124 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003125 if (sampler.sampler) {
3126 // pure sampler
3127 spvType = builder.makeSamplerType();
3128 } else {
3129 // an image is present, make its type
3130 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3131 sampler.image ? 2 : 1, TranslateImageFormat(type));
3132 if (sampler.combined) {
3133 // already has both image and sampler, make the combined type
3134 spvType = builder.makeSampledImageType(spvType);
3135 }
John Kessenich55e7d112015-11-15 21:33:39 -07003136 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003137 }
John Kessenich140f3df2015-06-26 16:58:36 -06003138 break;
3139 case glslang::EbtStruct:
3140 case glslang::EbtBlock:
3141 {
3142 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003143 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003144
3145 // Try to share structs for different layouts, but not yet for other
3146 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003147 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003148 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003149 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003150 break;
3151
3152 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003153 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003154 memberRemapper[glslangMembers].resize(glslangMembers->size());
3155 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003156 }
3157 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003158 case glslang::EbtReference:
3159 {
3160 // Make the forward pointer, then recurse to convert the structure type, then
3161 // patch up the forward pointer with a real pointer type.
3162 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3163 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3164 forwardPointers[type.getReferentType()] = forwardId;
3165 }
3166 spvType = forwardPointers[type.getReferentType()];
3167 if (!forwardReferenceOnly) {
3168 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3169 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3170 forwardPointers[type.getReferentType()],
3171 referentType);
3172 }
3173 }
3174 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003175 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003176 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003177 break;
3178 }
3179
3180 if (type.isMatrix())
3181 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3182 else {
3183 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3184 if (type.getVectorSize() > 1)
3185 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3186 }
3187
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003188 if (type.isCoopMat()) {
3189 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3190 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3191 if (type.getBasicType() == glslang::EbtFloat16)
3192 builder.addCapability(spv::CapabilityFloat16);
3193
3194 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3195 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3196 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3197
3198 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3199 }
3200
John Kessenich140f3df2015-06-26 16:58:36 -06003201 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003202 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3203
John Kessenichc9a80832015-09-12 12:17:44 -06003204 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003205 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003206 // We need to decorate array strides for types needing explicit layout, except blocks.
3207 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003208 // Use a dummy glslang type for querying internal strides of
3209 // arrays of arrays, but using just a one-dimensional array.
3210 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003211 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3212 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003213
3214 // Will compute the higher-order strides here, rather than making a whole
3215 // pile of types and doing repetitive recursion on their contents.
3216 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3217 }
John Kessenichf8842e52016-01-04 19:22:56 -07003218
3219 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003220 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003221 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003222 if (stride > 0)
3223 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003224 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003225 }
3226 } else {
3227 // single-dimensional array, and don't yet have stride
3228
John Kessenichf8842e52016-01-04 19:22:56 -07003229 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003230 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3231 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003232 }
John Kessenich31ed4832015-09-09 17:51:38 -06003233
John Kessenichead86222018-03-28 18:01:20 -06003234 // Do the outer dimension, which might not be known for a runtime-sized array.
3235 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3236 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003237 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003238 else {
3239 if (!lastBufferBlockMember) {
3240 builder.addExtension("SPV_EXT_descriptor_indexing");
3241 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3242 }
John Kessenichead86222018-03-28 18:01:20 -06003243 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003244 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003245 if (stride > 0)
3246 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003247 }
3248
3249 return spvType;
3250}
3251
John Kessenich0e737842017-03-24 18:38:16 -06003252// TODO: this functionality should exist at a higher level, in creating the AST
3253//
3254// Identify interface members that don't have their required extension turned on.
3255//
3256bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3257{
Chao Chen3c366992018-09-19 11:41:59 -07003258#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003259 auto& extensions = glslangIntermediate->getRequestedExtensions();
3260
Rex Xubcf291a2017-03-29 23:01:36 +08003261 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3262 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3263 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003264 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3265 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3266 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003267
3268 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3269 if (member.getFieldName() == "gl_ViewportMask" &&
3270 extensions.find("GL_NV_viewport_array2") == extensions.end())
3271 return true;
3272 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3273 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3274 return true;
3275 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3276 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3277 return true;
3278 }
3279#endif
John Kessenich0e737842017-03-24 18:38:16 -06003280
3281 return false;
3282};
3283
John Kessenich6090df02016-06-30 21:18:02 -06003284// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3285// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3286// Mutually recursive with convertGlslangToSpvType().
3287spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3288 const glslang::TTypeList* glslangMembers,
3289 glslang::TLayoutPacking explicitLayout,
3290 const glslang::TQualifier& qualifier)
3291{
3292 // Create a vector of struct types for SPIR-V to consume
3293 std::vector<spv::Id> spvMembers;
3294 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 -06003295 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003296 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3297 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3298 if (glslangMember.hiddenMember()) {
3299 ++memberDelta;
3300 if (type.getBasicType() == glslang::EbtBlock)
3301 memberRemapper[glslangMembers][i] = -1;
3302 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003303 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003304 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003305 if (filterMember(glslangMember))
3306 continue;
3307 }
John Kessenich6090df02016-06-30 21:18:02 -06003308 // modify just this child's view of the qualifier
3309 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3310 InheritQualifiers(memberQualifier, qualifier);
3311
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003312 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003313 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003314 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003315
3316 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003317 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3318 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003319
3320 // Make forward pointers for any pointer members, and create a list of members to
3321 // convert to spirv types after creating the struct.
3322 if (glslangMember.getBasicType() == glslang::EbtReference) {
3323 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3324 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3325 }
3326 spvMembers.push_back(
3327 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3328 } else {
3329 spvMembers.push_back(
3330 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3331 }
John Kessenich6090df02016-06-30 21:18:02 -06003332 }
3333 }
3334
3335 // Make the SPIR-V type
3336 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003337 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003338 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3339
3340 // Decorate it
3341 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3342
John Kessenichd72f4882019-01-16 14:55:37 +07003343 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003344 auto it = deferredForwardPointers[i];
3345 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3346 }
3347
John Kessenich6090df02016-06-30 21:18:02 -06003348 return spvType;
3349}
3350
3351void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3352 const glslang::TTypeList* glslangMembers,
3353 glslang::TLayoutPacking explicitLayout,
3354 const glslang::TQualifier& qualifier,
3355 spv::Id spvType)
3356{
3357 // Name and decorate the non-hidden members
3358 int offset = -1;
3359 int locationOffset = 0; // for use within the members of this struct
3360 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3361 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3362 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003363 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003364 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003365 if (filterMember(glslangMember))
3366 continue;
3367 }
John Kessenich6090df02016-06-30 21:18:02 -06003368
3369 // modify just this child's view of the qualifier
3370 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3371 InheritQualifiers(memberQualifier, qualifier);
3372
3373 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003374 if (member < 0)
3375 continue;
3376
3377 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3378 builder.addMemberDecoration(spvType, member,
3379 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3380 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3381 // Add interpolation and auxiliary storage decorations only to
3382 // top-level members of Input and Output storage classes
3383 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3384 type.getQualifier().storage == glslang::EvqVaryingOut) {
3385 if (type.getBasicType() == glslang::EbtBlock ||
3386 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3387 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3388 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003389#ifdef NV_EXTENSIONS
3390 addMeshNVDecoration(spvType, member, memberQualifier);
3391#endif
John Kessenich6090df02016-06-30 21:18:02 -06003392 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003393 }
3394 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003395
John Kessenich5d610ee2018-03-07 18:05:55 -07003396 if (type.getBasicType() == glslang::EbtBlock &&
3397 qualifier.storage == glslang::EvqBuffer) {
3398 // Add memory decorations only to top-level members of shader storage block
3399 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003400 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003401 for (unsigned int i = 0; i < memory.size(); ++i)
3402 builder.addMemberDecoration(spvType, member, memory[i]);
3403 }
John Kessenich6090df02016-06-30 21:18:02 -06003404
John Kessenich5d610ee2018-03-07 18:05:55 -07003405 // Location assignment was already completed correctly by the front end,
3406 // just track whether a member needs to be decorated.
3407 // Ignore member locations if the container is an array, as that's
3408 // ill-specified and decisions have been made to not allow this.
3409 if (! type.isArray() && memberQualifier.hasLocation())
3410 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003411
John Kessenich5d610ee2018-03-07 18:05:55 -07003412 if (qualifier.hasLocation()) // track for upcoming inheritance
3413 locationOffset += glslangIntermediate->computeTypeLocationSize(
3414 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003415
John Kessenich5d610ee2018-03-07 18:05:55 -07003416 // component, XFB, others
3417 if (glslangMember.getQualifier().hasComponent())
3418 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3419 glslangMember.getQualifier().layoutComponent);
3420 if (glslangMember.getQualifier().hasXfbOffset())
3421 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3422 glslangMember.getQualifier().layoutXfbOffset);
3423 else if (explicitLayout != glslang::ElpNone) {
3424 // figure out what to do with offset, which is accumulating
3425 int nextOffset;
3426 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3427 if (offset >= 0)
3428 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3429 offset = nextOffset;
3430 }
John Kessenich6090df02016-06-30 21:18:02 -06003431
John Kessenich5d610ee2018-03-07 18:05:55 -07003432 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3433 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3434 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003435
John Kessenich5d610ee2018-03-07 18:05:55 -07003436 // built-in variable decorations
3437 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3438 if (builtIn != spv::BuiltInMax)
3439 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003440
John Kessenich5611c6d2018-04-05 11:25:02 -06003441 // nonuniform
3442 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3443
John Kessenichead86222018-03-28 18:01:20 -06003444 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3445 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3446 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3447 memberQualifier.semanticName);
3448 }
3449
chaoc771d89f2017-01-13 01:10:53 -08003450#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003451 if (builtIn == spv::BuiltInLayer) {
3452 // SPV_NV_viewport_array2 extension
3453 if (glslangMember.getQualifier().layoutViewportRelative){
3454 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3455 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3456 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003457 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003458 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3459 builder.addMemberDecoration(spvType, member,
3460 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3461 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3462 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3463 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003464 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003465 }
3466 if (glslangMember.getQualifier().layoutPassthrough) {
3467 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3468 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3469 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3470 }
chaoc771d89f2017-01-13 01:10:53 -08003471#endif
John Kessenich6090df02016-06-30 21:18:02 -06003472 }
3473
3474 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003475 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3476 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003477}
3478
John Kessenich6c292d32016-02-15 20:58:50 -07003479// Turn the expression forming the array size into an id.
3480// This is not quite trivial, because of specialization constants.
3481// Sometimes, a raw constant is turned into an Id, and sometimes
3482// a specialization constant expression is.
3483spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3484{
3485 // First, see if this is sized with a node, meaning a specialization constant:
3486 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3487 if (specNode != nullptr) {
3488 builder.clearAccessChain();
3489 specNode->traverse(this);
3490 return accessChainLoad(specNode->getAsTyped()->getType());
3491 }
qining25262b32016-05-06 17:25:16 -04003492
John Kessenich6c292d32016-02-15 20:58:50 -07003493 // Otherwise, need a compile-time (front end) size, get it:
3494 int size = arraySizes.getDimSize(dim);
3495 assert(size > 0);
3496 return builder.makeUintConstant(size);
3497}
3498
John Kessenich103bef92016-02-08 21:38:15 -07003499// Wrap the builder's accessChainLoad to:
3500// - localize handling of RelaxedPrecision
3501// - use the SPIR-V inferred type instead of another conversion of the glslang type
3502// (avoids unnecessary work and possible type punning for structures)
3503// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003504spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3505{
John Kessenich103bef92016-02-08 21:38:15 -07003506 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003507
3508 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3509 coherentFlags |= TranslateCoherent(type);
3510
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003511 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003512 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003513
John Kessenich5611c6d2018-04-05 11:25:02 -06003514 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003515 TranslateNonUniformDecoration(type.getQualifier()),
3516 nominalTypeId,
3517 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003518 TranslateMemoryScope(coherentFlags),
3519 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003520
3521 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003522 if (type.getBasicType() == glslang::EbtBool) {
3523 if (builder.isScalarType(nominalTypeId)) {
3524 // Conversion for bool
3525 spv::Id boolType = builder.makeBoolType();
3526 if (nominalTypeId != boolType)
3527 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3528 } else if (builder.isVectorType(nominalTypeId)) {
3529 // Conversion for bvec
3530 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3531 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3532 if (nominalTypeId != bvecType)
3533 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3534 }
3535 }
John Kessenich103bef92016-02-08 21:38:15 -07003536
3537 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003538}
3539
Rex Xu27253232016-02-23 17:51:09 +08003540// Wrap the builder's accessChainStore to:
3541// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003542//
3543// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003544void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3545{
3546 // Need to convert to abstract types when necessary
3547 if (type.getBasicType() == glslang::EbtBool) {
3548 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3549
3550 if (builder.isScalarType(nominalTypeId)) {
3551 // Conversion for bool
3552 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003553 if (nominalTypeId != boolType) {
3554 // keep these outside arguments, for determinant order-of-evaluation
3555 spv::Id one = builder.makeUintConstant(1);
3556 spv::Id zero = builder.makeUintConstant(0);
3557 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3558 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003559 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003560 } else if (builder.isVectorType(nominalTypeId)) {
3561 // Conversion for bvec
3562 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3563 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003564 if (nominalTypeId != bvecType) {
3565 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003566 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3567 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3568 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003569 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003570 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3571 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003572 }
3573 }
3574
Jeff Bolz36831c92018-09-05 10:11:41 -05003575 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3576 coherentFlags |= TranslateCoherent(type);
3577
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003578 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003579 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003580
Jeff Bolz36831c92018-09-05 10:11:41 -05003581 builder.accessChainStore(rvalue,
3582 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003583 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003584}
3585
John Kessenich4bf71552016-09-02 11:20:21 -06003586// For storing when types match at the glslang level, but not might match at the
3587// SPIR-V level.
3588//
3589// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003590// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003591// as in a member-decorated way.
3592//
3593// NOTE: This function can handle any store request; if it's not special it
3594// simplifies to a simple OpStore.
3595//
3596// Implicitly uses the existing builder.accessChain as the storage target.
3597void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3598{
John Kessenichb3e24e42016-09-11 12:33:43 -06003599 // we only do the complex path here if it's an aggregate
3600 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003601 accessChainStore(type, rValue);
3602 return;
3603 }
3604
John Kessenichb3e24e42016-09-11 12:33:43 -06003605 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003606 spv::Id rType = builder.getTypeId(rValue);
3607 spv::Id lValue = builder.accessChainGetLValue();
3608 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3609 if (lType == rType) {
3610 accessChainStore(type, rValue);
3611 return;
3612 }
3613
John Kessenichb3e24e42016-09-11 12:33:43 -06003614 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003615 // where the two types were the same type in GLSL. This requires member
3616 // by member copy, recursively.
3617
John Kessenichb3e24e42016-09-11 12:33:43 -06003618 // If an array, copy element by element.
3619 if (type.isArray()) {
3620 glslang::TType glslangElementType(type, 0);
3621 spv::Id elementRType = builder.getContainedTypeId(rType);
3622 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3623 // get the source member
3624 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003625
John Kessenichb3e24e42016-09-11 12:33:43 -06003626 // set up the target storage
3627 builder.clearAccessChain();
3628 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003629 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003630
John Kessenichb3e24e42016-09-11 12:33:43 -06003631 // store the member
3632 multiTypeStore(glslangElementType, elementRValue);
3633 }
3634 } else {
3635 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003636
John Kessenichb3e24e42016-09-11 12:33:43 -06003637 // loop over structure members
3638 const glslang::TTypeList& members = *type.getStruct();
3639 for (int m = 0; m < (int)members.size(); ++m) {
3640 const glslang::TType& glslangMemberType = *members[m].type;
3641
3642 // get the source member
3643 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3644 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3645
3646 // set up the target storage
3647 builder.clearAccessChain();
3648 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003649 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003650
3651 // store the member
3652 multiTypeStore(glslangMemberType, memberRValue);
3653 }
John Kessenich4bf71552016-09-02 11:20:21 -06003654 }
3655}
3656
John Kessenichf85e8062015-12-19 13:57:10 -07003657// Decide whether or not this type should be
3658// decorated with offsets and strides, and if so
3659// whether std140 or std430 rules should be applied.
3660glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003661{
John Kessenichf85e8062015-12-19 13:57:10 -07003662 // has to be a block
3663 if (type.getBasicType() != glslang::EbtBlock)
3664 return glslang::ElpNone;
3665
Chao Chen3c366992018-09-19 11:41:59 -07003666 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003667 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003668 type.getQualifier().storage != glslang::EvqBuffer &&
3669 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003670 return glslang::ElpNone;
3671
3672 // return the layout to use
3673 switch (type.getQualifier().layoutPacking) {
3674 case glslang::ElpStd140:
3675 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003676 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003677 return type.getQualifier().layoutPacking;
3678 default:
3679 return glslang::ElpNone;
3680 }
John Kessenich31ed4832015-09-09 17:51:38 -06003681}
3682
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003683// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003684int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003685{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003686 int size;
John Kessenich49987892015-12-29 17:11:44 -07003687 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003688 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003689
3690 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003691}
3692
John Kessenich49987892015-12-29 17:11:44 -07003693// 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 -07003694// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003695int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003696{
John Kessenich49987892015-12-29 17:11:44 -07003697 glslang::TType elementType;
3698 elementType.shallowCopy(matrixType);
3699 elementType.clearArraySizes();
3700
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003701 int size;
John Kessenich49987892015-12-29 17:11:44 -07003702 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003703 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003704
3705 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003706}
3707
John Kessenich5e4b1242015-08-06 22:53:06 -06003708// Given a member type of a struct, realign the current offset for it, and compute
3709// the next (not yet aligned) offset for the next member, which will get aligned
3710// on the next call.
3711// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3712// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3713// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003714void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003715 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003716{
3717 // this will get a positive value when deemed necessary
3718 nextOffset = -1;
3719
John Kessenich5e4b1242015-08-06 22:53:06 -06003720 // override anything in currentOffset with user-set offset
3721 if (memberType.getQualifier().hasOffset())
3722 currentOffset = memberType.getQualifier().layoutOffset;
3723
3724 // It could be that current linker usage in glslang updated all the layoutOffset,
3725 // in which case the following code does not matter. But, that's not quite right
3726 // once cross-compilation unit GLSL validation is done, as the original user
3727 // settings are needed in layoutOffset, and then the following will come into play.
3728
John Kessenichf85e8062015-12-19 13:57:10 -07003729 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003730 if (! memberType.getQualifier().hasOffset())
3731 currentOffset = -1;
3732
3733 return;
3734 }
3735
John Kessenichf85e8062015-12-19 13:57:10 -07003736 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003737 if (currentOffset < 0)
3738 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003739
John Kessenich5e4b1242015-08-06 22:53:06 -06003740 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3741 // but possibly not yet correctly aligned.
3742
3743 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003744 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003745 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003746
3747 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003748 // TODO: make this consistent in early phases of code:
3749 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3750 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3751 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003752 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003753 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003754 int dummySize;
3755 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3756 if (componentAlignment <= 4)
3757 memberAlignment = componentAlignment;
3758 }
3759
3760 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003761 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003762
3763 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003764 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003765 glslang::RoundToPow2(currentOffset, 16);
3766
John Kessenich5e4b1242015-08-06 22:53:06 -06003767 nextOffset = currentOffset + memberSize;
3768}
3769
David Netoa901ffe2016-06-08 14:11:40 +01003770void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003771{
David Netoa901ffe2016-06-08 14:11:40 +01003772 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3773 switch (glslangBuiltIn)
3774 {
3775 case glslang::EbvClipDistance:
3776 case glslang::EbvCullDistance:
3777 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003778#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003779 case glslang::EbvViewportMaskNV:
3780 case glslang::EbvSecondaryPositionNV:
3781 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003782 case glslang::EbvPositionPerViewNV:
3783 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003784 case glslang::EbvTaskCountNV:
3785 case glslang::EbvPrimitiveCountNV:
3786 case glslang::EbvPrimitiveIndicesNV:
3787 case glslang::EbvClipDistancePerViewNV:
3788 case glslang::EbvCullDistancePerViewNV:
3789 case glslang::EbvLayerPerViewNV:
3790 case glslang::EbvMeshViewCountNV:
3791 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003792#endif
David Netoa901ffe2016-06-08 14:11:40 +01003793 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3794 // Alternately, we could just call this for any glslang built-in, since the
3795 // capability already guards against duplicates.
3796 TranslateBuiltInDecoration(glslangBuiltIn, false);
3797 break;
3798 default:
3799 // Capabilities were already generated when the struct was declared.
3800 break;
3801 }
John Kessenichebb50532016-05-16 19:22:05 -06003802}
3803
John Kessenich6fccb3c2016-09-19 16:01:41 -06003804bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003805{
John Kessenicheee9d532016-09-19 18:09:30 -06003806 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003807}
3808
John Kessenichd41993d2017-09-10 15:21:05 -06003809// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003810// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3811// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003812bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003813{
John Kessenich6a14f782017-12-04 02:48:10 -07003814 assert(qualifier == glslang::EvqIn ||
3815 qualifier == glslang::EvqOut ||
3816 qualifier == glslang::EvqInOut ||
3817 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003818 return qualifier != glslang::EvqConstReadOnly;
3819}
3820
3821// Is parameter pass-by-original?
3822bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3823 bool implicitThisParam)
3824{
3825 if (implicitThisParam) // implicit this
3826 return true;
3827 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003828 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003829 return paramType.containsOpaque() || // sampler, etc.
3830 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3831}
3832
John Kessenich140f3df2015-06-26 16:58:36 -06003833// Make all the functions, skeletally, without actually visiting their bodies.
3834void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3835{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003836 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003837 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3838 if (paramPrecision != spv::NoPrecision)
3839 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003840 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003841 if (type.getBasicType() == glslang::EbtReference) {
3842 // Original and non-writable params pass the pointer directly and
3843 // use restrict/aliased, others are stored to a pointer in Function
3844 // memory and use RestrictPointer/AliasedPointer.
3845 if (originalParam(type.getQualifier().storage, type, false) ||
3846 !writableParam(type.getQualifier().storage)) {
3847 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
3848 } else {
3849 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
3850 }
3851 }
John Kessenichfad62972017-07-18 02:35:46 -06003852 };
3853
John Kessenich140f3df2015-06-26 16:58:36 -06003854 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3855 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003856 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003857 continue;
3858
3859 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003860 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003861 //
qining25262b32016-05-06 17:25:16 -04003862 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003863 // function. What it is an address of varies:
3864 //
John Kessenich4bf71552016-09-02 11:20:21 -06003865 // - "in" parameters not marked as "const" can be written to without modifying the calling
3866 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003867 //
3868 // - "const in" parameters can just be the r-value, as no writes need occur.
3869 //
John Kessenich4bf71552016-09-02 11:20:21 -06003870 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3871 // 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 -06003872
3873 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003874 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003875 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3876
John Kessenichfad62972017-07-18 02:35:46 -06003877 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3878 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003879
John Kessenichfad62972017-07-18 02:35:46 -06003880 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003881 for (int p = 0; p < (int)parameters.size(); ++p) {
3882 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3883 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003884 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003885 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003886 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003887 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3888 else
John Kessenich4bf71552016-09-02 11:20:21 -06003889 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003890 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003891 paramTypes.push_back(typeId);
3892 }
3893
3894 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003895 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3896 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003897 glslFunction->getName().c_str(), paramTypes,
3898 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003899 if (implicitThis)
3900 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003901
3902 // Track function to emit/call later
3903 functionMap[glslFunction->getName().c_str()] = function;
3904
3905 // Set the parameter id's
3906 for (int p = 0; p < (int)parameters.size(); ++p) {
3907 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3908 // give a name too
3909 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3910 }
3911 }
3912}
3913
3914// Process all the initializers, while skipping the functions and link objects
3915void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3916{
3917 builder.setBuildPoint(shaderEntry->getLastBlock());
3918 for (int i = 0; i < (int)initializers.size(); ++i) {
3919 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3920 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3921
3922 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003923 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003924 initializer->traverse(this);
3925 }
3926 }
3927}
3928
3929// Process all the functions, while skipping initializers.
3930void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3931{
3932 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3933 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003934 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003935 node->traverse(this);
3936 }
3937}
3938
3939void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3940{
qining25262b32016-05-06 17:25:16 -04003941 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003942 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003943 currentFunction = functionMap[node->getName().c_str()];
3944 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003945 builder.setBuildPoint(functionBlock);
3946}
3947
Rex Xu04db3f52015-09-16 11:44:02 +08003948void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003949{
Rex Xufc618912015-09-09 16:42:49 +08003950 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003951
3952 glslang::TSampler sampler = {};
3953 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003954#ifdef AMD_EXTENSIONS
3955 bool f16ShadowCompare = false;
3956#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003957 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003958 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3959 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003960#ifdef AMD_EXTENSIONS
3961 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3962#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003963 }
3964
John Kessenich140f3df2015-06-26 16:58:36 -06003965 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3966 builder.clearAccessChain();
3967 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003968
3969 // Special case l-value operands
3970 bool lvalue = false;
3971 switch (node.getOp()) {
3972 case glslang::EOpImageAtomicAdd:
3973 case glslang::EOpImageAtomicMin:
3974 case glslang::EOpImageAtomicMax:
3975 case glslang::EOpImageAtomicAnd:
3976 case glslang::EOpImageAtomicOr:
3977 case glslang::EOpImageAtomicXor:
3978 case glslang::EOpImageAtomicExchange:
3979 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05003980 case glslang::EOpImageAtomicLoad:
3981 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08003982 if (i == 0)
3983 lvalue = true;
3984 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003985 case glslang::EOpSparseImageLoad:
3986 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3987 lvalue = true;
3988 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003989#ifdef AMD_EXTENSIONS
3990 case glslang::EOpSparseTexture:
3991 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3992 lvalue = true;
3993 break;
3994 case glslang::EOpSparseTextureClamp:
3995 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3996 lvalue = true;
3997 break;
3998 case glslang::EOpSparseTextureLod:
3999 case glslang::EOpSparseTextureOffset:
4000 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4001 lvalue = true;
4002 break;
4003#else
Rex Xu48edadf2015-12-31 16:11:41 +08004004 case glslang::EOpSparseTexture:
4005 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4006 lvalue = true;
4007 break;
4008 case glslang::EOpSparseTextureClamp:
4009 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4010 lvalue = true;
4011 break;
4012 case glslang::EOpSparseTextureLod:
4013 case glslang::EOpSparseTextureOffset:
4014 if (i == 3)
4015 lvalue = true;
4016 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004017#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004018 case glslang::EOpSparseTextureFetch:
4019 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4020 lvalue = true;
4021 break;
4022 case glslang::EOpSparseTextureFetchOffset:
4023 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4024 lvalue = true;
4025 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004026#ifdef AMD_EXTENSIONS
4027 case glslang::EOpSparseTextureLodOffset:
4028 case glslang::EOpSparseTextureGrad:
4029 case glslang::EOpSparseTextureOffsetClamp:
4030 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4031 lvalue = true;
4032 break;
4033 case glslang::EOpSparseTextureGradOffset:
4034 case glslang::EOpSparseTextureGradClamp:
4035 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4036 lvalue = true;
4037 break;
4038 case glslang::EOpSparseTextureGradOffsetClamp:
4039 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4040 lvalue = true;
4041 break;
4042#else
Rex Xu48edadf2015-12-31 16:11:41 +08004043 case glslang::EOpSparseTextureLodOffset:
4044 case glslang::EOpSparseTextureGrad:
4045 case glslang::EOpSparseTextureOffsetClamp:
4046 if (i == 4)
4047 lvalue = true;
4048 break;
4049 case glslang::EOpSparseTextureGradOffset:
4050 case glslang::EOpSparseTextureGradClamp:
4051 if (i == 5)
4052 lvalue = true;
4053 break;
4054 case glslang::EOpSparseTextureGradOffsetClamp:
4055 if (i == 6)
4056 lvalue = true;
4057 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004058#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004059 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004060 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4061 lvalue = true;
4062 break;
4063 case glslang::EOpSparseTextureGatherOffset:
4064 case glslang::EOpSparseTextureGatherOffsets:
4065 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4066 lvalue = true;
4067 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004068#ifdef AMD_EXTENSIONS
4069 case glslang::EOpSparseTextureGatherLod:
4070 if (i == 3)
4071 lvalue = true;
4072 break;
4073 case glslang::EOpSparseTextureGatherLodOffset:
4074 case glslang::EOpSparseTextureGatherLodOffsets:
4075 if (i == 4)
4076 lvalue = true;
4077 break;
Rex Xu129799a2017-07-05 17:23:28 +08004078 case glslang::EOpSparseImageLoadLod:
4079 if (i == 3)
4080 lvalue = true;
4081 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004082#endif
Chao Chen3a137962018-09-19 11:41:27 -07004083#ifdef NV_EXTENSIONS
4084 case glslang::EOpImageSampleFootprintNV:
4085 if (i == 4)
4086 lvalue = true;
4087 break;
4088 case glslang::EOpImageSampleFootprintClampNV:
4089 case glslang::EOpImageSampleFootprintLodNV:
4090 if (i == 5)
4091 lvalue = true;
4092 break;
4093 case glslang::EOpImageSampleFootprintGradNV:
4094 if (i == 6)
4095 lvalue = true;
4096 break;
4097 case glslang::EOpImageSampleFootprintGradClampNV:
4098 if (i == 7)
4099 lvalue = true;
4100 break;
4101#endif
Rex Xufc618912015-09-09 16:42:49 +08004102 default:
4103 break;
4104 }
4105
Rex Xu6b86d492015-09-16 17:48:22 +08004106 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08004107 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08004108 else
John Kessenich32cfd492016-02-02 12:37:46 -07004109 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004110 }
4111}
4112
John Kessenichfc51d282015-08-19 13:34:18 -06004113void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004114{
John Kessenichfc51d282015-08-19 13:34:18 -06004115 builder.clearAccessChain();
4116 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004117 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004118}
John Kessenich140f3df2015-06-26 16:58:36 -06004119
John Kessenichfc51d282015-08-19 13:34:18 -06004120spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4121{
John Kesseniche485c7a2017-05-31 18:50:53 -06004122 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004123 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004124
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004125 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004126
John Kessenichfc51d282015-08-19 13:34:18 -06004127 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004128
4129 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4130 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
4131 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004132#ifdef AMD_EXTENSIONS
4133 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
4134 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4135 : false;
4136#endif
4137
John Kessenichfc51d282015-08-19 13:34:18 -06004138 std::vector<spv::Id> arguments;
4139 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08004140 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06004141 else
4142 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004143 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004144
4145 spv::Builder::TextureParameters params = { };
4146 params.sampler = arguments[0];
4147
Rex Xu04db3f52015-09-16 11:44:02 +08004148 glslang::TCrackedTextureOp cracked;
4149 node->crackTexture(sampler, cracked);
4150
amhagan05506bb2017-06-13 16:53:02 -04004151 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004152
John Kessenichfc51d282015-08-19 13:34:18 -06004153 // Check for queries
4154 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004155 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4156 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004157 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004158
John Kessenichfc51d282015-08-19 13:34:18 -06004159 switch (node->getOp()) {
4160 case glslang::EOpImageQuerySize:
4161 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004162 if (arguments.size() > 1) {
4163 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004164 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004165 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004166 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004167 case glslang::EOpImageQuerySamples:
4168 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004169 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004170 case glslang::EOpTextureQueryLod:
4171 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004172 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004173 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004174 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004175 case glslang::EOpSparseTexelsResident:
4176 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004177 default:
4178 assert(0);
4179 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004180 }
John Kessenich140f3df2015-06-26 16:58:36 -06004181 }
4182
LoopDawg4425f242018-02-18 11:40:01 -07004183 int components = node->getType().getVectorSize();
4184
4185 if (node->getOp() == glslang::EOpTextureFetch) {
4186 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4187 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4188 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4189 // here around e.g. which ones return scalars or other types.
4190 components = 4;
4191 }
4192
4193 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4194
4195 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4196
Rex Xufc618912015-09-09 16:42:49 +08004197 // Check for image functions other than queries
4198 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004199 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004200 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004201 spv::IdImmediate image = { true, *(opIt++) };
4202 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004203
4204 // Handle subpass operations
4205 // TODO: GLSL should change to have the "MS" only on the type rather than the
4206 // built-in function.
4207 if (cracked.subpass) {
4208 // add on the (0,0) coordinate
4209 spv::Id zero = builder.makeIntConstant(0);
4210 std::vector<spv::Id> comps;
4211 comps.push_back(zero);
4212 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004213 spv::IdImmediate coord = { true,
4214 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4215 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07004216 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06004217 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
4218 operands.push_back(imageOperands);
4219 spv::IdImmediate imageOperand = { true, *(opIt++) };
4220 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07004221 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004222 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4223 builder.setPrecision(result, precision);
4224 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004225 }
4226
John Kessenich149afc32018-08-14 13:31:43 -06004227 spv::IdImmediate coord = { true, *(opIt++) };
4228 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004229#ifdef AMD_EXTENSIONS
4230 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4231#else
John Kessenich56bab042015-09-16 10:54:31 -06004232 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004233#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004234 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004235 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004236 mask = mask | spv::ImageOperandsSampleMask;
4237 }
Rex Xu129799a2017-07-05 17:23:28 +08004238#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004239 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004240 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4241 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004242 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004243 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004244#endif
4245 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4246 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4247 if (mask) {
4248 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4249 operands.push_back(imageOperands);
4250 }
4251 if (mask & spv::ImageOperandsSampleMask) {
4252 spv::IdImmediate imageOperand = { true, *opIt++ };
4253 operands.push_back(imageOperand);
4254 }
4255#ifdef AMD_EXTENSIONS
4256 if (mask & spv::ImageOperandsLodMask) {
4257 spv::IdImmediate imageOperand = { true, *opIt++ };
4258 operands.push_back(imageOperand);
4259 }
4260#endif
4261 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4262 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4263 operands.push_back(imageOperand);
4264 }
4265
John Kessenich149afc32018-08-14 13:31:43 -06004266 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004267 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004268
John Kessenich149afc32018-08-14 13:31:43 -06004269 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004270 builder.setPrecision(result[0], precision);
4271
4272 // If needed, add a conversion constructor to the proper size.
4273 if (components != node->getType().getVectorSize())
4274 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4275
4276 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004277#ifdef AMD_EXTENSIONS
4278 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4279#else
John Kessenich56bab042015-09-16 10:54:31 -06004280 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004281#endif
Rex Xu129799a2017-07-05 17:23:28 +08004282
Jeff Bolz36831c92018-09-05 10:11:41 -05004283 // Push the texel value before the operands
4284#ifdef AMD_EXTENSIONS
4285 if (sampler.ms || cracked.lod) {
4286#else
4287 if (sampler.ms) {
4288#endif
John Kessenich149afc32018-08-14 13:31:43 -06004289 spv::IdImmediate texel = { true, *(opIt + 1) };
4290 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004291 } else {
4292 spv::IdImmediate texel = { true, *opIt };
4293 operands.push_back(texel);
4294 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004295
4296 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4297 if (sampler.ms) {
4298 mask = mask | spv::ImageOperandsSampleMask;
4299 }
4300#ifdef AMD_EXTENSIONS
4301 if (cracked.lod) {
4302 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4303 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4304 mask = mask | spv::ImageOperandsLodMask;
4305 }
4306#endif
4307 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4308 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
4309 if (mask) {
4310 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4311 operands.push_back(imageOperands);
4312 }
4313 if (mask & spv::ImageOperandsSampleMask) {
4314 spv::IdImmediate imageOperand = { true, *opIt++ };
4315 operands.push_back(imageOperand);
4316 }
4317#ifdef AMD_EXTENSIONS
4318 if (mask & spv::ImageOperandsLodMask) {
4319 spv::IdImmediate imageOperand = { true, *opIt++ };
4320 operands.push_back(imageOperand);
4321 }
4322#endif
4323 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
4324 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4325 operands.push_back(imageOperand);
4326 }
4327
John Kessenich56bab042015-09-16 10:54:31 -06004328 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004329 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004330 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004331 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004332#ifdef AMD_EXTENSIONS
4333 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
4334#else
Rex Xu5eafa472016-02-19 22:24:03 +08004335 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004336#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004337 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004338 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004339 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4340
Jeff Bolz36831c92018-09-05 10:11:41 -05004341 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004342 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004343 mask = mask | spv::ImageOperandsSampleMask;
4344 }
Rex Xu129799a2017-07-05 17:23:28 +08004345#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004346 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004347 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4348 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4349
Jeff Bolz36831c92018-09-05 10:11:41 -05004350 mask = mask | spv::ImageOperandsLodMask;
4351 }
4352#endif
4353 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4354 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4355 if (mask) {
4356 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004357 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004358 }
4359 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004360 spv::IdImmediate imageOperand = { true, *opIt++ };
4361 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004362 }
4363#ifdef AMD_EXTENSIONS
4364 if (mask & spv::ImageOperandsLodMask) {
4365 spv::IdImmediate imageOperand = { true, *opIt++ };
4366 operands.push_back(imageOperand);
4367 }
Rex Xu129799a2017-07-05 17:23:28 +08004368#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004369 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4370 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4371 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004372 }
4373
4374 // Create the return type that was a special structure
4375 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004376 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004377 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4378 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4379
4380 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4381
4382 // Decode the return type
4383 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4384 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004385 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004386 // Process image atomic operations
4387
4388 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4389 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004390 // For non-MS, the sample value should be 0
4391 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4392 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004393
Jeff Bolz36831c92018-09-05 10:11:41 -05004394 spv::Id resultTypeId;
4395 // imageAtomicStore has a void return type so base the pointer type on
4396 // the type of the value operand.
4397 if (node->getOp() == glslang::EOpImageAtomicStore) {
4398 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4399 } else {
4400 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4401 }
John Kessenich56bab042015-09-16 10:54:31 -06004402 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004403
4404 std::vector<spv::Id> operands;
4405 operands.push_back(pointer);
4406 for (; opIt != arguments.end(); ++opIt)
4407 operands.push_back(*opIt);
4408
John Kessenich8c8505c2016-07-26 12:50:38 -06004409 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004410 }
4411 }
4412
amhagan05506bb2017-06-13 16:53:02 -04004413#ifdef AMD_EXTENSIONS
4414 // Check for fragment mask functions other than queries
4415 if (cracked.fragMask) {
4416 assert(sampler.ms);
4417
4418 auto opIt = arguments.begin();
4419 std::vector<spv::Id> operands;
4420
4421 // Extract the image if necessary
4422 if (builder.isSampledImage(params.sampler))
4423 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4424
4425 operands.push_back(params.sampler);
4426 ++opIt;
4427
4428 if (sampler.isSubpass()) {
4429 // add on the (0,0) coordinate
4430 spv::Id zero = builder.makeIntConstant(0);
4431 std::vector<spv::Id> comps;
4432 comps.push_back(zero);
4433 comps.push_back(zero);
4434 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4435 }
4436
4437 for (; opIt != arguments.end(); ++opIt)
4438 operands.push_back(*opIt);
4439
4440 spv::Op fragMaskOp = spv::OpNop;
4441 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4442 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4443 else if (node->getOp() == glslang::EOpFragmentFetch)
4444 fragMaskOp = spv::OpFragmentFetchAMD;
4445
4446 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4447 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4448 return builder.createOp(fragMaskOp, resultType(), operands);
4449 }
4450#endif
4451
Rex Xufc618912015-09-09 16:42:49 +08004452 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004453 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004454#ifdef NV_EXTENSIONS
4455 bool imageFootprint = node->isImageFootprint();
4456#endif
4457
Rex Xu71519fe2015-11-11 15:35:47 +08004458 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4459
John Kessenichfc51d282015-08-19 13:34:18 -06004460 // check for bias argument
4461 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004462#ifdef AMD_EXTENSIONS
4463 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4464#else
Rex Xu71519fe2015-11-11 15:35:47 +08004465 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004466#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004467 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004468#ifdef AMD_EXTENSIONS
4469 if (cracked.gather)
4470 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004471
4472 if (f16ShadowCompare)
4473 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004474#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004475 if (cracked.offset)
4476 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004477#ifdef AMD_EXTENSIONS
4478 else if (cracked.offsets)
4479 ++nonBiasArgCount;
4480#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004481 if (cracked.grad)
4482 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004483 if (cracked.lodClamp)
4484 ++nonBiasArgCount;
4485 if (sparse)
4486 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004487#ifdef NV_EXTENSIONS
4488 if (imageFootprint)
4489 //Following three extra arguments
4490 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4491 nonBiasArgCount += 3;
4492#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004493 if ((int)arguments.size() > nonBiasArgCount)
4494 bias = true;
4495 }
4496
John Kessenicha5c33d62016-06-02 23:45:21 -06004497 // See if the sampler param should really be just the SPV image part
4498 if (cracked.fetch) {
4499 // a fetch needs to have the image extracted first
4500 if (builder.isSampledImage(params.sampler))
4501 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4502 }
4503
Rex Xu225e0fc2016-11-17 17:47:59 +08004504#ifdef AMD_EXTENSIONS
4505 if (cracked.gather) {
4506 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4507 if (bias || cracked.lod ||
4508 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4509 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004510 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004511 }
4512 }
4513#endif
4514
John Kessenichfc51d282015-08-19 13:34:18 -06004515 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004516
John Kessenichfc51d282015-08-19 13:34:18 -06004517 params.coords = arguments[1];
4518 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004519 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004520
4521 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004522#ifdef AMD_EXTENSIONS
4523 if (cubeCompare || f16ShadowCompare) {
4524#else
Rex Xu48edadf2015-12-31 16:11:41 +08004525 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004526#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004527 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004528 ++extraArgs;
4529 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004530 params.Dref = arguments[2];
4531 ++extraArgs;
4532 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004533 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004534 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004535 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004536 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004537 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004538 dRefComp = builder.getNumComponents(params.coords) - 1;
4539 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004540 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4541 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004542
4543 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004544 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004545 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004546 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004547 } else if (glslangIntermediate->getStage() != EShLangFragment
4548#ifdef NV_EXTENSIONS
4549 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4550 && !(glslangIntermediate->getStage() == EShLangCompute &&
4551 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4552#endif
4553 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004554 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4555 noImplicitLod = true;
4556 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004557
4558 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004559 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004560 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004561 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004562 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004563
4564 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004565 if (cracked.grad) {
4566 params.gradX = arguments[2 + extraArgs];
4567 params.gradY = arguments[3 + extraArgs];
4568 extraArgs += 2;
4569 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004570
4571 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004572 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004573 params.offset = arguments[2 + extraArgs];
4574 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004575 } else if (cracked.offsets) {
4576 params.offsets = arguments[2 + extraArgs];
4577 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004578 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004579
4580 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004581 if (cracked.lodClamp) {
4582 params.lodClamp = arguments[2 + extraArgs];
4583 ++extraArgs;
4584 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004585 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004586 if (sparse) {
4587 params.texelOut = arguments[2 + extraArgs];
4588 ++extraArgs;
4589 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004590
John Kessenich76d4dfc2016-06-16 12:43:23 -06004591 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004592 if (cracked.gather && ! sampler.shadow) {
4593 // default component is 0, if missing, otherwise an argument
4594 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004595 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004596 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004597 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004598 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004599 }
Chao Chen3a137962018-09-19 11:41:27 -07004600#ifdef NV_EXTENSIONS
4601 spv::Id resultStruct = spv::NoResult;
4602 if (imageFootprint) {
4603 //Following three extra arguments
4604 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4605 params.granularity = arguments[2 + extraArgs];
4606 params.coarse = arguments[3 + extraArgs];
4607 resultStruct = arguments[4 + extraArgs];
4608 extraArgs += 3;
4609 }
4610#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004611 // bias
4612 if (bias) {
4613 params.bias = arguments[2 + extraArgs];
4614 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004615 }
John Kessenichfc51d282015-08-19 13:34:18 -06004616
Chao Chen3a137962018-09-19 11:41:27 -07004617#ifdef NV_EXTENSIONS
4618 if (imageFootprint) {
4619 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4620 builder.addCapability(spv::CapabilityImageFootprintNV);
4621
4622
4623 //resultStructType(OpenGL type) contains 5 elements:
4624 //struct gl_TextureFootprint2DNV {
4625 // uvec2 anchor;
4626 // uvec2 offset;
4627 // uvec2 mask;
4628 // uint lod;
4629 // uint granularity;
4630 //};
4631 //or
4632 //struct gl_TextureFootprint3DNV {
4633 // uvec3 anchor;
4634 // uvec3 offset;
4635 // uvec2 mask;
4636 // uint lod;
4637 // uint granularity;
4638 //};
4639 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4640 assert(builder.isStructType(resultStructType));
4641
4642 //resType (SPIR-V type) contains 6 elements:
4643 //Member 0 must be a Boolean type scalar(LOD),
4644 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4645 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4646 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4647 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4648 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4649 std::vector<spv::Id> members;
4650 members.push_back(resultType());
4651 for (int i = 0; i < 5; i++) {
4652 members.push_back(builder.getContainedTypeId(resultStructType, i));
4653 }
4654 spv::Id resType = builder.makeStructType(members, "ResType");
4655
4656 //call ImageFootprintNV
4657 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
4658
4659 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4660 for (int i = 0; i < 5; i++) {
4661 builder.clearAccessChain();
4662 builder.setAccessChainLValue(resultStruct);
4663
4664 //Accessing to a struct we created, no coherent flag is set
4665 spv::Builder::AccessChain::CoherentFlags flags;
4666 flags.clear();
4667
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004668 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004669 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4670 }
4671 return builder.createCompositeExtract(res, resultType(), 0);
4672 }
4673#endif
4674
John Kessenich65336482016-06-16 14:06:26 -06004675 // projective component (might not to move)
4676 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4677 // are divided by the last component of P."
4678 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4679 // unused components will appear after all used components."
4680 if (cracked.proj) {
4681 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4682 int projTargetComp;
4683 switch (sampler.dim) {
4684 case glslang::Esd1D: projTargetComp = 1; break;
4685 case glslang::Esd2D: projTargetComp = 2; break;
4686 case glslang::EsdRect: projTargetComp = 2; break;
4687 default: projTargetComp = projSourceComp; break;
4688 }
4689 // copy the projective coordinate if we have to
4690 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004691 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004692 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4693 projSourceComp);
4694 params.coords = builder.createCompositeInsert(projComp, params.coords,
4695 builder.getTypeId(params.coords), projTargetComp);
4696 }
4697 }
4698
Jeff Bolz36831c92018-09-05 10:11:41 -05004699 // nonprivate
4700 if (imageType.getQualifier().nonprivate) {
4701 params.nonprivate = true;
4702 }
4703
4704 // volatile
4705 if (imageType.getQualifier().volatil) {
4706 params.volatil = true;
4707 }
4708
St0fFa1184dd2018-04-09 21:08:14 +02004709 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004710 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004711 );
LoopDawg4425f242018-02-18 11:40:01 -07004712
4713 if (components != node->getType().getVectorSize())
4714 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4715
4716 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004717}
4718
4719spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4720{
4721 // Grab the function's pointer from the previously created function
4722 spv::Function* function = functionMap[node->getName().c_str()];
4723 if (! function)
4724 return 0;
4725
4726 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4727 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4728
4729 // See comments in makeFunctions() for details about the semantics for parameter passing.
4730 //
4731 // These imply we need a four step process:
4732 // 1. Evaluate the arguments
4733 // 2. Allocate and make copies of in, out, and inout arguments
4734 // 3. Make the call
4735 // 4. Copy back the results
4736
John Kessenichd3ed90b2018-05-04 11:43:03 -06004737 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004738 std::vector<spv::Builder::AccessChain> lValues;
4739 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004740 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004741 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004742 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004743 // build l-value
4744 builder.clearAccessChain();
4745 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004746 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004747 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004748 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004749 // save l-value
4750 lValues.push_back(builder.getAccessChain());
4751 } else {
4752 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004753 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004754 }
4755 }
4756
4757 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4758 // copy the original into that space.
4759 //
4760 // Also, build up the list of actual arguments to pass in for the call
4761 int lValueCount = 0;
4762 int rValueCount = 0;
4763 std::vector<spv::Id> spvArgs;
4764 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4765 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004766 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004767 builder.setAccessChain(lValues[lValueCount]);
4768 arg = builder.accessChainGetLValue();
4769 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004770 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004771 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004772 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004773 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4774 // need to copy the input into output space
4775 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004776 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004777 builder.clearAccessChain();
4778 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004779 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004780 }
4781 ++lValueCount;
4782 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004783 // process r-value, which involves a copy for a type mismatch
4784 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4785 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4786 builder.clearAccessChain();
4787 builder.setAccessChainLValue(argCopy);
4788 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4789 arg = builder.createLoad(argCopy);
4790 } else
4791 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004792 ++rValueCount;
4793 }
4794 spvArgs.push_back(arg);
4795 }
4796
4797 // 3. Make the call.
4798 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004799 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004800
4801 // 4. Copy back out an "out" arguments.
4802 lValueCount = 0;
4803 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004804 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004805 ++lValueCount;
4806 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004807 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4808 spv::Id copy = builder.createLoad(spvArgs[a]);
4809 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004810 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004811 }
4812 ++lValueCount;
4813 }
4814 }
4815
4816 return result;
4817}
4818
4819// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004820spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004821 spv::Id typeId, spv::Id left, spv::Id right,
4822 glslang::TBasicType typeProxy, bool reduceComparison)
4823{
John Kessenich66011cb2018-03-06 16:12:04 -07004824 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4825 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004826 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004827
4828 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004829 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004830 bool comparison = false;
4831
4832 switch (op) {
4833 case glslang::EOpAdd:
4834 case glslang::EOpAddAssign:
4835 if (isFloat)
4836 binOp = spv::OpFAdd;
4837 else
4838 binOp = spv::OpIAdd;
4839 break;
4840 case glslang::EOpSub:
4841 case glslang::EOpSubAssign:
4842 if (isFloat)
4843 binOp = spv::OpFSub;
4844 else
4845 binOp = spv::OpISub;
4846 break;
4847 case glslang::EOpMul:
4848 case glslang::EOpMulAssign:
4849 if (isFloat)
4850 binOp = spv::OpFMul;
4851 else
4852 binOp = spv::OpIMul;
4853 break;
4854 case glslang::EOpVectorTimesScalar:
4855 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004856 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004857 if (builder.isVector(right))
4858 std::swap(left, right);
4859 assert(builder.isScalar(right));
4860 needMatchingVectors = false;
4861 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01004862 } else if (isFloat)
4863 binOp = spv::OpFMul;
4864 else
John Kessenichec43d0a2015-07-04 17:17:31 -06004865 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004866 break;
4867 case glslang::EOpVectorTimesMatrix:
4868 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004869 binOp = spv::OpVectorTimesMatrix;
4870 break;
4871 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004872 binOp = spv::OpMatrixTimesVector;
4873 break;
4874 case glslang::EOpMatrixTimesScalar:
4875 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004876 binOp = spv::OpMatrixTimesScalar;
4877 break;
4878 case glslang::EOpMatrixTimesMatrix:
4879 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004880 binOp = spv::OpMatrixTimesMatrix;
4881 break;
4882 case glslang::EOpOuterProduct:
4883 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004884 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004885 break;
4886
4887 case glslang::EOpDiv:
4888 case glslang::EOpDivAssign:
4889 if (isFloat)
4890 binOp = spv::OpFDiv;
4891 else if (isUnsigned)
4892 binOp = spv::OpUDiv;
4893 else
4894 binOp = spv::OpSDiv;
4895 break;
4896 case glslang::EOpMod:
4897 case glslang::EOpModAssign:
4898 if (isFloat)
4899 binOp = spv::OpFMod;
4900 else if (isUnsigned)
4901 binOp = spv::OpUMod;
4902 else
4903 binOp = spv::OpSMod;
4904 break;
4905 case glslang::EOpRightShift:
4906 case glslang::EOpRightShiftAssign:
4907 if (isUnsigned)
4908 binOp = spv::OpShiftRightLogical;
4909 else
4910 binOp = spv::OpShiftRightArithmetic;
4911 break;
4912 case glslang::EOpLeftShift:
4913 case glslang::EOpLeftShiftAssign:
4914 binOp = spv::OpShiftLeftLogical;
4915 break;
4916 case glslang::EOpAnd:
4917 case glslang::EOpAndAssign:
4918 binOp = spv::OpBitwiseAnd;
4919 break;
4920 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004921 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004922 binOp = spv::OpLogicalAnd;
4923 break;
4924 case glslang::EOpInclusiveOr:
4925 case glslang::EOpInclusiveOrAssign:
4926 binOp = spv::OpBitwiseOr;
4927 break;
4928 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004929 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004930 binOp = spv::OpLogicalOr;
4931 break;
4932 case glslang::EOpExclusiveOr:
4933 case glslang::EOpExclusiveOrAssign:
4934 binOp = spv::OpBitwiseXor;
4935 break;
4936 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004937 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004938 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004939 break;
4940
4941 case glslang::EOpLessThan:
4942 case glslang::EOpGreaterThan:
4943 case glslang::EOpLessThanEqual:
4944 case glslang::EOpGreaterThanEqual:
4945 case glslang::EOpEqual:
4946 case glslang::EOpNotEqual:
4947 case glslang::EOpVectorEqual:
4948 case glslang::EOpVectorNotEqual:
4949 comparison = true;
4950 break;
4951 default:
4952 break;
4953 }
4954
John Kessenich7c1aa102015-10-15 13:29:11 -06004955 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004956 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004957 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06004958 if (builder.isMatrix(left) || builder.isMatrix(right) ||
4959 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004960 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004961
4962 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004963 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004964 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004965
qining25262b32016-05-06 17:25:16 -04004966 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004967 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004968 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004969 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004970 }
4971
4972 if (! comparison)
4973 return 0;
4974
John Kessenich7c1aa102015-10-15 13:29:11 -06004975 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004976
John Kessenich4583b612016-08-07 19:14:22 -06004977 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004978 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4979 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004980 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004981 return result;
4982 }
John Kessenich140f3df2015-06-26 16:58:36 -06004983
4984 switch (op) {
4985 case glslang::EOpLessThan:
4986 if (isFloat)
4987 binOp = spv::OpFOrdLessThan;
4988 else if (isUnsigned)
4989 binOp = spv::OpULessThan;
4990 else
4991 binOp = spv::OpSLessThan;
4992 break;
4993 case glslang::EOpGreaterThan:
4994 if (isFloat)
4995 binOp = spv::OpFOrdGreaterThan;
4996 else if (isUnsigned)
4997 binOp = spv::OpUGreaterThan;
4998 else
4999 binOp = spv::OpSGreaterThan;
5000 break;
5001 case glslang::EOpLessThanEqual:
5002 if (isFloat)
5003 binOp = spv::OpFOrdLessThanEqual;
5004 else if (isUnsigned)
5005 binOp = spv::OpULessThanEqual;
5006 else
5007 binOp = spv::OpSLessThanEqual;
5008 break;
5009 case glslang::EOpGreaterThanEqual:
5010 if (isFloat)
5011 binOp = spv::OpFOrdGreaterThanEqual;
5012 else if (isUnsigned)
5013 binOp = spv::OpUGreaterThanEqual;
5014 else
5015 binOp = spv::OpSGreaterThanEqual;
5016 break;
5017 case glslang::EOpEqual:
5018 case glslang::EOpVectorEqual:
5019 if (isFloat)
5020 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005021 else if (isBool)
5022 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005023 else
5024 binOp = spv::OpIEqual;
5025 break;
5026 case glslang::EOpNotEqual:
5027 case glslang::EOpVectorNotEqual:
5028 if (isFloat)
5029 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005030 else if (isBool)
5031 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005032 else
5033 binOp = spv::OpINotEqual;
5034 break;
5035 default:
5036 break;
5037 }
5038
qining25262b32016-05-06 17:25:16 -04005039 if (binOp != spv::OpNop) {
5040 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005041 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005042 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005043 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005044 }
John Kessenich140f3df2015-06-26 16:58:36 -06005045
5046 return 0;
5047}
5048
John Kessenich04bb8a02015-12-12 12:28:14 -07005049//
5050// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5051// These can be any of:
5052//
5053// matrix * scalar
5054// scalar * matrix
5055// matrix * matrix linear algebraic
5056// matrix * vector
5057// vector * matrix
5058// matrix * matrix componentwise
5059// matrix op matrix op in {+, -, /}
5060// matrix op scalar op in {+, -, /}
5061// scalar op matrix op in {+, -, /}
5062//
John Kessenichead86222018-03-28 18:01:20 -06005063spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5064 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005065{
5066 bool firstClass = true;
5067
5068 // First, handle first-class matrix operations (* and matrix/scalar)
5069 switch (op) {
5070 case spv::OpFDiv:
5071 if (builder.isMatrix(left) && builder.isScalar(right)) {
5072 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005073 spv::Id resultType = builder.getTypeId(right);
5074 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005075 op = spv::OpMatrixTimesScalar;
5076 } else
5077 firstClass = false;
5078 break;
5079 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005080 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005081 std::swap(left, right);
5082 assert(builder.isScalar(right));
5083 break;
5084 case spv::OpVectorTimesMatrix:
5085 assert(builder.isVector(left));
5086 assert(builder.isMatrix(right));
5087 break;
5088 case spv::OpMatrixTimesVector:
5089 assert(builder.isMatrix(left));
5090 assert(builder.isVector(right));
5091 break;
5092 case spv::OpMatrixTimesMatrix:
5093 assert(builder.isMatrix(left));
5094 assert(builder.isMatrix(right));
5095 break;
5096 default:
5097 firstClass = false;
5098 break;
5099 }
5100
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005101 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5102 firstClass = true;
5103
qining25262b32016-05-06 17:25:16 -04005104 if (firstClass) {
5105 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005106 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005107 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005108 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005109 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005110
LoopDawg592860c2016-06-09 08:57:35 -06005111 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005112 // The result type of all of them is the same type as the (a) matrix operand.
5113 // The algorithm is to:
5114 // - break the matrix(es) into vectors
5115 // - smear any scalar to a vector
5116 // - do vector operations
5117 // - make a matrix out the vector results
5118 switch (op) {
5119 case spv::OpFAdd:
5120 case spv::OpFSub:
5121 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005122 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005123 case spv::OpFMul:
5124 {
5125 // one time set up...
5126 bool leftMat = builder.isMatrix(left);
5127 bool rightMat = builder.isMatrix(right);
5128 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5129 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5130 spv::Id scalarType = builder.getScalarTypeId(typeId);
5131 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5132 std::vector<spv::Id> results;
5133 spv::Id smearVec = spv::NoResult;
5134 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005135 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005136 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005137 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005138
5139 // do each vector op
5140 for (unsigned int c = 0; c < numCols; ++c) {
5141 std::vector<unsigned int> indexes;
5142 indexes.push_back(c);
5143 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5144 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005145 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005146 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005147 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005148 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005149 }
5150
5151 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005152 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005153 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005154 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005155 }
5156 default:
5157 assert(0);
5158 return spv::NoResult;
5159 }
5160}
5161
John Kessenichead86222018-03-28 18:01:20 -06005162spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
5163 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005164{
5165 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005166 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005167 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005168 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5169 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005170
5171 switch (op) {
5172 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005173 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005174 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005175 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005176 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005177 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005178 unaryOp = spv::OpSNegate;
5179 break;
5180
5181 case glslang::EOpLogicalNot:
5182 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005183 unaryOp = spv::OpLogicalNot;
5184 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005185 case glslang::EOpBitwiseNot:
5186 unaryOp = spv::OpNot;
5187 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005188
John Kessenich140f3df2015-06-26 16:58:36 -06005189 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005190 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005191 break;
5192 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005193 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005194 break;
5195 case glslang::EOpTranspose:
5196 unaryOp = spv::OpTranspose;
5197 break;
5198
5199 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005200 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005201 break;
5202 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005203 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005204 break;
5205 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005206 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005207 break;
5208 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005209 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005210 break;
5211 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005212 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005213 break;
5214 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005215 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005216 break;
5217 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005218 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005219 break;
5220 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005221 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005222 break;
5223
5224 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005225 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005226 break;
5227 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005228 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005229 break;
5230 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005231 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005232 break;
5233 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005234 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005235 break;
5236 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005237 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005238 break;
5239 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005240 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005241 break;
5242
5243 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005244 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005245 break;
5246 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005247 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005248 break;
5249
5250 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005251 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005252 break;
5253 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005254 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005255 break;
5256 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005257 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005258 break;
5259 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005260 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005261 break;
5262 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005263 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005264 break;
5265 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005266 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005267 break;
5268
5269 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005270 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005271 break;
5272 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005273 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005274 break;
5275 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005276 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005277 break;
5278 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005279 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005280 break;
5281 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005282 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005283 break;
5284 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005285 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005286 break;
5287
5288 case glslang::EOpIsNan:
5289 unaryOp = spv::OpIsNan;
5290 break;
5291 case glslang::EOpIsInf:
5292 unaryOp = spv::OpIsInf;
5293 break;
LoopDawg592860c2016-06-09 08:57:35 -06005294 case glslang::EOpIsFinite:
5295 unaryOp = spv::OpIsFinite;
5296 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005297
Rex Xucbc426e2015-12-15 16:03:10 +08005298 case glslang::EOpFloatBitsToInt:
5299 case glslang::EOpFloatBitsToUint:
5300 case glslang::EOpIntBitsToFloat:
5301 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005302 case glslang::EOpDoubleBitsToInt64:
5303 case glslang::EOpDoubleBitsToUint64:
5304 case glslang::EOpInt64BitsToDouble:
5305 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005306 case glslang::EOpFloat16BitsToInt16:
5307 case glslang::EOpFloat16BitsToUint16:
5308 case glslang::EOpInt16BitsToFloat16:
5309 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005310 unaryOp = spv::OpBitcast;
5311 break;
5312
John Kessenich140f3df2015-06-26 16:58:36 -06005313 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005314 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005315 break;
5316 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005317 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005318 break;
5319 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005320 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005321 break;
5322 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005323 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005324 break;
5325 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005326 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005327 break;
5328 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005329 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005330 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005331 case glslang::EOpPackSnorm4x8:
5332 libCall = spv::GLSLstd450PackSnorm4x8;
5333 break;
5334 case glslang::EOpUnpackSnorm4x8:
5335 libCall = spv::GLSLstd450UnpackSnorm4x8;
5336 break;
5337 case glslang::EOpPackUnorm4x8:
5338 libCall = spv::GLSLstd450PackUnorm4x8;
5339 break;
5340 case glslang::EOpUnpackUnorm4x8:
5341 libCall = spv::GLSLstd450UnpackUnorm4x8;
5342 break;
5343 case glslang::EOpPackDouble2x32:
5344 libCall = spv::GLSLstd450PackDouble2x32;
5345 break;
5346 case glslang::EOpUnpackDouble2x32:
5347 libCall = spv::GLSLstd450UnpackDouble2x32;
5348 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005349
Rex Xu8ff43de2016-04-22 16:51:45 +08005350 case glslang::EOpPackInt2x32:
5351 case glslang::EOpUnpackInt2x32:
5352 case glslang::EOpPackUint2x32:
5353 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005354 case glslang::EOpPack16:
5355 case glslang::EOpPack32:
5356 case glslang::EOpPack64:
5357 case glslang::EOpUnpack32:
5358 case glslang::EOpUnpack16:
5359 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005360 case glslang::EOpPackInt2x16:
5361 case glslang::EOpUnpackInt2x16:
5362 case glslang::EOpPackUint2x16:
5363 case glslang::EOpUnpackUint2x16:
5364 case glslang::EOpPackInt4x16:
5365 case glslang::EOpUnpackInt4x16:
5366 case glslang::EOpPackUint4x16:
5367 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005368 case glslang::EOpPackFloat2x16:
5369 case glslang::EOpUnpackFloat2x16:
5370 unaryOp = spv::OpBitcast;
5371 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005372
John Kessenich140f3df2015-06-26 16:58:36 -06005373 case glslang::EOpDPdx:
5374 unaryOp = spv::OpDPdx;
5375 break;
5376 case glslang::EOpDPdy:
5377 unaryOp = spv::OpDPdy;
5378 break;
5379 case glslang::EOpFwidth:
5380 unaryOp = spv::OpFwidth;
5381 break;
5382 case glslang::EOpDPdxFine:
5383 unaryOp = spv::OpDPdxFine;
5384 break;
5385 case glslang::EOpDPdyFine:
5386 unaryOp = spv::OpDPdyFine;
5387 break;
5388 case glslang::EOpFwidthFine:
5389 unaryOp = spv::OpFwidthFine;
5390 break;
5391 case glslang::EOpDPdxCoarse:
5392 unaryOp = spv::OpDPdxCoarse;
5393 break;
5394 case glslang::EOpDPdyCoarse:
5395 unaryOp = spv::OpDPdyCoarse;
5396 break;
5397 case glslang::EOpFwidthCoarse:
5398 unaryOp = spv::OpFwidthCoarse;
5399 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005400 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005401#ifdef AMD_EXTENSIONS
5402 if (typeProxy == glslang::EbtFloat16)
5403 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5404#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005405 libCall = spv::GLSLstd450InterpolateAtCentroid;
5406 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005407 case glslang::EOpAny:
5408 unaryOp = spv::OpAny;
5409 break;
5410 case glslang::EOpAll:
5411 unaryOp = spv::OpAll;
5412 break;
5413
5414 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005415 if (isFloat)
5416 libCall = spv::GLSLstd450FAbs;
5417 else
5418 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005419 break;
5420 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005421 if (isFloat)
5422 libCall = spv::GLSLstd450FSign;
5423 else
5424 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005425 break;
5426
John Kessenichfc51d282015-08-19 13:34:18 -06005427 case glslang::EOpAtomicCounterIncrement:
5428 case glslang::EOpAtomicCounterDecrement:
5429 case glslang::EOpAtomicCounter:
5430 {
5431 // Handle all of the atomics in one place, in createAtomicOperation()
5432 std::vector<spv::Id> operands;
5433 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005434 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005435 }
5436
John Kessenichfc51d282015-08-19 13:34:18 -06005437 case glslang::EOpBitFieldReverse:
5438 unaryOp = spv::OpBitReverse;
5439 break;
5440 case glslang::EOpBitCount:
5441 unaryOp = spv::OpBitCount;
5442 break;
5443 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005444 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005445 break;
5446 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005447 if (isUnsigned)
5448 libCall = spv::GLSLstd450FindUMsb;
5449 else
5450 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005451 break;
5452
Rex Xu574ab042016-04-14 16:53:07 +08005453 case glslang::EOpBallot:
5454 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005455 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005456 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005457 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005458#ifdef AMD_EXTENSIONS
5459 case glslang::EOpMinInvocations:
5460 case glslang::EOpMaxInvocations:
5461 case glslang::EOpAddInvocations:
5462 case glslang::EOpMinInvocationsNonUniform:
5463 case glslang::EOpMaxInvocationsNonUniform:
5464 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005465 case glslang::EOpMinInvocationsInclusiveScan:
5466 case glslang::EOpMaxInvocationsInclusiveScan:
5467 case glslang::EOpAddInvocationsInclusiveScan:
5468 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5469 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5470 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5471 case glslang::EOpMinInvocationsExclusiveScan:
5472 case glslang::EOpMaxInvocationsExclusiveScan:
5473 case glslang::EOpAddInvocationsExclusiveScan:
5474 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5475 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5476 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005477#endif
Rex Xu51596642016-09-21 18:56:12 +08005478 {
5479 std::vector<spv::Id> operands;
5480 operands.push_back(operand);
5481 return createInvocationsOperation(op, typeId, operands, typeProxy);
5482 }
John Kessenich66011cb2018-03-06 16:12:04 -07005483 case glslang::EOpSubgroupAll:
5484 case glslang::EOpSubgroupAny:
5485 case glslang::EOpSubgroupAllEqual:
5486 case glslang::EOpSubgroupBroadcastFirst:
5487 case glslang::EOpSubgroupBallot:
5488 case glslang::EOpSubgroupInverseBallot:
5489 case glslang::EOpSubgroupBallotBitCount:
5490 case glslang::EOpSubgroupBallotInclusiveBitCount:
5491 case glslang::EOpSubgroupBallotExclusiveBitCount:
5492 case glslang::EOpSubgroupBallotFindLSB:
5493 case glslang::EOpSubgroupBallotFindMSB:
5494 case glslang::EOpSubgroupAdd:
5495 case glslang::EOpSubgroupMul:
5496 case glslang::EOpSubgroupMin:
5497 case glslang::EOpSubgroupMax:
5498 case glslang::EOpSubgroupAnd:
5499 case glslang::EOpSubgroupOr:
5500 case glslang::EOpSubgroupXor:
5501 case glslang::EOpSubgroupInclusiveAdd:
5502 case glslang::EOpSubgroupInclusiveMul:
5503 case glslang::EOpSubgroupInclusiveMin:
5504 case glslang::EOpSubgroupInclusiveMax:
5505 case glslang::EOpSubgroupInclusiveAnd:
5506 case glslang::EOpSubgroupInclusiveOr:
5507 case glslang::EOpSubgroupInclusiveXor:
5508 case glslang::EOpSubgroupExclusiveAdd:
5509 case glslang::EOpSubgroupExclusiveMul:
5510 case glslang::EOpSubgroupExclusiveMin:
5511 case glslang::EOpSubgroupExclusiveMax:
5512 case glslang::EOpSubgroupExclusiveAnd:
5513 case glslang::EOpSubgroupExclusiveOr:
5514 case glslang::EOpSubgroupExclusiveXor:
5515 case glslang::EOpSubgroupQuadSwapHorizontal:
5516 case glslang::EOpSubgroupQuadSwapVertical:
5517 case glslang::EOpSubgroupQuadSwapDiagonal: {
5518 std::vector<spv::Id> operands;
5519 operands.push_back(operand);
5520 return createSubgroupOperation(op, typeId, operands, typeProxy);
5521 }
Rex Xu9d93a232016-05-05 12:30:44 +08005522#ifdef AMD_EXTENSIONS
5523 case glslang::EOpMbcnt:
5524 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5525 libCall = spv::MbcntAMD;
5526 break;
5527
5528 case glslang::EOpCubeFaceIndex:
5529 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5530 libCall = spv::CubeFaceIndexAMD;
5531 break;
5532
5533 case glslang::EOpCubeFaceCoord:
5534 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5535 libCall = spv::CubeFaceCoordAMD;
5536 break;
5537#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005538#ifdef NV_EXTENSIONS
5539 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005540 unaryOp = spv::OpGroupNonUniformPartitionNV;
5541 break;
5542#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005543 case glslang::EOpConstructReference:
5544 unaryOp = spv::OpBitcast;
5545 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005546 default:
5547 return 0;
5548 }
5549
5550 spv::Id id;
5551 if (libCall >= 0) {
5552 std::vector<spv::Id> args;
5553 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005554 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005555 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005556 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005557 }
John Kessenich140f3df2015-06-26 16:58:36 -06005558
John Kessenichead86222018-03-28 18:01:20 -06005559 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005560 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005561 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005562}
5563
John Kessenich7a53f762016-01-20 11:19:27 -07005564// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005565spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5566 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005567{
5568 // Handle unary operations vector by vector.
5569 // The result type is the same type as the original type.
5570 // The algorithm is to:
5571 // - break the matrix into vectors
5572 // - apply the operation to each vector
5573 // - make a matrix out the vector results
5574
5575 // get the types sorted out
5576 int numCols = builder.getNumColumns(operand);
5577 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005578 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5579 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005580 std::vector<spv::Id> results;
5581
5582 // do each vector op
5583 for (int c = 0; c < numCols; ++c) {
5584 std::vector<unsigned int> indexes;
5585 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005586 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5587 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005588 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005589 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005590 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005591 }
5592
5593 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005594 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005595 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005596 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005597}
5598
John Kessenichad7645f2018-06-04 19:11:25 -06005599// For converting integers where both the bitwidth and the signedness could
5600// change, but only do the width change here. The caller is still responsible
5601// for the signedness conversion.
5602spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005603{
John Kessenichad7645f2018-06-04 19:11:25 -06005604 // Get the result type width, based on the type to convert to.
5605 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005606 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005607 case glslang::EOpConvInt16ToUint8:
5608 case glslang::EOpConvIntToUint8:
5609 case glslang::EOpConvInt64ToUint8:
5610 case glslang::EOpConvUint16ToInt8:
5611 case glslang::EOpConvUintToInt8:
5612 case glslang::EOpConvUint64ToInt8:
5613 width = 8;
5614 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005615 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005616 case glslang::EOpConvIntToUint16:
5617 case glslang::EOpConvInt64ToUint16:
5618 case glslang::EOpConvUint8ToInt16:
5619 case glslang::EOpConvUintToInt16:
5620 case glslang::EOpConvUint64ToInt16:
5621 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005622 break;
5623 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005624 case glslang::EOpConvInt16ToUint:
5625 case glslang::EOpConvInt64ToUint:
5626 case glslang::EOpConvUint8ToInt:
5627 case glslang::EOpConvUint16ToInt:
5628 case glslang::EOpConvUint64ToInt:
5629 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005630 break;
5631 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005632 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005633 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005634 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005635 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005636 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005637 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005638 break;
5639
5640 default:
5641 assert(false && "Default missing");
5642 break;
5643 }
5644
John Kessenichad7645f2018-06-04 19:11:25 -06005645 // Get the conversion operation and result type,
5646 // based on the target width, but the source type.
5647 spv::Id type = spv::NoType;
5648 spv::Op convOp = spv::OpNop;
5649 switch(op) {
5650 case glslang::EOpConvInt8ToUint16:
5651 case glslang::EOpConvInt8ToUint:
5652 case glslang::EOpConvInt8ToUint64:
5653 case glslang::EOpConvInt16ToUint8:
5654 case glslang::EOpConvInt16ToUint:
5655 case glslang::EOpConvInt16ToUint64:
5656 case glslang::EOpConvIntToUint8:
5657 case glslang::EOpConvIntToUint16:
5658 case glslang::EOpConvIntToUint64:
5659 case glslang::EOpConvInt64ToUint8:
5660 case glslang::EOpConvInt64ToUint16:
5661 case glslang::EOpConvInt64ToUint:
5662 convOp = spv::OpSConvert;
5663 type = builder.makeIntType(width);
5664 break;
5665 default:
5666 convOp = spv::OpUConvert;
5667 type = builder.makeUintType(width);
5668 break;
5669 }
5670
John Kessenich66011cb2018-03-06 16:12:04 -07005671 if (vectorSize > 0)
5672 type = builder.makeVectorType(type, vectorSize);
5673
John Kessenichad7645f2018-06-04 19:11:25 -06005674 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005675}
5676
John Kessenichead86222018-03-28 18:01:20 -06005677spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5678 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005679{
5680 spv::Op convOp = spv::OpNop;
5681 spv::Id zero = 0;
5682 spv::Id one = 0;
5683
5684 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5685
5686 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005687 case glslang::EOpConvInt8ToBool:
5688 case glslang::EOpConvUint8ToBool:
5689 zero = builder.makeUint8Constant(0);
5690 zero = makeSmearedConstant(zero, vectorSize);
5691 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005692 case glslang::EOpConvInt16ToBool:
5693 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005694 zero = builder.makeUint16Constant(0);
5695 zero = makeSmearedConstant(zero, vectorSize);
5696 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5697 case glslang::EOpConvIntToBool:
5698 case glslang::EOpConvUintToBool:
5699 zero = builder.makeUintConstant(0);
5700 zero = makeSmearedConstant(zero, vectorSize);
5701 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5702 case glslang::EOpConvInt64ToBool:
5703 case glslang::EOpConvUint64ToBool:
5704 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005705 zero = makeSmearedConstant(zero, vectorSize);
5706 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5707
5708 case glslang::EOpConvFloatToBool:
5709 zero = builder.makeFloatConstant(0.0F);
5710 zero = makeSmearedConstant(zero, vectorSize);
5711 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5712
5713 case glslang::EOpConvDoubleToBool:
5714 zero = builder.makeDoubleConstant(0.0);
5715 zero = makeSmearedConstant(zero, vectorSize);
5716 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5717
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005718 case glslang::EOpConvFloat16ToBool:
5719 zero = builder.makeFloat16Constant(0.0F);
5720 zero = makeSmearedConstant(zero, vectorSize);
5721 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005722
John Kessenich140f3df2015-06-26 16:58:36 -06005723 case glslang::EOpConvBoolToFloat:
5724 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005725 zero = builder.makeFloatConstant(0.0F);
5726 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005727 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005728
John Kessenich140f3df2015-06-26 16:58:36 -06005729 case glslang::EOpConvBoolToDouble:
5730 convOp = spv::OpSelect;
5731 zero = builder.makeDoubleConstant(0.0);
5732 one = builder.makeDoubleConstant(1.0);
5733 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005734
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005735 case glslang::EOpConvBoolToFloat16:
5736 convOp = spv::OpSelect;
5737 zero = builder.makeFloat16Constant(0.0F);
5738 one = builder.makeFloat16Constant(1.0F);
5739 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005740
5741 case glslang::EOpConvBoolToInt8:
5742 zero = builder.makeInt8Constant(0);
5743 one = builder.makeInt8Constant(1);
5744 convOp = spv::OpSelect;
5745 break;
5746
5747 case glslang::EOpConvBoolToUint8:
5748 zero = builder.makeUint8Constant(0);
5749 one = builder.makeUint8Constant(1);
5750 convOp = spv::OpSelect;
5751 break;
5752
5753 case glslang::EOpConvBoolToInt16:
5754 zero = builder.makeInt16Constant(0);
5755 one = builder.makeInt16Constant(1);
5756 convOp = spv::OpSelect;
5757 break;
5758
5759 case glslang::EOpConvBoolToUint16:
5760 zero = builder.makeUint16Constant(0);
5761 one = builder.makeUint16Constant(1);
5762 convOp = spv::OpSelect;
5763 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005764
John Kessenich140f3df2015-06-26 16:58:36 -06005765 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005766 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005767 if (op == glslang::EOpConvBoolToInt64)
5768 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005769 else
5770 zero = builder.makeIntConstant(0);
5771
5772 if (op == glslang::EOpConvBoolToInt64)
5773 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005774 else
5775 one = builder.makeIntConstant(1);
5776
John Kessenich140f3df2015-06-26 16:58:36 -06005777 convOp = spv::OpSelect;
5778 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005779
John Kessenich140f3df2015-06-26 16:58:36 -06005780 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005781 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005782 if (op == glslang::EOpConvBoolToUint64)
5783 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005784 else
5785 zero = builder.makeUintConstant(0);
5786
5787 if (op == glslang::EOpConvBoolToUint64)
5788 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005789 else
5790 one = builder.makeUintConstant(1);
5791
John Kessenich140f3df2015-06-26 16:58:36 -06005792 convOp = spv::OpSelect;
5793 break;
5794
John Kessenich66011cb2018-03-06 16:12:04 -07005795 case glslang::EOpConvInt8ToFloat16:
5796 case glslang::EOpConvInt8ToFloat:
5797 case glslang::EOpConvInt8ToDouble:
5798 case glslang::EOpConvInt16ToFloat16:
5799 case glslang::EOpConvInt16ToFloat:
5800 case glslang::EOpConvInt16ToDouble:
5801 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005802 case glslang::EOpConvIntToFloat:
5803 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005804 case glslang::EOpConvInt64ToFloat:
5805 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005806 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005807 convOp = spv::OpConvertSToF;
5808 break;
5809
John Kessenich66011cb2018-03-06 16:12:04 -07005810 case glslang::EOpConvUint8ToFloat16:
5811 case glslang::EOpConvUint8ToFloat:
5812 case glslang::EOpConvUint8ToDouble:
5813 case glslang::EOpConvUint16ToFloat16:
5814 case glslang::EOpConvUint16ToFloat:
5815 case glslang::EOpConvUint16ToDouble:
5816 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005817 case glslang::EOpConvUintToFloat:
5818 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005819 case glslang::EOpConvUint64ToFloat:
5820 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005821 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005822 convOp = spv::OpConvertUToF;
5823 break;
5824
5825 case glslang::EOpConvDoubleToFloat:
5826 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005827 case glslang::EOpConvDoubleToFloat16:
5828 case glslang::EOpConvFloat16ToDouble:
5829 case glslang::EOpConvFloatToFloat16:
5830 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005831 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005832 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005833 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005834 break;
5835
John Kessenich66011cb2018-03-06 16:12:04 -07005836 case glslang::EOpConvFloat16ToInt8:
5837 case glslang::EOpConvFloatToInt8:
5838 case glslang::EOpConvDoubleToInt8:
5839 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005840 case glslang::EOpConvFloatToInt16:
5841 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005842 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005843 case glslang::EOpConvFloatToInt:
5844 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005845 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005846 case glslang::EOpConvFloatToInt64:
5847 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005848 convOp = spv::OpConvertFToS;
5849 break;
5850
John Kessenich66011cb2018-03-06 16:12:04 -07005851 case glslang::EOpConvUint8ToInt8:
5852 case glslang::EOpConvInt8ToUint8:
5853 case glslang::EOpConvUint16ToInt16:
5854 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005855 case glslang::EOpConvUintToInt:
5856 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005857 case glslang::EOpConvUint64ToInt64:
5858 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005859 if (builder.isInSpecConstCodeGenMode()) {
5860 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005861 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5862 zero = builder.makeUint8Constant(0);
5863 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005864 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005865 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5866 zero = builder.makeUint64Constant(0);
5867 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005868 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005869 }
qining189b2032016-04-12 23:16:20 -04005870 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005871 // Use OpIAdd, instead of OpBitcast to do the conversion when
5872 // generating for OpSpecConstantOp instruction.
5873 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5874 }
5875 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005876 convOp = spv::OpBitcast;
5877 break;
5878
John Kessenich66011cb2018-03-06 16:12:04 -07005879 case glslang::EOpConvFloat16ToUint8:
5880 case glslang::EOpConvFloatToUint8:
5881 case glslang::EOpConvDoubleToUint8:
5882 case glslang::EOpConvFloat16ToUint16:
5883 case glslang::EOpConvFloatToUint16:
5884 case glslang::EOpConvDoubleToUint16:
5885 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005886 case glslang::EOpConvFloatToUint:
5887 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005888 case glslang::EOpConvFloatToUint64:
5889 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005890 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005891 convOp = spv::OpConvertFToU;
5892 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005893
John Kessenich66011cb2018-03-06 16:12:04 -07005894 case glslang::EOpConvInt8ToInt16:
5895 case glslang::EOpConvInt8ToInt:
5896 case glslang::EOpConvInt8ToInt64:
5897 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005898 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005899 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005900 case glslang::EOpConvIntToInt8:
5901 case glslang::EOpConvIntToInt16:
5902 case glslang::EOpConvIntToInt64:
5903 case glslang::EOpConvInt64ToInt8:
5904 case glslang::EOpConvInt64ToInt16:
5905 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005906 convOp = spv::OpSConvert;
5907 break;
5908
John Kessenich66011cb2018-03-06 16:12:04 -07005909 case glslang::EOpConvUint8ToUint16:
5910 case glslang::EOpConvUint8ToUint:
5911 case glslang::EOpConvUint8ToUint64:
5912 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005913 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005914 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005915 case glslang::EOpConvUintToUint8:
5916 case glslang::EOpConvUintToUint16:
5917 case glslang::EOpConvUintToUint64:
5918 case glslang::EOpConvUint64ToUint8:
5919 case glslang::EOpConvUint64ToUint16:
5920 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005921 convOp = spv::OpUConvert;
5922 break;
5923
John Kessenich66011cb2018-03-06 16:12:04 -07005924 case glslang::EOpConvInt8ToUint16:
5925 case glslang::EOpConvInt8ToUint:
5926 case glslang::EOpConvInt8ToUint64:
5927 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005928 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005929 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005930 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005931 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005932 case glslang::EOpConvIntToUint64:
5933 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005934 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005935 case glslang::EOpConvInt64ToUint:
5936 case glslang::EOpConvUint8ToInt16:
5937 case glslang::EOpConvUint8ToInt:
5938 case glslang::EOpConvUint8ToInt64:
5939 case glslang::EOpConvUint16ToInt8:
5940 case glslang::EOpConvUint16ToInt:
5941 case glslang::EOpConvUint16ToInt64:
5942 case glslang::EOpConvUintToInt8:
5943 case glslang::EOpConvUintToInt16:
5944 case glslang::EOpConvUintToInt64:
5945 case glslang::EOpConvUint64ToInt8:
5946 case glslang::EOpConvUint64ToInt16:
5947 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005948 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005949 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005950
5951 if (builder.isInSpecConstCodeGenMode()) {
5952 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005953 switch(op) {
5954 case glslang::EOpConvInt16ToUint8:
5955 case glslang::EOpConvIntToUint8:
5956 case glslang::EOpConvInt64ToUint8:
5957 case glslang::EOpConvUint16ToInt8:
5958 case glslang::EOpConvUintToInt8:
5959 case glslang::EOpConvUint64ToInt8:
5960 zero = builder.makeUint8Constant(0);
5961 break;
5962 case glslang::EOpConvInt8ToUint16:
5963 case glslang::EOpConvIntToUint16:
5964 case glslang::EOpConvInt64ToUint16:
5965 case glslang::EOpConvUint8ToInt16:
5966 case glslang::EOpConvUintToInt16:
5967 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005968 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005969 break;
5970 case glslang::EOpConvInt8ToUint:
5971 case glslang::EOpConvInt16ToUint:
5972 case glslang::EOpConvInt64ToUint:
5973 case glslang::EOpConvUint8ToInt:
5974 case glslang::EOpConvUint16ToInt:
5975 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005976 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005977 break;
5978 case glslang::EOpConvInt8ToUint64:
5979 case glslang::EOpConvInt16ToUint64:
5980 case glslang::EOpConvIntToUint64:
5981 case glslang::EOpConvUint8ToInt64:
5982 case glslang::EOpConvUint16ToInt64:
5983 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005984 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005985 break;
5986 default:
5987 assert(false && "Default missing");
5988 break;
5989 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005990 zero = makeSmearedConstant(zero, vectorSize);
5991 // Use OpIAdd, instead of OpBitcast to do the conversion when
5992 // generating for OpSpecConstantOp instruction.
5993 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5994 }
5995 // For normal run-time conversion instruction, use OpBitcast.
5996 convOp = spv::OpBitcast;
5997 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005998 case glslang::EOpConvUint64ToPtr:
5999 convOp = spv::OpConvertUToPtr;
6000 break;
6001 case glslang::EOpConvPtrToUint64:
6002 convOp = spv::OpConvertPtrToU;
6003 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006004 default:
6005 break;
6006 }
6007
6008 spv::Id result = 0;
6009 if (convOp == spv::OpNop)
6010 return result;
6011
6012 if (convOp == spv::OpSelect) {
6013 zero = makeSmearedConstant(zero, vectorSize);
6014 one = makeSmearedConstant(one, vectorSize);
6015 result = builder.createTriOp(convOp, destType, operand, one, zero);
6016 } else
6017 result = builder.createUnaryOp(convOp, destType, operand);
6018
John Kessenichead86222018-03-28 18:01:20 -06006019 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006020 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006021 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006022}
6023
6024spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6025{
6026 if (vectorSize == 0)
6027 return constant;
6028
6029 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6030 std::vector<spv::Id> components;
6031 for (int c = 0; c < vectorSize; ++c)
6032 components.push_back(constant);
6033 return builder.makeCompositeConstant(vectorTypeId, components);
6034}
6035
John Kessenich426394d2015-07-23 10:22:48 -06006036// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07006037spv::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 -06006038{
6039 spv::Op opCode = spv::OpNop;
6040
6041 switch (op) {
6042 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006043 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006044 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006045 opCode = spv::OpAtomicIAdd;
6046 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006047 case glslang::EOpAtomicCounterSubtract:
6048 opCode = spv::OpAtomicISub;
6049 break;
John Kessenich426394d2015-07-23 10:22:48 -06006050 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006051 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006052 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006053 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006054 break;
6055 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006056 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006057 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006058 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006059 break;
6060 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006061 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006062 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006063 opCode = spv::OpAtomicAnd;
6064 break;
6065 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006066 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006067 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006068 opCode = spv::OpAtomicOr;
6069 break;
6070 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006071 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006072 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006073 opCode = spv::OpAtomicXor;
6074 break;
6075 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006076 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006077 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006078 opCode = spv::OpAtomicExchange;
6079 break;
6080 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006081 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006082 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006083 opCode = spv::OpAtomicCompareExchange;
6084 break;
6085 case glslang::EOpAtomicCounterIncrement:
6086 opCode = spv::OpAtomicIIncrement;
6087 break;
6088 case glslang::EOpAtomicCounterDecrement:
6089 opCode = spv::OpAtomicIDecrement;
6090 break;
6091 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006092 case glslang::EOpImageAtomicLoad:
6093 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006094 opCode = spv::OpAtomicLoad;
6095 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006096 case glslang::EOpAtomicStore:
6097 case glslang::EOpImageAtomicStore:
6098 opCode = spv::OpAtomicStore;
6099 break;
John Kessenich426394d2015-07-23 10:22:48 -06006100 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006101 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006102 break;
6103 }
6104
Rex Xue8fe8b02017-09-26 15:42:56 +08006105 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6106 builder.addCapability(spv::CapabilityInt64Atomics);
6107
John Kessenich426394d2015-07-23 10:22:48 -06006108 // Sort out the operands
6109 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006110 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006111 // - compare-exchange swaps the value and comparator
6112 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006113 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006114 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6115 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6116 spv::Id scopeId;
6117 if (glslangIntermediate->usingVulkanMemoryModel()) {
6118 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6119 } else {
6120 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6121 }
6122 // semantics default to relaxed
6123 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
6124 spv::Id semanticsId2 = semanticsId;
6125
6126 pointerId = operands[0];
6127 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6128 // no additional operands
6129 } else if (opCode == spv::OpAtomicCompareExchange) {
6130 compareId = operands[1];
6131 valueId = operands[2];
6132 if (operands.size() > 3) {
6133 scopeId = operands[3];
6134 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6135 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6136 }
6137 } else if (opCode == spv::OpAtomicLoad) {
6138 if (operands.size() > 1) {
6139 scopeId = operands[1];
6140 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6141 }
6142 } else {
6143 // atomic store or RMW
6144 valueId = operands[1];
6145 if (operands.size() > 2) {
6146 scopeId = operands[2];
6147 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6148 }
Rex Xu04db3f52015-09-16 11:44:02 +08006149 }
John Kessenich426394d2015-07-23 10:22:48 -06006150
Jeff Bolz36831c92018-09-05 10:11:41 -05006151 // Check for capabilities
6152 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
6153 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6154 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6155 }
John Kessenich426394d2015-07-23 10:22:48 -06006156
Jeff Bolz36831c92018-09-05 10:11:41 -05006157 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6158 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6159 }
John Kessenich48d6e792017-10-06 21:21:48 -06006160
Jeff Bolz36831c92018-09-05 10:11:41 -05006161 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6162 spvAtomicOperands.push_back(pointerId);
6163 spvAtomicOperands.push_back(scopeId);
6164 spvAtomicOperands.push_back(semanticsId);
6165 if (opCode == spv::OpAtomicCompareExchange) {
6166 spvAtomicOperands.push_back(semanticsId2);
6167 spvAtomicOperands.push_back(valueId);
6168 spvAtomicOperands.push_back(compareId);
6169 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6170 spvAtomicOperands.push_back(valueId);
6171 }
John Kessenich48d6e792017-10-06 21:21:48 -06006172
Jeff Bolz36831c92018-09-05 10:11:41 -05006173 if (opCode == spv::OpAtomicStore) {
6174 builder.createNoResultOp(opCode, spvAtomicOperands);
6175 return 0;
6176 } else {
6177 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6178
6179 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6180 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6181 if (op == glslang::EOpAtomicCounterDecrement)
6182 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6183
6184 return resultId;
6185 }
John Kessenich426394d2015-07-23 10:22:48 -06006186}
6187
John Kessenich91cef522016-05-05 16:45:40 -06006188// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006189spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006190{
Corentin Walleze7061422018-08-08 15:20:15 +02006191#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006192 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6193 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006194#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006195
Rex Xu51596642016-09-21 18:56:12 +08006196 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006197 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006198 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6199
chaocf200da82016-12-20 12:44:35 -08006200 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6201 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006202 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6203 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006204 } else if (op == glslang::EOpAnyInvocation ||
6205 op == glslang::EOpAllInvocations ||
6206 op == glslang::EOpAllInvocationsEqual) {
6207 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6208 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006209 } else {
6210 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006211#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006212 if (op == glslang::EOpMinInvocationsNonUniform ||
6213 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006214 op == glslang::EOpAddInvocationsNonUniform ||
6215 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6216 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6217 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6218 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6219 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6220 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006221 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006222#endif
Rex Xu51596642016-09-21 18:56:12 +08006223
Rex Xu9d93a232016-05-05 12:30:44 +08006224#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006225 switch (op) {
6226 case glslang::EOpMinInvocations:
6227 case glslang::EOpMaxInvocations:
6228 case glslang::EOpAddInvocations:
6229 case glslang::EOpMinInvocationsNonUniform:
6230 case glslang::EOpMaxInvocationsNonUniform:
6231 case glslang::EOpAddInvocationsNonUniform:
6232 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006233 break;
6234 case glslang::EOpMinInvocationsInclusiveScan:
6235 case glslang::EOpMaxInvocationsInclusiveScan:
6236 case glslang::EOpAddInvocationsInclusiveScan:
6237 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6238 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6239 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6240 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006241 break;
6242 case glslang::EOpMinInvocationsExclusiveScan:
6243 case glslang::EOpMaxInvocationsExclusiveScan:
6244 case glslang::EOpAddInvocationsExclusiveScan:
6245 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6246 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6247 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6248 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006249 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006250 default:
6251 break;
Rex Xu430ef402016-10-14 17:22:23 +08006252 }
John Kessenich149afc32018-08-14 13:31:43 -06006253 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6254 spvGroupOperands.push_back(scope);
6255 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006256 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006257 spvGroupOperands.push_back(groupOp);
6258 }
Rex Xu9d93a232016-05-05 12:30:44 +08006259#endif
Rex Xu51596642016-09-21 18:56:12 +08006260 }
6261
John Kessenich149afc32018-08-14 13:31:43 -06006262 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6263 spv::IdImmediate op = { true, *opIt };
6264 spvGroupOperands.push_back(op);
6265 }
John Kessenich91cef522016-05-05 16:45:40 -06006266
6267 switch (op) {
6268 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006269 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006270 break;
John Kessenich91cef522016-05-05 16:45:40 -06006271 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006272 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006273 break;
John Kessenich91cef522016-05-05 16:45:40 -06006274 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006275 opCode = spv::OpSubgroupAllEqualKHR;
6276 break;
Rex Xu51596642016-09-21 18:56:12 +08006277 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006278 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006279 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006280 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006281 break;
6282 case glslang::EOpReadFirstInvocation:
6283 opCode = spv::OpSubgroupFirstInvocationKHR;
6284 break;
6285 case glslang::EOpBallot:
6286 {
6287 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6288 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6289 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6290 //
6291 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6292 //
6293 spv::Id uintType = builder.makeUintType(32);
6294 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6295 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6296
6297 std::vector<spv::Id> components;
6298 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6299 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6300
6301 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6302 return builder.createUnaryOp(spv::OpBitcast, typeId,
6303 builder.createCompositeConstruct(uvec2Type, components));
6304 }
6305
Rex Xu9d93a232016-05-05 12:30:44 +08006306#ifdef AMD_EXTENSIONS
6307 case glslang::EOpMinInvocations:
6308 case glslang::EOpMaxInvocations:
6309 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006310 case glslang::EOpMinInvocationsInclusiveScan:
6311 case glslang::EOpMaxInvocationsInclusiveScan:
6312 case glslang::EOpAddInvocationsInclusiveScan:
6313 case glslang::EOpMinInvocationsExclusiveScan:
6314 case glslang::EOpMaxInvocationsExclusiveScan:
6315 case glslang::EOpAddInvocationsExclusiveScan:
6316 if (op == glslang::EOpMinInvocations ||
6317 op == glslang::EOpMinInvocationsInclusiveScan ||
6318 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006319 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006320 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006321 else {
6322 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006323 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006324 else
Rex Xu51596642016-09-21 18:56:12 +08006325 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006326 }
Rex Xu430ef402016-10-14 17:22:23 +08006327 } else if (op == glslang::EOpMaxInvocations ||
6328 op == glslang::EOpMaxInvocationsInclusiveScan ||
6329 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006330 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006331 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006332 else {
6333 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006334 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006335 else
Rex Xu51596642016-09-21 18:56:12 +08006336 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006337 }
6338 } else {
6339 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006340 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006341 else
Rex Xu51596642016-09-21 18:56:12 +08006342 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006343 }
6344
Rex Xu2bbbe062016-08-23 15:41:05 +08006345 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006346 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006347
6348 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006349 case glslang::EOpMinInvocationsNonUniform:
6350 case glslang::EOpMaxInvocationsNonUniform:
6351 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006352 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6353 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6354 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6355 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6356 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6357 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6358 if (op == glslang::EOpMinInvocationsNonUniform ||
6359 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6360 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006361 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006362 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006363 else {
6364 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006365 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006366 else
Rex Xu51596642016-09-21 18:56:12 +08006367 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006368 }
6369 }
Rex Xu430ef402016-10-14 17:22:23 +08006370 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6371 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6372 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006373 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006374 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006375 else {
6376 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006377 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006378 else
Rex Xu51596642016-09-21 18:56:12 +08006379 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006380 }
6381 }
6382 else {
6383 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006384 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006385 else
Rex Xu51596642016-09-21 18:56:12 +08006386 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006387 }
6388
Rex Xu2bbbe062016-08-23 15:41:05 +08006389 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006390 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006391
6392 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006393#endif
John Kessenich91cef522016-05-05 16:45:40 -06006394 default:
6395 logger->missingFunctionality("invocation operation");
6396 return spv::NoResult;
6397 }
Rex Xu51596642016-09-21 18:56:12 +08006398
6399 assert(opCode != spv::OpNop);
6400 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006401}
6402
Rex Xu2bbbe062016-08-23 15:41:05 +08006403// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006404spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6405 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006406{
Rex Xub7072052016-09-26 15:53:40 +08006407#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006408 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6409 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006410 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006411 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006412 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6413 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6414 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006415#else
6416 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6417 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006418 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6419 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006420#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006421
6422 // Handle group invocation operations scalar by scalar.
6423 // The result type is the same type as the original type.
6424 // The algorithm is to:
6425 // - break the vector into scalars
6426 // - apply the operation to each scalar
6427 // - make a vector out the scalar results
6428
6429 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006430 int numComponents = builder.getNumComponents(operands[0]);
6431 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006432 std::vector<spv::Id> results;
6433
6434 // do each scalar op
6435 for (int comp = 0; comp < numComponents; ++comp) {
6436 std::vector<unsigned int> indexes;
6437 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006438 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6439 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006440 if (op == spv::OpSubgroupReadInvocationKHR) {
6441 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006442 spv::IdImmediate operand = { true, operands[1] };
6443 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006444 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006445 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6446 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006447 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006448 spv::IdImmediate operand = { true, operands[1] };
6449 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006450 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006451 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6452 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006453 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006454 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006455 spvGroupOperands.push_back(scalar);
6456 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006457
Rex Xub7072052016-09-26 15:53:40 +08006458 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006459 }
6460
6461 // put the pieces together
6462 return builder.createCompositeConstruct(typeId, results);
6463}
Rex Xu2bbbe062016-08-23 15:41:05 +08006464
John Kessenich66011cb2018-03-06 16:12:04 -07006465// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006466spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6467 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006468{
6469 // Add the required capabilities.
6470 switch (op) {
6471 case glslang::EOpSubgroupElect:
6472 builder.addCapability(spv::CapabilityGroupNonUniform);
6473 break;
6474 case glslang::EOpSubgroupAll:
6475 case glslang::EOpSubgroupAny:
6476 case glslang::EOpSubgroupAllEqual:
6477 builder.addCapability(spv::CapabilityGroupNonUniform);
6478 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6479 break;
6480 case glslang::EOpSubgroupBroadcast:
6481 case glslang::EOpSubgroupBroadcastFirst:
6482 case glslang::EOpSubgroupBallot:
6483 case glslang::EOpSubgroupInverseBallot:
6484 case glslang::EOpSubgroupBallotBitExtract:
6485 case glslang::EOpSubgroupBallotBitCount:
6486 case glslang::EOpSubgroupBallotInclusiveBitCount:
6487 case glslang::EOpSubgroupBallotExclusiveBitCount:
6488 case glslang::EOpSubgroupBallotFindLSB:
6489 case glslang::EOpSubgroupBallotFindMSB:
6490 builder.addCapability(spv::CapabilityGroupNonUniform);
6491 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6492 break;
6493 case glslang::EOpSubgroupShuffle:
6494 case glslang::EOpSubgroupShuffleXor:
6495 builder.addCapability(spv::CapabilityGroupNonUniform);
6496 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6497 break;
6498 case glslang::EOpSubgroupShuffleUp:
6499 case glslang::EOpSubgroupShuffleDown:
6500 builder.addCapability(spv::CapabilityGroupNonUniform);
6501 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6502 break;
6503 case glslang::EOpSubgroupAdd:
6504 case glslang::EOpSubgroupMul:
6505 case glslang::EOpSubgroupMin:
6506 case glslang::EOpSubgroupMax:
6507 case glslang::EOpSubgroupAnd:
6508 case glslang::EOpSubgroupOr:
6509 case glslang::EOpSubgroupXor:
6510 case glslang::EOpSubgroupInclusiveAdd:
6511 case glslang::EOpSubgroupInclusiveMul:
6512 case glslang::EOpSubgroupInclusiveMin:
6513 case glslang::EOpSubgroupInclusiveMax:
6514 case glslang::EOpSubgroupInclusiveAnd:
6515 case glslang::EOpSubgroupInclusiveOr:
6516 case glslang::EOpSubgroupInclusiveXor:
6517 case glslang::EOpSubgroupExclusiveAdd:
6518 case glslang::EOpSubgroupExclusiveMul:
6519 case glslang::EOpSubgroupExclusiveMin:
6520 case glslang::EOpSubgroupExclusiveMax:
6521 case glslang::EOpSubgroupExclusiveAnd:
6522 case glslang::EOpSubgroupExclusiveOr:
6523 case glslang::EOpSubgroupExclusiveXor:
6524 builder.addCapability(spv::CapabilityGroupNonUniform);
6525 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6526 break;
6527 case glslang::EOpSubgroupClusteredAdd:
6528 case glslang::EOpSubgroupClusteredMul:
6529 case glslang::EOpSubgroupClusteredMin:
6530 case glslang::EOpSubgroupClusteredMax:
6531 case glslang::EOpSubgroupClusteredAnd:
6532 case glslang::EOpSubgroupClusteredOr:
6533 case glslang::EOpSubgroupClusteredXor:
6534 builder.addCapability(spv::CapabilityGroupNonUniform);
6535 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6536 break;
6537 case glslang::EOpSubgroupQuadBroadcast:
6538 case glslang::EOpSubgroupQuadSwapHorizontal:
6539 case glslang::EOpSubgroupQuadSwapVertical:
6540 case glslang::EOpSubgroupQuadSwapDiagonal:
6541 builder.addCapability(spv::CapabilityGroupNonUniform);
6542 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6543 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006544#ifdef NV_EXTENSIONS
6545 case glslang::EOpSubgroupPartitionedAdd:
6546 case glslang::EOpSubgroupPartitionedMul:
6547 case glslang::EOpSubgroupPartitionedMin:
6548 case glslang::EOpSubgroupPartitionedMax:
6549 case glslang::EOpSubgroupPartitionedAnd:
6550 case glslang::EOpSubgroupPartitionedOr:
6551 case glslang::EOpSubgroupPartitionedXor:
6552 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6553 case glslang::EOpSubgroupPartitionedInclusiveMul:
6554 case glslang::EOpSubgroupPartitionedInclusiveMin:
6555 case glslang::EOpSubgroupPartitionedInclusiveMax:
6556 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6557 case glslang::EOpSubgroupPartitionedInclusiveOr:
6558 case glslang::EOpSubgroupPartitionedInclusiveXor:
6559 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6560 case glslang::EOpSubgroupPartitionedExclusiveMul:
6561 case glslang::EOpSubgroupPartitionedExclusiveMin:
6562 case glslang::EOpSubgroupPartitionedExclusiveMax:
6563 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6564 case glslang::EOpSubgroupPartitionedExclusiveOr:
6565 case glslang::EOpSubgroupPartitionedExclusiveXor:
6566 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6567 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6568 break;
6569#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006570 default: assert(0 && "Unhandled subgroup operation!");
6571 }
6572
6573 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6574 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6575 const bool isBool = typeProxy == glslang::EbtBool;
6576
6577 spv::Op opCode = spv::OpNop;
6578
6579 // Figure out which opcode to use.
6580 switch (op) {
6581 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6582 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6583 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6584 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6585 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6586 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6587 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6588 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6589 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6590 case glslang::EOpSubgroupBallotBitCount:
6591 case glslang::EOpSubgroupBallotInclusiveBitCount:
6592 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6593 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6594 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6595 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6596 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6597 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6598 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6599 case glslang::EOpSubgroupAdd:
6600 case glslang::EOpSubgroupInclusiveAdd:
6601 case glslang::EOpSubgroupExclusiveAdd:
6602 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006603#ifdef NV_EXTENSIONS
6604 case glslang::EOpSubgroupPartitionedAdd:
6605 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6606 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6607#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006608 if (isFloat) {
6609 opCode = spv::OpGroupNonUniformFAdd;
6610 } else {
6611 opCode = spv::OpGroupNonUniformIAdd;
6612 }
6613 break;
6614 case glslang::EOpSubgroupMul:
6615 case glslang::EOpSubgroupInclusiveMul:
6616 case glslang::EOpSubgroupExclusiveMul:
6617 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006618#ifdef NV_EXTENSIONS
6619 case glslang::EOpSubgroupPartitionedMul:
6620 case glslang::EOpSubgroupPartitionedInclusiveMul:
6621 case glslang::EOpSubgroupPartitionedExclusiveMul:
6622#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006623 if (isFloat) {
6624 opCode = spv::OpGroupNonUniformFMul;
6625 } else {
6626 opCode = spv::OpGroupNonUniformIMul;
6627 }
6628 break;
6629 case glslang::EOpSubgroupMin:
6630 case glslang::EOpSubgroupInclusiveMin:
6631 case glslang::EOpSubgroupExclusiveMin:
6632 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006633#ifdef NV_EXTENSIONS
6634 case glslang::EOpSubgroupPartitionedMin:
6635 case glslang::EOpSubgroupPartitionedInclusiveMin:
6636 case glslang::EOpSubgroupPartitionedExclusiveMin:
6637#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006638 if (isFloat) {
6639 opCode = spv::OpGroupNonUniformFMin;
6640 } else if (isUnsigned) {
6641 opCode = spv::OpGroupNonUniformUMin;
6642 } else {
6643 opCode = spv::OpGroupNonUniformSMin;
6644 }
6645 break;
6646 case glslang::EOpSubgroupMax:
6647 case glslang::EOpSubgroupInclusiveMax:
6648 case glslang::EOpSubgroupExclusiveMax:
6649 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006650#ifdef NV_EXTENSIONS
6651 case glslang::EOpSubgroupPartitionedMax:
6652 case glslang::EOpSubgroupPartitionedInclusiveMax:
6653 case glslang::EOpSubgroupPartitionedExclusiveMax:
6654#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006655 if (isFloat) {
6656 opCode = spv::OpGroupNonUniformFMax;
6657 } else if (isUnsigned) {
6658 opCode = spv::OpGroupNonUniformUMax;
6659 } else {
6660 opCode = spv::OpGroupNonUniformSMax;
6661 }
6662 break;
6663 case glslang::EOpSubgroupAnd:
6664 case glslang::EOpSubgroupInclusiveAnd:
6665 case glslang::EOpSubgroupExclusiveAnd:
6666 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006667#ifdef NV_EXTENSIONS
6668 case glslang::EOpSubgroupPartitionedAnd:
6669 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6670 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6671#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006672 if (isBool) {
6673 opCode = spv::OpGroupNonUniformLogicalAnd;
6674 } else {
6675 opCode = spv::OpGroupNonUniformBitwiseAnd;
6676 }
6677 break;
6678 case glslang::EOpSubgroupOr:
6679 case glslang::EOpSubgroupInclusiveOr:
6680 case glslang::EOpSubgroupExclusiveOr:
6681 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006682#ifdef NV_EXTENSIONS
6683 case glslang::EOpSubgroupPartitionedOr:
6684 case glslang::EOpSubgroupPartitionedInclusiveOr:
6685 case glslang::EOpSubgroupPartitionedExclusiveOr:
6686#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006687 if (isBool) {
6688 opCode = spv::OpGroupNonUniformLogicalOr;
6689 } else {
6690 opCode = spv::OpGroupNonUniformBitwiseOr;
6691 }
6692 break;
6693 case glslang::EOpSubgroupXor:
6694 case glslang::EOpSubgroupInclusiveXor:
6695 case glslang::EOpSubgroupExclusiveXor:
6696 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006697#ifdef NV_EXTENSIONS
6698 case glslang::EOpSubgroupPartitionedXor:
6699 case glslang::EOpSubgroupPartitionedInclusiveXor:
6700 case glslang::EOpSubgroupPartitionedExclusiveXor:
6701#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006702 if (isBool) {
6703 opCode = spv::OpGroupNonUniformLogicalXor;
6704 } else {
6705 opCode = spv::OpGroupNonUniformBitwiseXor;
6706 }
6707 break;
6708 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6709 case glslang::EOpSubgroupQuadSwapHorizontal:
6710 case glslang::EOpSubgroupQuadSwapVertical:
6711 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6712 default: assert(0 && "Unhandled subgroup operation!");
6713 }
6714
John Kessenich149afc32018-08-14 13:31:43 -06006715 // get the right Group Operation
6716 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006717 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006718 default:
6719 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006720 case glslang::EOpSubgroupBallotBitCount:
6721 case glslang::EOpSubgroupAdd:
6722 case glslang::EOpSubgroupMul:
6723 case glslang::EOpSubgroupMin:
6724 case glslang::EOpSubgroupMax:
6725 case glslang::EOpSubgroupAnd:
6726 case glslang::EOpSubgroupOr:
6727 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006728 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006729 break;
6730 case glslang::EOpSubgroupBallotInclusiveBitCount:
6731 case glslang::EOpSubgroupInclusiveAdd:
6732 case glslang::EOpSubgroupInclusiveMul:
6733 case glslang::EOpSubgroupInclusiveMin:
6734 case glslang::EOpSubgroupInclusiveMax:
6735 case glslang::EOpSubgroupInclusiveAnd:
6736 case glslang::EOpSubgroupInclusiveOr:
6737 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006738 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006739 break;
6740 case glslang::EOpSubgroupBallotExclusiveBitCount:
6741 case glslang::EOpSubgroupExclusiveAdd:
6742 case glslang::EOpSubgroupExclusiveMul:
6743 case glslang::EOpSubgroupExclusiveMin:
6744 case glslang::EOpSubgroupExclusiveMax:
6745 case glslang::EOpSubgroupExclusiveAnd:
6746 case glslang::EOpSubgroupExclusiveOr:
6747 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006748 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006749 break;
6750 case glslang::EOpSubgroupClusteredAdd:
6751 case glslang::EOpSubgroupClusteredMul:
6752 case glslang::EOpSubgroupClusteredMin:
6753 case glslang::EOpSubgroupClusteredMax:
6754 case glslang::EOpSubgroupClusteredAnd:
6755 case glslang::EOpSubgroupClusteredOr:
6756 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006757 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006758 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006759#ifdef NV_EXTENSIONS
6760 case glslang::EOpSubgroupPartitionedAdd:
6761 case glslang::EOpSubgroupPartitionedMul:
6762 case glslang::EOpSubgroupPartitionedMin:
6763 case glslang::EOpSubgroupPartitionedMax:
6764 case glslang::EOpSubgroupPartitionedAnd:
6765 case glslang::EOpSubgroupPartitionedOr:
6766 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006767 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006768 break;
6769 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6770 case glslang::EOpSubgroupPartitionedInclusiveMul:
6771 case glslang::EOpSubgroupPartitionedInclusiveMin:
6772 case glslang::EOpSubgroupPartitionedInclusiveMax:
6773 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6774 case glslang::EOpSubgroupPartitionedInclusiveOr:
6775 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006776 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006777 break;
6778 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6779 case glslang::EOpSubgroupPartitionedExclusiveMul:
6780 case glslang::EOpSubgroupPartitionedExclusiveMin:
6781 case glslang::EOpSubgroupPartitionedExclusiveMax:
6782 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6783 case glslang::EOpSubgroupPartitionedExclusiveOr:
6784 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006785 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006786 break;
6787#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006788 }
6789
John Kessenich149afc32018-08-14 13:31:43 -06006790 // build the instruction
6791 std::vector<spv::IdImmediate> spvGroupOperands;
6792
6793 // Every operation begins with the Execution Scope operand.
6794 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6795 spvGroupOperands.push_back(executionScope);
6796
6797 // Next, for all operations that use a Group Operation, push that as an operand.
6798 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006799 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006800 spvGroupOperands.push_back(groupOperand);
6801 }
6802
John Kessenich66011cb2018-03-06 16:12:04 -07006803 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006804 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6805 spv::IdImmediate operand = { true, *opIt };
6806 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006807 }
6808
6809 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006810 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006811 switch (op) {
6812 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006813 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6814 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6815 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6816 }
6817 if (directionId != spv::NoResult) {
6818 spv::IdImmediate direction = { true, directionId };
6819 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006820 }
6821
6822 return builder.createOp(opCode, typeId, spvGroupOperands);
6823}
6824
John Kessenich5e4b1242015-08-06 22:53:06 -06006825spv::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 -06006826{
John Kessenich66011cb2018-03-06 16:12:04 -07006827 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6828 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006829
John Kessenich140f3df2015-06-26 16:58:36 -06006830 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006831 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006832 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006833 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006834 spv::Id typeId0 = 0;
6835 if (consumedOperands > 0)
6836 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006837 spv::Id typeId1 = 0;
6838 if (consumedOperands > 1)
6839 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006840 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006841
6842 switch (op) {
6843 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006844 if (isFloat)
6845 libCall = spv::GLSLstd450FMin;
6846 else if (isUnsigned)
6847 libCall = spv::GLSLstd450UMin;
6848 else
6849 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006850 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006851 break;
6852 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006853 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006854 break;
6855 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006856 if (isFloat)
6857 libCall = spv::GLSLstd450FMax;
6858 else if (isUnsigned)
6859 libCall = spv::GLSLstd450UMax;
6860 else
6861 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006862 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006863 break;
6864 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006865 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006866 break;
6867 case glslang::EOpDot:
6868 opCode = spv::OpDot;
6869 break;
6870 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006871 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006872 break;
6873
6874 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006875 if (isFloat)
6876 libCall = spv::GLSLstd450FClamp;
6877 else if (isUnsigned)
6878 libCall = spv::GLSLstd450UClamp;
6879 else
6880 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006881 builder.promoteScalar(precision, operands.front(), operands[1]);
6882 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006883 break;
6884 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006885 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6886 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006887 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006888 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006889 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006890 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006891 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006892 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006893 break;
6894 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006895 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006896 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006897 break;
6898 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006899 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006900 builder.promoteScalar(precision, operands[0], operands[2]);
6901 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006902 break;
6903
6904 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006905 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006906 break;
6907 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006908 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006909 break;
6910 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006911 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006912 break;
6913 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006914 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006915 break;
6916 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006917 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006918 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006919 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006920#ifdef AMD_EXTENSIONS
6921 if (typeProxy == glslang::EbtFloat16)
6922 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6923#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006924 libCall = spv::GLSLstd450InterpolateAtSample;
6925 break;
6926 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006927#ifdef AMD_EXTENSIONS
6928 if (typeProxy == glslang::EbtFloat16)
6929 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6930#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006931 libCall = spv::GLSLstd450InterpolateAtOffset;
6932 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006933 case glslang::EOpAddCarry:
6934 opCode = spv::OpIAddCarry;
6935 typeId = builder.makeStructResultType(typeId0, typeId0);
6936 consumedOperands = 2;
6937 break;
6938 case glslang::EOpSubBorrow:
6939 opCode = spv::OpISubBorrow;
6940 typeId = builder.makeStructResultType(typeId0, typeId0);
6941 consumedOperands = 2;
6942 break;
6943 case glslang::EOpUMulExtended:
6944 opCode = spv::OpUMulExtended;
6945 typeId = builder.makeStructResultType(typeId0, typeId0);
6946 consumedOperands = 2;
6947 break;
6948 case glslang::EOpIMulExtended:
6949 opCode = spv::OpSMulExtended;
6950 typeId = builder.makeStructResultType(typeId0, typeId0);
6951 consumedOperands = 2;
6952 break;
6953 case glslang::EOpBitfieldExtract:
6954 if (isUnsigned)
6955 opCode = spv::OpBitFieldUExtract;
6956 else
6957 opCode = spv::OpBitFieldSExtract;
6958 break;
6959 case glslang::EOpBitfieldInsert:
6960 opCode = spv::OpBitFieldInsert;
6961 break;
6962
6963 case glslang::EOpFma:
6964 libCall = spv::GLSLstd450Fma;
6965 break;
6966 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006967 {
6968 libCall = spv::GLSLstd450FrexpStruct;
6969 assert(builder.isPointerType(typeId1));
6970 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006971 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006972#ifdef AMD_EXTENSIONS
6973 if (width == 16)
6974 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6975 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6976#endif
Rex Xu470026f2017-03-29 17:12:40 +08006977 if (builder.getNumComponents(operands[0]) == 1)
6978 frexpIntType = builder.makeIntegerType(width, true);
6979 else
6980 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6981 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6982 consumedOperands = 1;
6983 }
John Kessenich55e7d112015-11-15 21:33:39 -07006984 break;
6985 case glslang::EOpLdexp:
6986 libCall = spv::GLSLstd450Ldexp;
6987 break;
6988
Rex Xu574ab042016-04-14 16:53:07 +08006989 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006990 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006991
John Kessenich66011cb2018-03-06 16:12:04 -07006992 case glslang::EOpSubgroupBroadcast:
6993 case glslang::EOpSubgroupBallotBitExtract:
6994 case glslang::EOpSubgroupShuffle:
6995 case glslang::EOpSubgroupShuffleXor:
6996 case glslang::EOpSubgroupShuffleUp:
6997 case glslang::EOpSubgroupShuffleDown:
6998 case glslang::EOpSubgroupClusteredAdd:
6999 case glslang::EOpSubgroupClusteredMul:
7000 case glslang::EOpSubgroupClusteredMin:
7001 case glslang::EOpSubgroupClusteredMax:
7002 case glslang::EOpSubgroupClusteredAnd:
7003 case glslang::EOpSubgroupClusteredOr:
7004 case glslang::EOpSubgroupClusteredXor:
7005 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007006#ifdef NV_EXTENSIONS
7007 case glslang::EOpSubgroupPartitionedAdd:
7008 case glslang::EOpSubgroupPartitionedMul:
7009 case glslang::EOpSubgroupPartitionedMin:
7010 case glslang::EOpSubgroupPartitionedMax:
7011 case glslang::EOpSubgroupPartitionedAnd:
7012 case glslang::EOpSubgroupPartitionedOr:
7013 case glslang::EOpSubgroupPartitionedXor:
7014 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7015 case glslang::EOpSubgroupPartitionedInclusiveMul:
7016 case glslang::EOpSubgroupPartitionedInclusiveMin:
7017 case glslang::EOpSubgroupPartitionedInclusiveMax:
7018 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7019 case glslang::EOpSubgroupPartitionedInclusiveOr:
7020 case glslang::EOpSubgroupPartitionedInclusiveXor:
7021 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7022 case glslang::EOpSubgroupPartitionedExclusiveMul:
7023 case glslang::EOpSubgroupPartitionedExclusiveMin:
7024 case glslang::EOpSubgroupPartitionedExclusiveMax:
7025 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7026 case glslang::EOpSubgroupPartitionedExclusiveOr:
7027 case glslang::EOpSubgroupPartitionedExclusiveXor:
7028#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007029 return createSubgroupOperation(op, typeId, operands, typeProxy);
7030
Rex Xu9d93a232016-05-05 12:30:44 +08007031#ifdef AMD_EXTENSIONS
7032 case glslang::EOpSwizzleInvocations:
7033 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7034 libCall = spv::SwizzleInvocationsAMD;
7035 break;
7036 case glslang::EOpSwizzleInvocationsMasked:
7037 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7038 libCall = spv::SwizzleInvocationsMaskedAMD;
7039 break;
7040 case glslang::EOpWriteInvocation:
7041 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7042 libCall = spv::WriteInvocationAMD;
7043 break;
7044
7045 case glslang::EOpMin3:
7046 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7047 if (isFloat)
7048 libCall = spv::FMin3AMD;
7049 else {
7050 if (isUnsigned)
7051 libCall = spv::UMin3AMD;
7052 else
7053 libCall = spv::SMin3AMD;
7054 }
7055 break;
7056 case glslang::EOpMax3:
7057 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7058 if (isFloat)
7059 libCall = spv::FMax3AMD;
7060 else {
7061 if (isUnsigned)
7062 libCall = spv::UMax3AMD;
7063 else
7064 libCall = spv::SMax3AMD;
7065 }
7066 break;
7067 case glslang::EOpMid3:
7068 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7069 if (isFloat)
7070 libCall = spv::FMid3AMD;
7071 else {
7072 if (isUnsigned)
7073 libCall = spv::UMid3AMD;
7074 else
7075 libCall = spv::SMid3AMD;
7076 }
7077 break;
7078
7079 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007080 if (typeProxy == glslang::EbtFloat16)
7081 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007082 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7083 libCall = spv::InterpolateAtVertexAMD;
7084 break;
7085#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007086 case glslang::EOpBarrier:
7087 {
7088 // This is for the extended controlBarrier function, with four operands.
7089 // The unextended barrier() goes through createNoArgOperation.
7090 assert(operands.size() == 4);
7091 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7092 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7093 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7094 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7095 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7096 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7097 }
7098 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7099 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7100 }
7101 return 0;
7102 }
7103 break;
7104 case glslang::EOpMemoryBarrier:
7105 {
7106 // This is for the extended memoryBarrier function, with three operands.
7107 // The unextended memoryBarrier() goes through createNoArgOperation.
7108 assert(operands.size() == 3);
7109 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7110 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7111 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7112 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7113 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7114 }
7115 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7116 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7117 }
7118 return 0;
7119 }
7120 break;
Chao Chen3c366992018-09-19 11:41:59 -07007121
7122#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007123 case glslang::EOpReportIntersectionNV:
7124 {
7125 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007126 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007127 }
7128 break;
7129 case glslang::EOpTraceNV:
7130 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007131 builder.createNoResultOp(spv::OpTraceNV, operands);
7132 return 0;
7133 }
7134 break;
7135 case glslang::EOpExecuteCallableNV:
7136 {
7137 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007138 return 0;
7139 }
7140 break;
Chao Chen3c366992018-09-19 11:41:59 -07007141 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7142 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7143 return 0;
7144#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007145 case glslang::EOpCooperativeMatrixMulAdd:
7146 opCode = spv::OpCooperativeMatrixMulAddNV;
7147 break;
7148
John Kessenich140f3df2015-06-26 16:58:36 -06007149 default:
7150 return 0;
7151 }
7152
7153 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007154 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007155 // Use an extended instruction from the standard library.
7156 // Construct the call arguments, without modifying the original operands vector.
7157 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7158 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007159 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007160 } else if (opCode == spv::OpDot && !isFloat) {
7161 // int dot(int, int)
7162 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7163 const int componentCount = builder.getNumComponents(operands[0]);
7164 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7165 builder.setPrecision(mulOp, precision);
7166 id = builder.createCompositeExtract(mulOp, typeId, 0);
7167 for (int i = 1; i < componentCount; ++i) {
7168 builder.setPrecision(id, precision);
7169 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7170 }
John Kessenich2359bd02015-12-06 19:29:11 -07007171 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007172 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007173 case 0:
7174 // should all be handled by visitAggregate and createNoArgOperation
7175 assert(0);
7176 return 0;
7177 case 1:
7178 // should all be handled by createUnaryOperation
7179 assert(0);
7180 return 0;
7181 case 2:
7182 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7183 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007184 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007185 // anything 3 or over doesn't have l-value operands, so all should be consumed
7186 assert(consumedOperands == operands.size());
7187 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007188 break;
7189 }
7190 }
7191
John Kessenich55e7d112015-11-15 21:33:39 -07007192 // Decode the return types that were structures
7193 switch (op) {
7194 case glslang::EOpAddCarry:
7195 case glslang::EOpSubBorrow:
7196 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7197 id = builder.createCompositeExtract(id, typeId0, 0);
7198 break;
7199 case glslang::EOpUMulExtended:
7200 case glslang::EOpIMulExtended:
7201 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7202 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7203 break;
7204 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007205 {
7206 assert(operands.size() == 2);
7207 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7208 // "exp" is floating-point type (from HLSL intrinsic)
7209 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7210 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7211 builder.createStore(member1, operands[1]);
7212 } else
7213 // "exp" is integer type (from GLSL built-in function)
7214 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7215 id = builder.createCompositeExtract(id, typeId0, 0);
7216 }
John Kessenich55e7d112015-11-15 21:33:39 -07007217 break;
7218 default:
7219 break;
7220 }
7221
John Kessenich32cfd492016-02-02 12:37:46 -07007222 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007223}
7224
Rex Xu9d93a232016-05-05 12:30:44 +08007225// Intrinsics with no arguments (or no return value, and no precision).
7226spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007227{
Jeff Bolz36831c92018-09-05 10:11:41 -05007228 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7229 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007230
7231 switch (op) {
7232 case glslang::EOpEmitVertex:
7233 builder.createNoResultOp(spv::OpEmitVertex);
7234 return 0;
7235 case glslang::EOpEndPrimitive:
7236 builder.createNoResultOp(spv::OpEndPrimitive);
7237 return 0;
7238 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007239 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007240 if (glslangIntermediate->usingVulkanMemoryModel()) {
7241 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7242 spv::MemorySemanticsOutputMemoryKHRMask |
7243 spv::MemorySemanticsAcquireReleaseMask);
7244 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7245 } else {
7246 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7247 }
John Kessenich82979362017-12-11 04:02:24 -07007248 } else {
7249 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7250 spv::MemorySemanticsWorkgroupMemoryMask |
7251 spv::MemorySemanticsAcquireReleaseMask);
7252 }
John Kessenich140f3df2015-06-26 16:58:36 -06007253 return 0;
7254 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007255 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7256 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007257 return 0;
7258 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007259 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7260 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007261 return 0;
7262 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007263 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7264 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007265 return 0;
7266 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007267 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7268 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007269 return 0;
7270 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007271 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7272 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007273 return 0;
7274 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007275 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7276 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007277 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007278 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007279 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007280 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007281 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007282 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007283 case glslang::EOpDeviceMemoryBarrier:
7284 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7285 spv::MemorySemanticsImageMemoryMask |
7286 spv::MemorySemanticsAcquireReleaseMask);
7287 return 0;
7288 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7289 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7290 spv::MemorySemanticsImageMemoryMask |
7291 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007292 return 0;
7293 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007294 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7295 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007296 return 0;
7297 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007298 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7299 spv::MemorySemanticsWorkgroupMemoryMask |
7300 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007301 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007302 case glslang::EOpSubgroupBarrier:
7303 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7304 spv::MemorySemanticsAcquireReleaseMask);
7305 return spv::NoResult;
7306 case glslang::EOpSubgroupMemoryBarrier:
7307 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7308 spv::MemorySemanticsAcquireReleaseMask);
7309 return spv::NoResult;
7310 case glslang::EOpSubgroupMemoryBarrierBuffer:
7311 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7312 spv::MemorySemanticsAcquireReleaseMask);
7313 return spv::NoResult;
7314 case glslang::EOpSubgroupMemoryBarrierImage:
7315 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7316 spv::MemorySemanticsAcquireReleaseMask);
7317 return spv::NoResult;
7318 case glslang::EOpSubgroupMemoryBarrierShared:
7319 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7320 spv::MemorySemanticsAcquireReleaseMask);
7321 return spv::NoResult;
7322 case glslang::EOpSubgroupElect: {
7323 std::vector<spv::Id> operands;
7324 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7325 }
Rex Xu9d93a232016-05-05 12:30:44 +08007326#ifdef AMD_EXTENSIONS
7327 case glslang::EOpTime:
7328 {
7329 std::vector<spv::Id> args; // Dummy arguments
7330 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7331 return builder.setPrecision(id, precision);
7332 }
7333#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007334#ifdef NV_EXTENSIONS
7335 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007336 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007337 return 0;
7338 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007339 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007340 return 0;
7341#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007342 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007343 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007344 return 0;
7345 }
7346}
7347
7348spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7349{
John Kessenich2f273362015-07-18 22:34:27 -06007350 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007351 spv::Id id;
7352 if (symbolValues.end() != iter) {
7353 id = iter->second;
7354 return id;
7355 }
7356
7357 // it was not found, create it
7358 id = createSpvVariable(symbol);
7359 symbolValues[symbol->getId()] = id;
7360
Rex Xuc884b4a2016-06-29 15:03:44 +08007361 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007362 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7363 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7364 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007365#ifdef NV_EXTENSIONS
7366 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7367#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007368 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007369 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007370 if (symbol->getQualifier().hasIndex())
7371 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7372 if (symbol->getQualifier().hasComponent())
7373 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007374 // atomic counters use this:
7375 if (symbol->getQualifier().hasOffset())
7376 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007377 }
7378
scygan2c864272016-05-18 18:09:17 +02007379 if (symbol->getQualifier().hasLocation())
7380 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007381 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007382 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007383 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007384 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007385 }
John Kessenich140f3df2015-06-26 16:58:36 -06007386 if (symbol->getQualifier().hasSet())
7387 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007388 else if (IsDescriptorResource(symbol->getType())) {
7389 // default to 0
7390 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7391 }
John Kessenich140f3df2015-06-26 16:58:36 -06007392 if (symbol->getQualifier().hasBinding())
7393 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007394 else if (IsDescriptorResource(symbol->getType())) {
7395 // default to 0
7396 builder.addDecoration(id, spv::DecorationBinding, 0);
7397 }
John Kessenich6c292d32016-02-15 20:58:50 -07007398 if (symbol->getQualifier().hasAttachment())
7399 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007400 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007401 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007402 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007403 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007404 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7405 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7406 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7407 }
7408 if (symbol->getQualifier().hasXfbOffset())
7409 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007410 }
7411
Rex Xu1da878f2016-02-21 20:59:01 +08007412 if (symbol->getType().isImage()) {
7413 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007414 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007415 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007416 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007417 }
7418
John Kessenich140f3df2015-06-26 16:58:36 -06007419 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007420 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007421 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007422 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007423
John Kessenich5611c6d2018-04-05 11:25:02 -06007424 // nonuniform
7425 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7426
John Kessenichecba76f2017-01-06 00:34:48 -07007427#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007428 if (builtIn == spv::BuiltInSampleMask) {
7429 spv::Decoration decoration;
7430 // GL_NV_sample_mask_override_coverage extension
7431 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007432 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007433 else
7434 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007435 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007436 if (decoration != spv::DecorationMax) {
7437 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7438 }
7439 }
chaoc771d89f2017-01-13 01:10:53 -08007440 else if (builtIn == spv::BuiltInLayer) {
7441 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007442 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007443 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007444 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7445 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7446 }
John Kessenichb41bff62017-08-11 13:07:17 -06007447 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007448 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7449 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007450 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7451 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7452 }
7453 }
7454
chaoc6e5acae2016-12-20 13:28:52 -08007455 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007456 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007457 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007458 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7459 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007460 if (symbol->getQualifier().pervertexNV) {
7461 builder.addDecoration(id, spv::DecorationPerVertexNV);
7462 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7463 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7464 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007465#endif
7466
John Kessenich5d610ee2018-03-07 18:05:55 -07007467 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7468 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7469 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7470 symbol->getType().getQualifier().semanticName);
7471 }
7472
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007473 if (symbol->getBasicType() == glslang::EbtReference) {
7474 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7475 }
7476
John Kessenich140f3df2015-06-26 16:58:36 -06007477 return id;
7478}
7479
Chao Chen3c366992018-09-19 11:41:59 -07007480#ifdef NV_EXTENSIONS
7481// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7482void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7483{
7484 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007485 if (qualifier.perPrimitiveNV) {
7486 // Need to add capability/extension for fragment shader.
7487 // Mesh shader already adds this by default.
7488 if (glslangIntermediate->getStage() == EShLangFragment) {
7489 builder.addCapability(spv::CapabilityMeshShadingNV);
7490 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7491 }
Chao Chen3c366992018-09-19 11:41:59 -07007492 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007493 }
Chao Chen3c366992018-09-19 11:41:59 -07007494 if (qualifier.perViewNV)
7495 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7496 if (qualifier.perTaskNV)
7497 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7498 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007499 if (qualifier.perPrimitiveNV) {
7500 // Need to add capability/extension for fragment shader.
7501 // Mesh shader already adds this by default.
7502 if (glslangIntermediate->getStage() == EShLangFragment) {
7503 builder.addCapability(spv::CapabilityMeshShadingNV);
7504 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7505 }
Chao Chen3c366992018-09-19 11:41:59 -07007506 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007507 }
Chao Chen3c366992018-09-19 11:41:59 -07007508 if (qualifier.perViewNV)
7509 builder.addDecoration(id, spv::DecorationPerViewNV);
7510 if (qualifier.perTaskNV)
7511 builder.addDecoration(id, spv::DecorationPerTaskNV);
7512 }
7513}
7514#endif
7515
John Kessenich55e7d112015-11-15 21:33:39 -07007516// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007517// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007518//
7519// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7520//
7521// Recursively walk the nodes. The nodes form a tree whose leaves are
7522// regular constants, which themselves are trees that createSpvConstant()
7523// recursively walks. So, this function walks the "top" of the tree:
7524// - emit specialization constant-building instructions for specConstant
7525// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007526spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007527{
John Kessenich7cc0e282016-03-20 00:46:02 -06007528 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007529
qining4f4bb812016-04-03 23:55:17 -04007530 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007531 if (! node.getQualifier().specConstant) {
7532 // hand off to the non-spec-constant path
7533 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7534 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007535 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007536 nextConst, false);
7537 }
7538
7539 // We now know we have a specialization constant to build
7540
John Kessenichd94c0032016-05-30 19:29:40 -06007541 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007542 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7543 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7544 std::vector<spv::Id> dimConstId;
7545 for (int dim = 0; dim < 3; ++dim) {
7546 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7547 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007548 if (specConst) {
7549 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7550 glslangIntermediate->getLocalSizeSpecId(dim));
7551 }
qining4f4bb812016-04-03 23:55:17 -04007552 }
7553 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7554 }
7555
7556 // An AST node labelled as specialization constant should be a symbol node.
7557 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7558 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007559 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007560 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007561 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7562 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7563 // will set the builder into spec constant op instruction generating mode.
7564 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007565 result = accessChainLoad(sub_tree->getType());
7566 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007567 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007568 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007569 } else {
7570 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007571 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007572 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007573 builder.addName(result, sn->getName().c_str());
7574 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007575 }
qining4f4bb812016-04-03 23:55:17 -04007576
7577 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7578 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007579 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007580 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007581}
7582
John Kessenich140f3df2015-06-26 16:58:36 -06007583// Use 'consts' as the flattened glslang source of scalar constants to recursively
7584// build the aggregate SPIR-V constant.
7585//
7586// If there are not enough elements present in 'consts', 0 will be substituted;
7587// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7588//
qining08408382016-03-21 09:51:37 -04007589spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007590{
7591 // vector of constants for SPIR-V
7592 std::vector<spv::Id> spvConsts;
7593
7594 // Type is used for struct and array constants
7595 spv::Id typeId = convertGlslangToSpvType(glslangType);
7596
7597 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007598 glslang::TType elementType(glslangType, 0);
7599 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007600 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007601 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007602 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007603 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007604 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007605 } else if (glslangType.isCoopMat()) {
7606 glslang::TType componentType(glslangType.getBasicType());
7607 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007608 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007609 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7610 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007611 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007612 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007613 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7614 bool zero = nextConst >= consts.size();
7615 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007616 case glslang::EbtInt8:
7617 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7618 break;
7619 case glslang::EbtUint8:
7620 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7621 break;
7622 case glslang::EbtInt16:
7623 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7624 break;
7625 case glslang::EbtUint16:
7626 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7627 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007628 case glslang::EbtInt:
7629 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7630 break;
7631 case glslang::EbtUint:
7632 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7633 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007634 case glslang::EbtInt64:
7635 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7636 break;
7637 case glslang::EbtUint64:
7638 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7639 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007640 case glslang::EbtFloat:
7641 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7642 break;
7643 case glslang::EbtDouble:
7644 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7645 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007646 case glslang::EbtFloat16:
7647 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7648 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007649 case glslang::EbtBool:
7650 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7651 break;
7652 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007653 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007654 break;
7655 }
7656 ++nextConst;
7657 }
7658 } else {
7659 // we have a non-aggregate (scalar) constant
7660 bool zero = nextConst >= consts.size();
7661 spv::Id scalar = 0;
7662 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007663 case glslang::EbtInt8:
7664 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7665 break;
7666 case glslang::EbtUint8:
7667 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7668 break;
7669 case glslang::EbtInt16:
7670 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7671 break;
7672 case glslang::EbtUint16:
7673 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7674 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007675 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007676 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007677 break;
7678 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007679 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007680 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007681 case glslang::EbtInt64:
7682 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7683 break;
7684 case glslang::EbtUint64:
7685 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7686 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007687 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007688 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007689 break;
7690 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007691 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007692 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007693 case glslang::EbtFloat16:
7694 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7695 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007696 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007697 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007698 break;
7699 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007700 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007701 break;
7702 }
7703 ++nextConst;
7704 return scalar;
7705 }
7706
7707 return builder.makeCompositeConstant(typeId, spvConsts);
7708}
7709
John Kessenich7c1aa102015-10-15 13:29:11 -06007710// Return true if the node is a constant or symbol whose reading has no
7711// non-trivial observable cost or effect.
7712bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7713{
7714 // don't know what this is
7715 if (node == nullptr)
7716 return false;
7717
7718 // a constant is safe
7719 if (node->getAsConstantUnion() != nullptr)
7720 return true;
7721
7722 // not a symbol means non-trivial
7723 if (node->getAsSymbolNode() == nullptr)
7724 return false;
7725
7726 // a symbol, depends on what's being read
7727 switch (node->getType().getQualifier().storage) {
7728 case glslang::EvqTemporary:
7729 case glslang::EvqGlobal:
7730 case glslang::EvqIn:
7731 case glslang::EvqInOut:
7732 case glslang::EvqConst:
7733 case glslang::EvqConstReadOnly:
7734 case glslang::EvqUniform:
7735 return true;
7736 default:
7737 return false;
7738 }
qining25262b32016-05-06 17:25:16 -04007739}
John Kessenich7c1aa102015-10-15 13:29:11 -06007740
7741// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007742// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007743// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007744// Return true if trivial.
7745bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7746{
7747 if (node == nullptr)
7748 return false;
7749
John Kessenich84cc15f2017-05-24 16:44:47 -06007750 // count non scalars as trivial, as well as anything coming from HLSL
7751 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007752 return true;
7753
John Kessenich7c1aa102015-10-15 13:29:11 -06007754 // symbols and constants are trivial
7755 if (isTrivialLeaf(node))
7756 return true;
7757
7758 // otherwise, it needs to be a simple operation or one or two leaf nodes
7759
7760 // not a simple operation
7761 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7762 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7763 if (binaryNode == nullptr && unaryNode == nullptr)
7764 return false;
7765
7766 // not on leaf nodes
7767 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7768 return false;
7769
7770 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7771 return false;
7772 }
7773
7774 switch (node->getAsOperator()->getOp()) {
7775 case glslang::EOpLogicalNot:
7776 case glslang::EOpConvIntToBool:
7777 case glslang::EOpConvUintToBool:
7778 case glslang::EOpConvFloatToBool:
7779 case glslang::EOpConvDoubleToBool:
7780 case glslang::EOpEqual:
7781 case glslang::EOpNotEqual:
7782 case glslang::EOpLessThan:
7783 case glslang::EOpGreaterThan:
7784 case glslang::EOpLessThanEqual:
7785 case glslang::EOpGreaterThanEqual:
7786 case glslang::EOpIndexDirect:
7787 case glslang::EOpIndexDirectStruct:
7788 case glslang::EOpLogicalXor:
7789 case glslang::EOpAny:
7790 case glslang::EOpAll:
7791 return true;
7792 default:
7793 return false;
7794 }
7795}
7796
7797// Emit short-circuiting code, where 'right' is never evaluated unless
7798// the left side is true (for &&) or false (for ||).
7799spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7800{
7801 spv::Id boolTypeId = builder.makeBoolType();
7802
7803 // emit left operand
7804 builder.clearAccessChain();
7805 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007806 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007807
7808 // Operands to accumulate OpPhi operands
7809 std::vector<spv::Id> phiOperands;
7810 // accumulate left operand's phi information
7811 phiOperands.push_back(leftId);
7812 phiOperands.push_back(builder.getBuildPoint()->getId());
7813
7814 // Make the two kinds of operation symmetric with a "!"
7815 // || => emit "if (! left) result = right"
7816 // && => emit "if ( left) result = right"
7817 //
7818 // TODO: this runtime "not" for || could be avoided by adding functionality
7819 // to 'builder' to have an "else" without an "then"
7820 if (op == glslang::EOpLogicalOr)
7821 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7822
7823 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007824 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007825
7826 // emit right operand as the "then" part of the "if"
7827 builder.clearAccessChain();
7828 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007829 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007830
7831 // accumulate left operand's phi information
7832 phiOperands.push_back(rightId);
7833 phiOperands.push_back(builder.getBuildPoint()->getId());
7834
7835 // finish the "if"
7836 ifBuilder.makeEndIf();
7837
7838 // phi together the two results
7839 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7840}
7841
Frank Henigman541f7bb2018-01-16 00:18:26 -05007842#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007843// Return type Id of the imported set of extended instructions corresponds to the name.
7844// Import this set if it has not been imported yet.
7845spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7846{
7847 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7848 return extBuiltinMap[name];
7849 else {
Rex Xu51596642016-09-21 18:56:12 +08007850 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007851 spv::Id extBuiltins = builder.import(name);
7852 extBuiltinMap[name] = extBuiltins;
7853 return extBuiltins;
7854 }
7855}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007856#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007857
John Kessenich140f3df2015-06-26 16:58:36 -06007858}; // end anonymous namespace
7859
7860namespace glslang {
7861
John Kessenich68d78fd2015-07-12 19:28:10 -06007862void GetSpirvVersion(std::string& version)
7863{
John Kessenich9e55f632015-07-15 10:03:39 -06007864 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007865 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007866 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007867 version = buf;
7868}
7869
John Kessenicha372a3e2017-11-02 22:32:14 -06007870// For low-order part of the generator's magic number. Bump up
7871// when there is a change in the style (e.g., if SSA form changes,
7872// or a different instruction sequence to do something gets used).
7873int GetSpirvGeneratorVersion()
7874{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007875 // return 1; // start
7876 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007877 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007878 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007879 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007880 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7881 // versions 4 and 6 each generate OpArrayLength as it has long been done
7882 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007883}
7884
John Kessenich140f3df2015-06-26 16:58:36 -06007885// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007886void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007887{
7888 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007889 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007890 if (out.fail())
7891 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007892 for (int i = 0; i < (int)spirv.size(); ++i) {
7893 unsigned int word = spirv[i];
7894 out.write((const char*)&word, 4);
7895 }
7896 out.close();
7897}
7898
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007899// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007900void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007901{
7902 std::ofstream out;
7903 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007904 if (out.fail())
7905 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007906 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007907 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007908 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007909 if (varName != nullptr) {
7910 out << "\t #pragma once" << std::endl;
7911 out << "const uint32_t " << varName << "[] = {" << std::endl;
7912 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007913 const int WORDS_PER_LINE = 8;
7914 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7915 out << "\t";
7916 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7917 const unsigned int word = spirv[i + j];
7918 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7919 if (i + j + 1 < (int)spirv.size()) {
7920 out << ",";
7921 }
7922 }
7923 out << std::endl;
7924 }
Flavio15017db2017-02-15 14:29:33 -08007925 if (varName != nullptr) {
7926 out << "};";
7927 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007928 out.close();
7929}
7930
John Kessenich140f3df2015-06-26 16:58:36 -06007931//
7932// Set up the glslang traversal
7933//
John Kessenich4e11b612018-08-30 16:56:59 -06007934void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007935{
Lei Zhang17535f72016-05-04 15:55:59 -04007936 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007937 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007938}
7939
John Kessenich4e11b612018-08-30 16:56:59 -06007940void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007941 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007942{
John Kessenich140f3df2015-06-26 16:58:36 -06007943 TIntermNode* root = intermediate.getTreeRoot();
7944
7945 if (root == 0)
7946 return;
7947
John Kessenich4e11b612018-08-30 16:56:59 -06007948 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007949 if (options == nullptr)
7950 options = &defaultOptions;
7951
John Kessenich4e11b612018-08-30 16:56:59 -06007952 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007953
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007954 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007955 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007956 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007957 it.dumpSpv(spirv);
7958
GregFfb03a552018-03-29 11:49:14 -06007959#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007960 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7961 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007962 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007963 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007964
John Kessenich4e11b612018-08-30 16:56:59 -06007965 if (options->validate)
7966 SpirvToolsValidate(intermediate, spirv, logger);
7967
John Kessenich717c80a2018-08-23 15:17:10 -06007968 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007969 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007970
GregFcd1f1692017-09-21 18:40:22 -06007971#endif
7972
John Kessenich4e11b612018-08-30 16:56:59 -06007973 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06007974}
7975
7976}; // end namespace glslang