blob: 655d77b4e82943c4a72c42536ddccbaacba7d419 [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;
Jeff Bolz88220d52019-05-08 10:24:46 -05005546
5547 case glslang::EOpCopyObject:
5548 unaryOp = spv::OpCopyObject;
5549 break;
5550
John Kessenich140f3df2015-06-26 16:58:36 -06005551 default:
5552 return 0;
5553 }
5554
5555 spv::Id id;
5556 if (libCall >= 0) {
5557 std::vector<spv::Id> args;
5558 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005559 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005560 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005561 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005562 }
John Kessenich140f3df2015-06-26 16:58:36 -06005563
John Kessenichead86222018-03-28 18:01:20 -06005564 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005565 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005566 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005567}
5568
John Kessenich7a53f762016-01-20 11:19:27 -07005569// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005570spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5571 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005572{
5573 // Handle unary operations vector by vector.
5574 // The result type is the same type as the original type.
5575 // The algorithm is to:
5576 // - break the matrix into vectors
5577 // - apply the operation to each vector
5578 // - make a matrix out the vector results
5579
5580 // get the types sorted out
5581 int numCols = builder.getNumColumns(operand);
5582 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005583 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5584 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005585 std::vector<spv::Id> results;
5586
5587 // do each vector op
5588 for (int c = 0; c < numCols; ++c) {
5589 std::vector<unsigned int> indexes;
5590 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005591 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5592 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005593 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005594 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005595 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005596 }
5597
5598 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005599 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005600 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005601 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005602}
5603
John Kessenichad7645f2018-06-04 19:11:25 -06005604// For converting integers where both the bitwidth and the signedness could
5605// change, but only do the width change here. The caller is still responsible
5606// for the signedness conversion.
5607spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005608{
John Kessenichad7645f2018-06-04 19:11:25 -06005609 // Get the result type width, based on the type to convert to.
5610 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005611 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005612 case glslang::EOpConvInt16ToUint8:
5613 case glslang::EOpConvIntToUint8:
5614 case glslang::EOpConvInt64ToUint8:
5615 case glslang::EOpConvUint16ToInt8:
5616 case glslang::EOpConvUintToInt8:
5617 case glslang::EOpConvUint64ToInt8:
5618 width = 8;
5619 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005620 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005621 case glslang::EOpConvIntToUint16:
5622 case glslang::EOpConvInt64ToUint16:
5623 case glslang::EOpConvUint8ToInt16:
5624 case glslang::EOpConvUintToInt16:
5625 case glslang::EOpConvUint64ToInt16:
5626 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005627 break;
5628 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005629 case glslang::EOpConvInt16ToUint:
5630 case glslang::EOpConvInt64ToUint:
5631 case glslang::EOpConvUint8ToInt:
5632 case glslang::EOpConvUint16ToInt:
5633 case glslang::EOpConvUint64ToInt:
5634 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005635 break;
5636 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005637 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005638 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005639 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005640 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005641 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005642 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005643 break;
5644
5645 default:
5646 assert(false && "Default missing");
5647 break;
5648 }
5649
John Kessenichad7645f2018-06-04 19:11:25 -06005650 // Get the conversion operation and result type,
5651 // based on the target width, but the source type.
5652 spv::Id type = spv::NoType;
5653 spv::Op convOp = spv::OpNop;
5654 switch(op) {
5655 case glslang::EOpConvInt8ToUint16:
5656 case glslang::EOpConvInt8ToUint:
5657 case glslang::EOpConvInt8ToUint64:
5658 case glslang::EOpConvInt16ToUint8:
5659 case glslang::EOpConvInt16ToUint:
5660 case glslang::EOpConvInt16ToUint64:
5661 case glslang::EOpConvIntToUint8:
5662 case glslang::EOpConvIntToUint16:
5663 case glslang::EOpConvIntToUint64:
5664 case glslang::EOpConvInt64ToUint8:
5665 case glslang::EOpConvInt64ToUint16:
5666 case glslang::EOpConvInt64ToUint:
5667 convOp = spv::OpSConvert;
5668 type = builder.makeIntType(width);
5669 break;
5670 default:
5671 convOp = spv::OpUConvert;
5672 type = builder.makeUintType(width);
5673 break;
5674 }
5675
John Kessenich66011cb2018-03-06 16:12:04 -07005676 if (vectorSize > 0)
5677 type = builder.makeVectorType(type, vectorSize);
5678
John Kessenichad7645f2018-06-04 19:11:25 -06005679 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005680}
5681
John Kessenichead86222018-03-28 18:01:20 -06005682spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5683 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005684{
5685 spv::Op convOp = spv::OpNop;
5686 spv::Id zero = 0;
5687 spv::Id one = 0;
5688
5689 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5690
5691 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005692 case glslang::EOpConvInt8ToBool:
5693 case glslang::EOpConvUint8ToBool:
5694 zero = builder.makeUint8Constant(0);
5695 zero = makeSmearedConstant(zero, vectorSize);
5696 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005697 case glslang::EOpConvInt16ToBool:
5698 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005699 zero = builder.makeUint16Constant(0);
5700 zero = makeSmearedConstant(zero, vectorSize);
5701 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5702 case glslang::EOpConvIntToBool:
5703 case glslang::EOpConvUintToBool:
5704 zero = builder.makeUintConstant(0);
5705 zero = makeSmearedConstant(zero, vectorSize);
5706 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5707 case glslang::EOpConvInt64ToBool:
5708 case glslang::EOpConvUint64ToBool:
5709 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005710 zero = makeSmearedConstant(zero, vectorSize);
5711 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5712
5713 case glslang::EOpConvFloatToBool:
5714 zero = builder.makeFloatConstant(0.0F);
5715 zero = makeSmearedConstant(zero, vectorSize);
5716 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5717
5718 case glslang::EOpConvDoubleToBool:
5719 zero = builder.makeDoubleConstant(0.0);
5720 zero = makeSmearedConstant(zero, vectorSize);
5721 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5722
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005723 case glslang::EOpConvFloat16ToBool:
5724 zero = builder.makeFloat16Constant(0.0F);
5725 zero = makeSmearedConstant(zero, vectorSize);
5726 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005727
John Kessenich140f3df2015-06-26 16:58:36 -06005728 case glslang::EOpConvBoolToFloat:
5729 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005730 zero = builder.makeFloatConstant(0.0F);
5731 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005732 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005733
John Kessenich140f3df2015-06-26 16:58:36 -06005734 case glslang::EOpConvBoolToDouble:
5735 convOp = spv::OpSelect;
5736 zero = builder.makeDoubleConstant(0.0);
5737 one = builder.makeDoubleConstant(1.0);
5738 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005739
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005740 case glslang::EOpConvBoolToFloat16:
5741 convOp = spv::OpSelect;
5742 zero = builder.makeFloat16Constant(0.0F);
5743 one = builder.makeFloat16Constant(1.0F);
5744 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005745
5746 case glslang::EOpConvBoolToInt8:
5747 zero = builder.makeInt8Constant(0);
5748 one = builder.makeInt8Constant(1);
5749 convOp = spv::OpSelect;
5750 break;
5751
5752 case glslang::EOpConvBoolToUint8:
5753 zero = builder.makeUint8Constant(0);
5754 one = builder.makeUint8Constant(1);
5755 convOp = spv::OpSelect;
5756 break;
5757
5758 case glslang::EOpConvBoolToInt16:
5759 zero = builder.makeInt16Constant(0);
5760 one = builder.makeInt16Constant(1);
5761 convOp = spv::OpSelect;
5762 break;
5763
5764 case glslang::EOpConvBoolToUint16:
5765 zero = builder.makeUint16Constant(0);
5766 one = builder.makeUint16Constant(1);
5767 convOp = spv::OpSelect;
5768 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005769
John Kessenich140f3df2015-06-26 16:58:36 -06005770 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005771 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005772 if (op == glslang::EOpConvBoolToInt64)
5773 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005774 else
5775 zero = builder.makeIntConstant(0);
5776
5777 if (op == glslang::EOpConvBoolToInt64)
5778 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005779 else
5780 one = builder.makeIntConstant(1);
5781
John Kessenich140f3df2015-06-26 16:58:36 -06005782 convOp = spv::OpSelect;
5783 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005784
John Kessenich140f3df2015-06-26 16:58:36 -06005785 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005786 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005787 if (op == glslang::EOpConvBoolToUint64)
5788 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005789 else
5790 zero = builder.makeUintConstant(0);
5791
5792 if (op == glslang::EOpConvBoolToUint64)
5793 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005794 else
5795 one = builder.makeUintConstant(1);
5796
John Kessenich140f3df2015-06-26 16:58:36 -06005797 convOp = spv::OpSelect;
5798 break;
5799
John Kessenich66011cb2018-03-06 16:12:04 -07005800 case glslang::EOpConvInt8ToFloat16:
5801 case glslang::EOpConvInt8ToFloat:
5802 case glslang::EOpConvInt8ToDouble:
5803 case glslang::EOpConvInt16ToFloat16:
5804 case glslang::EOpConvInt16ToFloat:
5805 case glslang::EOpConvInt16ToDouble:
5806 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005807 case glslang::EOpConvIntToFloat:
5808 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005809 case glslang::EOpConvInt64ToFloat:
5810 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005811 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005812 convOp = spv::OpConvertSToF;
5813 break;
5814
John Kessenich66011cb2018-03-06 16:12:04 -07005815 case glslang::EOpConvUint8ToFloat16:
5816 case glslang::EOpConvUint8ToFloat:
5817 case glslang::EOpConvUint8ToDouble:
5818 case glslang::EOpConvUint16ToFloat16:
5819 case glslang::EOpConvUint16ToFloat:
5820 case glslang::EOpConvUint16ToDouble:
5821 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005822 case glslang::EOpConvUintToFloat:
5823 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005824 case glslang::EOpConvUint64ToFloat:
5825 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005826 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005827 convOp = spv::OpConvertUToF;
5828 break;
5829
5830 case glslang::EOpConvDoubleToFloat:
5831 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005832 case glslang::EOpConvDoubleToFloat16:
5833 case glslang::EOpConvFloat16ToDouble:
5834 case glslang::EOpConvFloatToFloat16:
5835 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005836 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005837 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005838 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005839 break;
5840
John Kessenich66011cb2018-03-06 16:12:04 -07005841 case glslang::EOpConvFloat16ToInt8:
5842 case glslang::EOpConvFloatToInt8:
5843 case glslang::EOpConvDoubleToInt8:
5844 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005845 case glslang::EOpConvFloatToInt16:
5846 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005847 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005848 case glslang::EOpConvFloatToInt:
5849 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005850 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005851 case glslang::EOpConvFloatToInt64:
5852 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005853 convOp = spv::OpConvertFToS;
5854 break;
5855
John Kessenich66011cb2018-03-06 16:12:04 -07005856 case glslang::EOpConvUint8ToInt8:
5857 case glslang::EOpConvInt8ToUint8:
5858 case glslang::EOpConvUint16ToInt16:
5859 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005860 case glslang::EOpConvUintToInt:
5861 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005862 case glslang::EOpConvUint64ToInt64:
5863 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005864 if (builder.isInSpecConstCodeGenMode()) {
5865 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005866 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5867 zero = builder.makeUint8Constant(0);
5868 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005869 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005870 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5871 zero = builder.makeUint64Constant(0);
5872 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005873 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005874 }
qining189b2032016-04-12 23:16:20 -04005875 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005876 // Use OpIAdd, instead of OpBitcast to do the conversion when
5877 // generating for OpSpecConstantOp instruction.
5878 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5879 }
5880 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005881 convOp = spv::OpBitcast;
5882 break;
5883
John Kessenich66011cb2018-03-06 16:12:04 -07005884 case glslang::EOpConvFloat16ToUint8:
5885 case glslang::EOpConvFloatToUint8:
5886 case glslang::EOpConvDoubleToUint8:
5887 case glslang::EOpConvFloat16ToUint16:
5888 case glslang::EOpConvFloatToUint16:
5889 case glslang::EOpConvDoubleToUint16:
5890 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005891 case glslang::EOpConvFloatToUint:
5892 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005893 case glslang::EOpConvFloatToUint64:
5894 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005895 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005896 convOp = spv::OpConvertFToU;
5897 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005898
John Kessenich66011cb2018-03-06 16:12:04 -07005899 case glslang::EOpConvInt8ToInt16:
5900 case glslang::EOpConvInt8ToInt:
5901 case glslang::EOpConvInt8ToInt64:
5902 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005903 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005904 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005905 case glslang::EOpConvIntToInt8:
5906 case glslang::EOpConvIntToInt16:
5907 case glslang::EOpConvIntToInt64:
5908 case glslang::EOpConvInt64ToInt8:
5909 case glslang::EOpConvInt64ToInt16:
5910 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005911 convOp = spv::OpSConvert;
5912 break;
5913
John Kessenich66011cb2018-03-06 16:12:04 -07005914 case glslang::EOpConvUint8ToUint16:
5915 case glslang::EOpConvUint8ToUint:
5916 case glslang::EOpConvUint8ToUint64:
5917 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005918 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005919 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005920 case glslang::EOpConvUintToUint8:
5921 case glslang::EOpConvUintToUint16:
5922 case glslang::EOpConvUintToUint64:
5923 case glslang::EOpConvUint64ToUint8:
5924 case glslang::EOpConvUint64ToUint16:
5925 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005926 convOp = spv::OpUConvert;
5927 break;
5928
John Kessenich66011cb2018-03-06 16:12:04 -07005929 case glslang::EOpConvInt8ToUint16:
5930 case glslang::EOpConvInt8ToUint:
5931 case glslang::EOpConvInt8ToUint64:
5932 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005933 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005934 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005935 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005936 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005937 case glslang::EOpConvIntToUint64:
5938 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005939 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005940 case glslang::EOpConvInt64ToUint:
5941 case glslang::EOpConvUint8ToInt16:
5942 case glslang::EOpConvUint8ToInt:
5943 case glslang::EOpConvUint8ToInt64:
5944 case glslang::EOpConvUint16ToInt8:
5945 case glslang::EOpConvUint16ToInt:
5946 case glslang::EOpConvUint16ToInt64:
5947 case glslang::EOpConvUintToInt8:
5948 case glslang::EOpConvUintToInt16:
5949 case glslang::EOpConvUintToInt64:
5950 case glslang::EOpConvUint64ToInt8:
5951 case glslang::EOpConvUint64ToInt16:
5952 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005953 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005954 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005955
5956 if (builder.isInSpecConstCodeGenMode()) {
5957 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005958 switch(op) {
5959 case glslang::EOpConvInt16ToUint8:
5960 case glslang::EOpConvIntToUint8:
5961 case glslang::EOpConvInt64ToUint8:
5962 case glslang::EOpConvUint16ToInt8:
5963 case glslang::EOpConvUintToInt8:
5964 case glslang::EOpConvUint64ToInt8:
5965 zero = builder.makeUint8Constant(0);
5966 break;
5967 case glslang::EOpConvInt8ToUint16:
5968 case glslang::EOpConvIntToUint16:
5969 case glslang::EOpConvInt64ToUint16:
5970 case glslang::EOpConvUint8ToInt16:
5971 case glslang::EOpConvUintToInt16:
5972 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005973 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005974 break;
5975 case glslang::EOpConvInt8ToUint:
5976 case glslang::EOpConvInt16ToUint:
5977 case glslang::EOpConvInt64ToUint:
5978 case glslang::EOpConvUint8ToInt:
5979 case glslang::EOpConvUint16ToInt:
5980 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005981 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005982 break;
5983 case glslang::EOpConvInt8ToUint64:
5984 case glslang::EOpConvInt16ToUint64:
5985 case glslang::EOpConvIntToUint64:
5986 case glslang::EOpConvUint8ToInt64:
5987 case glslang::EOpConvUint16ToInt64:
5988 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005989 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005990 break;
5991 default:
5992 assert(false && "Default missing");
5993 break;
5994 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005995 zero = makeSmearedConstant(zero, vectorSize);
5996 // Use OpIAdd, instead of OpBitcast to do the conversion when
5997 // generating for OpSpecConstantOp instruction.
5998 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5999 }
6000 // For normal run-time conversion instruction, use OpBitcast.
6001 convOp = spv::OpBitcast;
6002 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006003 case glslang::EOpConvUint64ToPtr:
6004 convOp = spv::OpConvertUToPtr;
6005 break;
6006 case glslang::EOpConvPtrToUint64:
6007 convOp = spv::OpConvertPtrToU;
6008 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006009 default:
6010 break;
6011 }
6012
6013 spv::Id result = 0;
6014 if (convOp == spv::OpNop)
6015 return result;
6016
6017 if (convOp == spv::OpSelect) {
6018 zero = makeSmearedConstant(zero, vectorSize);
6019 one = makeSmearedConstant(one, vectorSize);
6020 result = builder.createTriOp(convOp, destType, operand, one, zero);
6021 } else
6022 result = builder.createUnaryOp(convOp, destType, operand);
6023
John Kessenichead86222018-03-28 18:01:20 -06006024 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006025 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006026 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006027}
6028
6029spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6030{
6031 if (vectorSize == 0)
6032 return constant;
6033
6034 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6035 std::vector<spv::Id> components;
6036 for (int c = 0; c < vectorSize; ++c)
6037 components.push_back(constant);
6038 return builder.makeCompositeConstant(vectorTypeId, components);
6039}
6040
John Kessenich426394d2015-07-23 10:22:48 -06006041// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07006042spv::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 -06006043{
6044 spv::Op opCode = spv::OpNop;
6045
6046 switch (op) {
6047 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006048 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006049 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006050 opCode = spv::OpAtomicIAdd;
6051 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006052 case glslang::EOpAtomicCounterSubtract:
6053 opCode = spv::OpAtomicISub;
6054 break;
John Kessenich426394d2015-07-23 10:22:48 -06006055 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006056 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006057 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006058 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006059 break;
6060 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006061 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006062 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006063 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006064 break;
6065 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006066 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006067 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006068 opCode = spv::OpAtomicAnd;
6069 break;
6070 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006071 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006072 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006073 opCode = spv::OpAtomicOr;
6074 break;
6075 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006076 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006077 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006078 opCode = spv::OpAtomicXor;
6079 break;
6080 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006081 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006082 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006083 opCode = spv::OpAtomicExchange;
6084 break;
6085 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006086 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006087 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006088 opCode = spv::OpAtomicCompareExchange;
6089 break;
6090 case glslang::EOpAtomicCounterIncrement:
6091 opCode = spv::OpAtomicIIncrement;
6092 break;
6093 case glslang::EOpAtomicCounterDecrement:
6094 opCode = spv::OpAtomicIDecrement;
6095 break;
6096 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006097 case glslang::EOpImageAtomicLoad:
6098 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006099 opCode = spv::OpAtomicLoad;
6100 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006101 case glslang::EOpAtomicStore:
6102 case glslang::EOpImageAtomicStore:
6103 opCode = spv::OpAtomicStore;
6104 break;
John Kessenich426394d2015-07-23 10:22:48 -06006105 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006106 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006107 break;
6108 }
6109
Rex Xue8fe8b02017-09-26 15:42:56 +08006110 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6111 builder.addCapability(spv::CapabilityInt64Atomics);
6112
John Kessenich426394d2015-07-23 10:22:48 -06006113 // Sort out the operands
6114 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006115 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006116 // - compare-exchange swaps the value and comparator
6117 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006118 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006119 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6120 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6121 spv::Id scopeId;
6122 if (glslangIntermediate->usingVulkanMemoryModel()) {
6123 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6124 } else {
6125 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6126 }
6127 // semantics default to relaxed
6128 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
6129 spv::Id semanticsId2 = semanticsId;
6130
6131 pointerId = operands[0];
6132 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6133 // no additional operands
6134 } else if (opCode == spv::OpAtomicCompareExchange) {
6135 compareId = operands[1];
6136 valueId = operands[2];
6137 if (operands.size() > 3) {
6138 scopeId = operands[3];
6139 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6140 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6141 }
6142 } else if (opCode == spv::OpAtomicLoad) {
6143 if (operands.size() > 1) {
6144 scopeId = operands[1];
6145 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6146 }
6147 } else {
6148 // atomic store or RMW
6149 valueId = operands[1];
6150 if (operands.size() > 2) {
6151 scopeId = operands[2];
6152 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6153 }
Rex Xu04db3f52015-09-16 11:44:02 +08006154 }
John Kessenich426394d2015-07-23 10:22:48 -06006155
Jeff Bolz36831c92018-09-05 10:11:41 -05006156 // Check for capabilities
6157 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
6158 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6159 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6160 }
John Kessenich426394d2015-07-23 10:22:48 -06006161
Jeff Bolz36831c92018-09-05 10:11:41 -05006162 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6163 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6164 }
John Kessenich48d6e792017-10-06 21:21:48 -06006165
Jeff Bolz36831c92018-09-05 10:11:41 -05006166 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6167 spvAtomicOperands.push_back(pointerId);
6168 spvAtomicOperands.push_back(scopeId);
6169 spvAtomicOperands.push_back(semanticsId);
6170 if (opCode == spv::OpAtomicCompareExchange) {
6171 spvAtomicOperands.push_back(semanticsId2);
6172 spvAtomicOperands.push_back(valueId);
6173 spvAtomicOperands.push_back(compareId);
6174 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6175 spvAtomicOperands.push_back(valueId);
6176 }
John Kessenich48d6e792017-10-06 21:21:48 -06006177
Jeff Bolz36831c92018-09-05 10:11:41 -05006178 if (opCode == spv::OpAtomicStore) {
6179 builder.createNoResultOp(opCode, spvAtomicOperands);
6180 return 0;
6181 } else {
6182 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6183
6184 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6185 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6186 if (op == glslang::EOpAtomicCounterDecrement)
6187 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6188
6189 return resultId;
6190 }
John Kessenich426394d2015-07-23 10:22:48 -06006191}
6192
John Kessenich91cef522016-05-05 16:45:40 -06006193// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006194spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006195{
Corentin Walleze7061422018-08-08 15:20:15 +02006196#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006197 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6198 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006199#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006200
Rex Xu51596642016-09-21 18:56:12 +08006201 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006202 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006203 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6204
chaocf200da82016-12-20 12:44:35 -08006205 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6206 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006207 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6208 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006209 } else if (op == glslang::EOpAnyInvocation ||
6210 op == glslang::EOpAllInvocations ||
6211 op == glslang::EOpAllInvocationsEqual) {
6212 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6213 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006214 } else {
6215 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006216#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006217 if (op == glslang::EOpMinInvocationsNonUniform ||
6218 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006219 op == glslang::EOpAddInvocationsNonUniform ||
6220 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6221 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6222 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6223 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6224 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6225 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006226 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006227#endif
Rex Xu51596642016-09-21 18:56:12 +08006228
Rex Xu9d93a232016-05-05 12:30:44 +08006229#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006230 switch (op) {
6231 case glslang::EOpMinInvocations:
6232 case glslang::EOpMaxInvocations:
6233 case glslang::EOpAddInvocations:
6234 case glslang::EOpMinInvocationsNonUniform:
6235 case glslang::EOpMaxInvocationsNonUniform:
6236 case glslang::EOpAddInvocationsNonUniform:
6237 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006238 break;
6239 case glslang::EOpMinInvocationsInclusiveScan:
6240 case glslang::EOpMaxInvocationsInclusiveScan:
6241 case glslang::EOpAddInvocationsInclusiveScan:
6242 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6243 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6244 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6245 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006246 break;
6247 case glslang::EOpMinInvocationsExclusiveScan:
6248 case glslang::EOpMaxInvocationsExclusiveScan:
6249 case glslang::EOpAddInvocationsExclusiveScan:
6250 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6251 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6252 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6253 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006254 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006255 default:
6256 break;
Rex Xu430ef402016-10-14 17:22:23 +08006257 }
John Kessenich149afc32018-08-14 13:31:43 -06006258 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6259 spvGroupOperands.push_back(scope);
6260 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006261 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006262 spvGroupOperands.push_back(groupOp);
6263 }
Rex Xu9d93a232016-05-05 12:30:44 +08006264#endif
Rex Xu51596642016-09-21 18:56:12 +08006265 }
6266
John Kessenich149afc32018-08-14 13:31:43 -06006267 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6268 spv::IdImmediate op = { true, *opIt };
6269 spvGroupOperands.push_back(op);
6270 }
John Kessenich91cef522016-05-05 16:45:40 -06006271
6272 switch (op) {
6273 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006274 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006275 break;
John Kessenich91cef522016-05-05 16:45:40 -06006276 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006277 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006278 break;
John Kessenich91cef522016-05-05 16:45:40 -06006279 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006280 opCode = spv::OpSubgroupAllEqualKHR;
6281 break;
Rex Xu51596642016-09-21 18:56:12 +08006282 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006283 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006284 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006285 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006286 break;
6287 case glslang::EOpReadFirstInvocation:
6288 opCode = spv::OpSubgroupFirstInvocationKHR;
6289 break;
6290 case glslang::EOpBallot:
6291 {
6292 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6293 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6294 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6295 //
6296 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6297 //
6298 spv::Id uintType = builder.makeUintType(32);
6299 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6300 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6301
6302 std::vector<spv::Id> components;
6303 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6304 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6305
6306 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6307 return builder.createUnaryOp(spv::OpBitcast, typeId,
6308 builder.createCompositeConstruct(uvec2Type, components));
6309 }
6310
Rex Xu9d93a232016-05-05 12:30:44 +08006311#ifdef AMD_EXTENSIONS
6312 case glslang::EOpMinInvocations:
6313 case glslang::EOpMaxInvocations:
6314 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006315 case glslang::EOpMinInvocationsInclusiveScan:
6316 case glslang::EOpMaxInvocationsInclusiveScan:
6317 case glslang::EOpAddInvocationsInclusiveScan:
6318 case glslang::EOpMinInvocationsExclusiveScan:
6319 case glslang::EOpMaxInvocationsExclusiveScan:
6320 case glslang::EOpAddInvocationsExclusiveScan:
6321 if (op == glslang::EOpMinInvocations ||
6322 op == glslang::EOpMinInvocationsInclusiveScan ||
6323 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006324 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006325 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006326 else {
6327 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006328 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006329 else
Rex Xu51596642016-09-21 18:56:12 +08006330 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006331 }
Rex Xu430ef402016-10-14 17:22:23 +08006332 } else if (op == glslang::EOpMaxInvocations ||
6333 op == glslang::EOpMaxInvocationsInclusiveScan ||
6334 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006335 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006336 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006337 else {
6338 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006339 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006340 else
Rex Xu51596642016-09-21 18:56:12 +08006341 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006342 }
6343 } else {
6344 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006345 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006346 else
Rex Xu51596642016-09-21 18:56:12 +08006347 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006348 }
6349
Rex Xu2bbbe062016-08-23 15:41:05 +08006350 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006351 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006352
6353 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006354 case glslang::EOpMinInvocationsNonUniform:
6355 case glslang::EOpMaxInvocationsNonUniform:
6356 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006357 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6358 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6359 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6360 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6361 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6362 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6363 if (op == glslang::EOpMinInvocationsNonUniform ||
6364 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6365 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006366 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006367 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006368 else {
6369 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006370 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006371 else
Rex Xu51596642016-09-21 18:56:12 +08006372 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006373 }
6374 }
Rex Xu430ef402016-10-14 17:22:23 +08006375 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6376 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6377 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006378 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006379 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006380 else {
6381 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006382 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006383 else
Rex Xu51596642016-09-21 18:56:12 +08006384 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006385 }
6386 }
6387 else {
6388 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006389 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006390 else
Rex Xu51596642016-09-21 18:56:12 +08006391 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006392 }
6393
Rex Xu2bbbe062016-08-23 15:41:05 +08006394 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006395 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006396
6397 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006398#endif
John Kessenich91cef522016-05-05 16:45:40 -06006399 default:
6400 logger->missingFunctionality("invocation operation");
6401 return spv::NoResult;
6402 }
Rex Xu51596642016-09-21 18:56:12 +08006403
6404 assert(opCode != spv::OpNop);
6405 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006406}
6407
Rex Xu2bbbe062016-08-23 15:41:05 +08006408// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006409spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6410 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006411{
Rex Xub7072052016-09-26 15:53:40 +08006412#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006413 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6414 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006415 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006416 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006417 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6418 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6419 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006420#else
6421 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6422 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006423 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6424 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006425#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006426
6427 // Handle group invocation operations scalar by scalar.
6428 // The result type is the same type as the original type.
6429 // The algorithm is to:
6430 // - break the vector into scalars
6431 // - apply the operation to each scalar
6432 // - make a vector out the scalar results
6433
6434 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006435 int numComponents = builder.getNumComponents(operands[0]);
6436 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006437 std::vector<spv::Id> results;
6438
6439 // do each scalar op
6440 for (int comp = 0; comp < numComponents; ++comp) {
6441 std::vector<unsigned int> indexes;
6442 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006443 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6444 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006445 if (op == spv::OpSubgroupReadInvocationKHR) {
6446 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006447 spv::IdImmediate operand = { true, operands[1] };
6448 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006449 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006450 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6451 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006452 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006453 spv::IdImmediate operand = { true, operands[1] };
6454 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006455 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006456 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6457 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006458 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006459 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006460 spvGroupOperands.push_back(scalar);
6461 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006462
Rex Xub7072052016-09-26 15:53:40 +08006463 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006464 }
6465
6466 // put the pieces together
6467 return builder.createCompositeConstruct(typeId, results);
6468}
Rex Xu2bbbe062016-08-23 15:41:05 +08006469
John Kessenich66011cb2018-03-06 16:12:04 -07006470// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006471spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6472 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006473{
6474 // Add the required capabilities.
6475 switch (op) {
6476 case glslang::EOpSubgroupElect:
6477 builder.addCapability(spv::CapabilityGroupNonUniform);
6478 break;
6479 case glslang::EOpSubgroupAll:
6480 case glslang::EOpSubgroupAny:
6481 case glslang::EOpSubgroupAllEqual:
6482 builder.addCapability(spv::CapabilityGroupNonUniform);
6483 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6484 break;
6485 case glslang::EOpSubgroupBroadcast:
6486 case glslang::EOpSubgroupBroadcastFirst:
6487 case glslang::EOpSubgroupBallot:
6488 case glslang::EOpSubgroupInverseBallot:
6489 case glslang::EOpSubgroupBallotBitExtract:
6490 case glslang::EOpSubgroupBallotBitCount:
6491 case glslang::EOpSubgroupBallotInclusiveBitCount:
6492 case glslang::EOpSubgroupBallotExclusiveBitCount:
6493 case glslang::EOpSubgroupBallotFindLSB:
6494 case glslang::EOpSubgroupBallotFindMSB:
6495 builder.addCapability(spv::CapabilityGroupNonUniform);
6496 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6497 break;
6498 case glslang::EOpSubgroupShuffle:
6499 case glslang::EOpSubgroupShuffleXor:
6500 builder.addCapability(spv::CapabilityGroupNonUniform);
6501 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6502 break;
6503 case glslang::EOpSubgroupShuffleUp:
6504 case glslang::EOpSubgroupShuffleDown:
6505 builder.addCapability(spv::CapabilityGroupNonUniform);
6506 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6507 break;
6508 case glslang::EOpSubgroupAdd:
6509 case glslang::EOpSubgroupMul:
6510 case glslang::EOpSubgroupMin:
6511 case glslang::EOpSubgroupMax:
6512 case glslang::EOpSubgroupAnd:
6513 case glslang::EOpSubgroupOr:
6514 case glslang::EOpSubgroupXor:
6515 case glslang::EOpSubgroupInclusiveAdd:
6516 case glslang::EOpSubgroupInclusiveMul:
6517 case glslang::EOpSubgroupInclusiveMin:
6518 case glslang::EOpSubgroupInclusiveMax:
6519 case glslang::EOpSubgroupInclusiveAnd:
6520 case glslang::EOpSubgroupInclusiveOr:
6521 case glslang::EOpSubgroupInclusiveXor:
6522 case glslang::EOpSubgroupExclusiveAdd:
6523 case glslang::EOpSubgroupExclusiveMul:
6524 case glslang::EOpSubgroupExclusiveMin:
6525 case glslang::EOpSubgroupExclusiveMax:
6526 case glslang::EOpSubgroupExclusiveAnd:
6527 case glslang::EOpSubgroupExclusiveOr:
6528 case glslang::EOpSubgroupExclusiveXor:
6529 builder.addCapability(spv::CapabilityGroupNonUniform);
6530 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6531 break;
6532 case glslang::EOpSubgroupClusteredAdd:
6533 case glslang::EOpSubgroupClusteredMul:
6534 case glslang::EOpSubgroupClusteredMin:
6535 case glslang::EOpSubgroupClusteredMax:
6536 case glslang::EOpSubgroupClusteredAnd:
6537 case glslang::EOpSubgroupClusteredOr:
6538 case glslang::EOpSubgroupClusteredXor:
6539 builder.addCapability(spv::CapabilityGroupNonUniform);
6540 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6541 break;
6542 case glslang::EOpSubgroupQuadBroadcast:
6543 case glslang::EOpSubgroupQuadSwapHorizontal:
6544 case glslang::EOpSubgroupQuadSwapVertical:
6545 case glslang::EOpSubgroupQuadSwapDiagonal:
6546 builder.addCapability(spv::CapabilityGroupNonUniform);
6547 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6548 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006549#ifdef NV_EXTENSIONS
6550 case glslang::EOpSubgroupPartitionedAdd:
6551 case glslang::EOpSubgroupPartitionedMul:
6552 case glslang::EOpSubgroupPartitionedMin:
6553 case glslang::EOpSubgroupPartitionedMax:
6554 case glslang::EOpSubgroupPartitionedAnd:
6555 case glslang::EOpSubgroupPartitionedOr:
6556 case glslang::EOpSubgroupPartitionedXor:
6557 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6558 case glslang::EOpSubgroupPartitionedInclusiveMul:
6559 case glslang::EOpSubgroupPartitionedInclusiveMin:
6560 case glslang::EOpSubgroupPartitionedInclusiveMax:
6561 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6562 case glslang::EOpSubgroupPartitionedInclusiveOr:
6563 case glslang::EOpSubgroupPartitionedInclusiveXor:
6564 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6565 case glslang::EOpSubgroupPartitionedExclusiveMul:
6566 case glslang::EOpSubgroupPartitionedExclusiveMin:
6567 case glslang::EOpSubgroupPartitionedExclusiveMax:
6568 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6569 case glslang::EOpSubgroupPartitionedExclusiveOr:
6570 case glslang::EOpSubgroupPartitionedExclusiveXor:
6571 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6572 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6573 break;
6574#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006575 default: assert(0 && "Unhandled subgroup operation!");
6576 }
6577
6578 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6579 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6580 const bool isBool = typeProxy == glslang::EbtBool;
6581
6582 spv::Op opCode = spv::OpNop;
6583
6584 // Figure out which opcode to use.
6585 switch (op) {
6586 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6587 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6588 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6589 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6590 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6591 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6592 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6593 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6594 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6595 case glslang::EOpSubgroupBallotBitCount:
6596 case glslang::EOpSubgroupBallotInclusiveBitCount:
6597 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6598 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6599 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6600 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6601 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6602 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6603 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6604 case glslang::EOpSubgroupAdd:
6605 case glslang::EOpSubgroupInclusiveAdd:
6606 case glslang::EOpSubgroupExclusiveAdd:
6607 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006608#ifdef NV_EXTENSIONS
6609 case glslang::EOpSubgroupPartitionedAdd:
6610 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6611 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6612#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006613 if (isFloat) {
6614 opCode = spv::OpGroupNonUniformFAdd;
6615 } else {
6616 opCode = spv::OpGroupNonUniformIAdd;
6617 }
6618 break;
6619 case glslang::EOpSubgroupMul:
6620 case glslang::EOpSubgroupInclusiveMul:
6621 case glslang::EOpSubgroupExclusiveMul:
6622 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006623#ifdef NV_EXTENSIONS
6624 case glslang::EOpSubgroupPartitionedMul:
6625 case glslang::EOpSubgroupPartitionedInclusiveMul:
6626 case glslang::EOpSubgroupPartitionedExclusiveMul:
6627#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006628 if (isFloat) {
6629 opCode = spv::OpGroupNonUniformFMul;
6630 } else {
6631 opCode = spv::OpGroupNonUniformIMul;
6632 }
6633 break;
6634 case glslang::EOpSubgroupMin:
6635 case glslang::EOpSubgroupInclusiveMin:
6636 case glslang::EOpSubgroupExclusiveMin:
6637 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006638#ifdef NV_EXTENSIONS
6639 case glslang::EOpSubgroupPartitionedMin:
6640 case glslang::EOpSubgroupPartitionedInclusiveMin:
6641 case glslang::EOpSubgroupPartitionedExclusiveMin:
6642#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006643 if (isFloat) {
6644 opCode = spv::OpGroupNonUniformFMin;
6645 } else if (isUnsigned) {
6646 opCode = spv::OpGroupNonUniformUMin;
6647 } else {
6648 opCode = spv::OpGroupNonUniformSMin;
6649 }
6650 break;
6651 case glslang::EOpSubgroupMax:
6652 case glslang::EOpSubgroupInclusiveMax:
6653 case glslang::EOpSubgroupExclusiveMax:
6654 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006655#ifdef NV_EXTENSIONS
6656 case glslang::EOpSubgroupPartitionedMax:
6657 case glslang::EOpSubgroupPartitionedInclusiveMax:
6658 case glslang::EOpSubgroupPartitionedExclusiveMax:
6659#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006660 if (isFloat) {
6661 opCode = spv::OpGroupNonUniformFMax;
6662 } else if (isUnsigned) {
6663 opCode = spv::OpGroupNonUniformUMax;
6664 } else {
6665 opCode = spv::OpGroupNonUniformSMax;
6666 }
6667 break;
6668 case glslang::EOpSubgroupAnd:
6669 case glslang::EOpSubgroupInclusiveAnd:
6670 case glslang::EOpSubgroupExclusiveAnd:
6671 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006672#ifdef NV_EXTENSIONS
6673 case glslang::EOpSubgroupPartitionedAnd:
6674 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6675 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6676#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006677 if (isBool) {
6678 opCode = spv::OpGroupNonUniformLogicalAnd;
6679 } else {
6680 opCode = spv::OpGroupNonUniformBitwiseAnd;
6681 }
6682 break;
6683 case glslang::EOpSubgroupOr:
6684 case glslang::EOpSubgroupInclusiveOr:
6685 case glslang::EOpSubgroupExclusiveOr:
6686 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006687#ifdef NV_EXTENSIONS
6688 case glslang::EOpSubgroupPartitionedOr:
6689 case glslang::EOpSubgroupPartitionedInclusiveOr:
6690 case glslang::EOpSubgroupPartitionedExclusiveOr:
6691#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006692 if (isBool) {
6693 opCode = spv::OpGroupNonUniformLogicalOr;
6694 } else {
6695 opCode = spv::OpGroupNonUniformBitwiseOr;
6696 }
6697 break;
6698 case glslang::EOpSubgroupXor:
6699 case glslang::EOpSubgroupInclusiveXor:
6700 case glslang::EOpSubgroupExclusiveXor:
6701 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006702#ifdef NV_EXTENSIONS
6703 case glslang::EOpSubgroupPartitionedXor:
6704 case glslang::EOpSubgroupPartitionedInclusiveXor:
6705 case glslang::EOpSubgroupPartitionedExclusiveXor:
6706#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006707 if (isBool) {
6708 opCode = spv::OpGroupNonUniformLogicalXor;
6709 } else {
6710 opCode = spv::OpGroupNonUniformBitwiseXor;
6711 }
6712 break;
6713 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6714 case glslang::EOpSubgroupQuadSwapHorizontal:
6715 case glslang::EOpSubgroupQuadSwapVertical:
6716 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6717 default: assert(0 && "Unhandled subgroup operation!");
6718 }
6719
John Kessenich149afc32018-08-14 13:31:43 -06006720 // get the right Group Operation
6721 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006722 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006723 default:
6724 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006725 case glslang::EOpSubgroupBallotBitCount:
6726 case glslang::EOpSubgroupAdd:
6727 case glslang::EOpSubgroupMul:
6728 case glslang::EOpSubgroupMin:
6729 case glslang::EOpSubgroupMax:
6730 case glslang::EOpSubgroupAnd:
6731 case glslang::EOpSubgroupOr:
6732 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006733 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006734 break;
6735 case glslang::EOpSubgroupBallotInclusiveBitCount:
6736 case glslang::EOpSubgroupInclusiveAdd:
6737 case glslang::EOpSubgroupInclusiveMul:
6738 case glslang::EOpSubgroupInclusiveMin:
6739 case glslang::EOpSubgroupInclusiveMax:
6740 case glslang::EOpSubgroupInclusiveAnd:
6741 case glslang::EOpSubgroupInclusiveOr:
6742 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006743 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006744 break;
6745 case glslang::EOpSubgroupBallotExclusiveBitCount:
6746 case glslang::EOpSubgroupExclusiveAdd:
6747 case glslang::EOpSubgroupExclusiveMul:
6748 case glslang::EOpSubgroupExclusiveMin:
6749 case glslang::EOpSubgroupExclusiveMax:
6750 case glslang::EOpSubgroupExclusiveAnd:
6751 case glslang::EOpSubgroupExclusiveOr:
6752 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006753 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006754 break;
6755 case glslang::EOpSubgroupClusteredAdd:
6756 case glslang::EOpSubgroupClusteredMul:
6757 case glslang::EOpSubgroupClusteredMin:
6758 case glslang::EOpSubgroupClusteredMax:
6759 case glslang::EOpSubgroupClusteredAnd:
6760 case glslang::EOpSubgroupClusteredOr:
6761 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006762 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006763 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006764#ifdef NV_EXTENSIONS
6765 case glslang::EOpSubgroupPartitionedAdd:
6766 case glslang::EOpSubgroupPartitionedMul:
6767 case glslang::EOpSubgroupPartitionedMin:
6768 case glslang::EOpSubgroupPartitionedMax:
6769 case glslang::EOpSubgroupPartitionedAnd:
6770 case glslang::EOpSubgroupPartitionedOr:
6771 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006772 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006773 break;
6774 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6775 case glslang::EOpSubgroupPartitionedInclusiveMul:
6776 case glslang::EOpSubgroupPartitionedInclusiveMin:
6777 case glslang::EOpSubgroupPartitionedInclusiveMax:
6778 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6779 case glslang::EOpSubgroupPartitionedInclusiveOr:
6780 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006781 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006782 break;
6783 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6784 case glslang::EOpSubgroupPartitionedExclusiveMul:
6785 case glslang::EOpSubgroupPartitionedExclusiveMin:
6786 case glslang::EOpSubgroupPartitionedExclusiveMax:
6787 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6788 case glslang::EOpSubgroupPartitionedExclusiveOr:
6789 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006790 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006791 break;
6792#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006793 }
6794
John Kessenich149afc32018-08-14 13:31:43 -06006795 // build the instruction
6796 std::vector<spv::IdImmediate> spvGroupOperands;
6797
6798 // Every operation begins with the Execution Scope operand.
6799 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6800 spvGroupOperands.push_back(executionScope);
6801
6802 // Next, for all operations that use a Group Operation, push that as an operand.
6803 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006804 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006805 spvGroupOperands.push_back(groupOperand);
6806 }
6807
John Kessenich66011cb2018-03-06 16:12:04 -07006808 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006809 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6810 spv::IdImmediate operand = { true, *opIt };
6811 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006812 }
6813
6814 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006815 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006816 switch (op) {
6817 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006818 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6819 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6820 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6821 }
6822 if (directionId != spv::NoResult) {
6823 spv::IdImmediate direction = { true, directionId };
6824 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006825 }
6826
6827 return builder.createOp(opCode, typeId, spvGroupOperands);
6828}
6829
John Kessenich5e4b1242015-08-06 22:53:06 -06006830spv::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 -06006831{
John Kessenich66011cb2018-03-06 16:12:04 -07006832 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6833 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006834
John Kessenich140f3df2015-06-26 16:58:36 -06006835 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006836 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006837 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006838 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006839 spv::Id typeId0 = 0;
6840 if (consumedOperands > 0)
6841 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006842 spv::Id typeId1 = 0;
6843 if (consumedOperands > 1)
6844 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006845 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006846
6847 switch (op) {
6848 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006849 if (isFloat)
6850 libCall = spv::GLSLstd450FMin;
6851 else if (isUnsigned)
6852 libCall = spv::GLSLstd450UMin;
6853 else
6854 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006855 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006856 break;
6857 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006858 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006859 break;
6860 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006861 if (isFloat)
6862 libCall = spv::GLSLstd450FMax;
6863 else if (isUnsigned)
6864 libCall = spv::GLSLstd450UMax;
6865 else
6866 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006867 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006868 break;
6869 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006870 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006871 break;
6872 case glslang::EOpDot:
6873 opCode = spv::OpDot;
6874 break;
6875 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006876 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006877 break;
6878
6879 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006880 if (isFloat)
6881 libCall = spv::GLSLstd450FClamp;
6882 else if (isUnsigned)
6883 libCall = spv::GLSLstd450UClamp;
6884 else
6885 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006886 builder.promoteScalar(precision, operands.front(), operands[1]);
6887 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006888 break;
6889 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006890 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6891 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006892 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006893 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006894 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006895 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006896 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006897 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006898 break;
6899 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006900 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006901 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006902 break;
6903 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006904 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006905 builder.promoteScalar(precision, operands[0], operands[2]);
6906 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006907 break;
6908
6909 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006910 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006911 break;
6912 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006913 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006914 break;
6915 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006916 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006917 break;
6918 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006919 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006920 break;
6921 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006922 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006923 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006924 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006925#ifdef AMD_EXTENSIONS
6926 if (typeProxy == glslang::EbtFloat16)
6927 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6928#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006929 libCall = spv::GLSLstd450InterpolateAtSample;
6930 break;
6931 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006932#ifdef AMD_EXTENSIONS
6933 if (typeProxy == glslang::EbtFloat16)
6934 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6935#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006936 libCall = spv::GLSLstd450InterpolateAtOffset;
6937 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006938 case glslang::EOpAddCarry:
6939 opCode = spv::OpIAddCarry;
6940 typeId = builder.makeStructResultType(typeId0, typeId0);
6941 consumedOperands = 2;
6942 break;
6943 case glslang::EOpSubBorrow:
6944 opCode = spv::OpISubBorrow;
6945 typeId = builder.makeStructResultType(typeId0, typeId0);
6946 consumedOperands = 2;
6947 break;
6948 case glslang::EOpUMulExtended:
6949 opCode = spv::OpUMulExtended;
6950 typeId = builder.makeStructResultType(typeId0, typeId0);
6951 consumedOperands = 2;
6952 break;
6953 case glslang::EOpIMulExtended:
6954 opCode = spv::OpSMulExtended;
6955 typeId = builder.makeStructResultType(typeId0, typeId0);
6956 consumedOperands = 2;
6957 break;
6958 case glslang::EOpBitfieldExtract:
6959 if (isUnsigned)
6960 opCode = spv::OpBitFieldUExtract;
6961 else
6962 opCode = spv::OpBitFieldSExtract;
6963 break;
6964 case glslang::EOpBitfieldInsert:
6965 opCode = spv::OpBitFieldInsert;
6966 break;
6967
6968 case glslang::EOpFma:
6969 libCall = spv::GLSLstd450Fma;
6970 break;
6971 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006972 {
6973 libCall = spv::GLSLstd450FrexpStruct;
6974 assert(builder.isPointerType(typeId1));
6975 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006976 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006977#ifdef AMD_EXTENSIONS
6978 if (width == 16)
6979 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6980 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6981#endif
Rex Xu470026f2017-03-29 17:12:40 +08006982 if (builder.getNumComponents(operands[0]) == 1)
6983 frexpIntType = builder.makeIntegerType(width, true);
6984 else
6985 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6986 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6987 consumedOperands = 1;
6988 }
John Kessenich55e7d112015-11-15 21:33:39 -07006989 break;
6990 case glslang::EOpLdexp:
6991 libCall = spv::GLSLstd450Ldexp;
6992 break;
6993
Rex Xu574ab042016-04-14 16:53:07 +08006994 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006995 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006996
John Kessenich66011cb2018-03-06 16:12:04 -07006997 case glslang::EOpSubgroupBroadcast:
6998 case glslang::EOpSubgroupBallotBitExtract:
6999 case glslang::EOpSubgroupShuffle:
7000 case glslang::EOpSubgroupShuffleXor:
7001 case glslang::EOpSubgroupShuffleUp:
7002 case glslang::EOpSubgroupShuffleDown:
7003 case glslang::EOpSubgroupClusteredAdd:
7004 case glslang::EOpSubgroupClusteredMul:
7005 case glslang::EOpSubgroupClusteredMin:
7006 case glslang::EOpSubgroupClusteredMax:
7007 case glslang::EOpSubgroupClusteredAnd:
7008 case glslang::EOpSubgroupClusteredOr:
7009 case glslang::EOpSubgroupClusteredXor:
7010 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007011#ifdef NV_EXTENSIONS
7012 case glslang::EOpSubgroupPartitionedAdd:
7013 case glslang::EOpSubgroupPartitionedMul:
7014 case glslang::EOpSubgroupPartitionedMin:
7015 case glslang::EOpSubgroupPartitionedMax:
7016 case glslang::EOpSubgroupPartitionedAnd:
7017 case glslang::EOpSubgroupPartitionedOr:
7018 case glslang::EOpSubgroupPartitionedXor:
7019 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7020 case glslang::EOpSubgroupPartitionedInclusiveMul:
7021 case glslang::EOpSubgroupPartitionedInclusiveMin:
7022 case glslang::EOpSubgroupPartitionedInclusiveMax:
7023 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7024 case glslang::EOpSubgroupPartitionedInclusiveOr:
7025 case glslang::EOpSubgroupPartitionedInclusiveXor:
7026 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7027 case glslang::EOpSubgroupPartitionedExclusiveMul:
7028 case glslang::EOpSubgroupPartitionedExclusiveMin:
7029 case glslang::EOpSubgroupPartitionedExclusiveMax:
7030 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7031 case glslang::EOpSubgroupPartitionedExclusiveOr:
7032 case glslang::EOpSubgroupPartitionedExclusiveXor:
7033#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007034 return createSubgroupOperation(op, typeId, operands, typeProxy);
7035
Rex Xu9d93a232016-05-05 12:30:44 +08007036#ifdef AMD_EXTENSIONS
7037 case glslang::EOpSwizzleInvocations:
7038 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7039 libCall = spv::SwizzleInvocationsAMD;
7040 break;
7041 case glslang::EOpSwizzleInvocationsMasked:
7042 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7043 libCall = spv::SwizzleInvocationsMaskedAMD;
7044 break;
7045 case glslang::EOpWriteInvocation:
7046 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7047 libCall = spv::WriteInvocationAMD;
7048 break;
7049
7050 case glslang::EOpMin3:
7051 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7052 if (isFloat)
7053 libCall = spv::FMin3AMD;
7054 else {
7055 if (isUnsigned)
7056 libCall = spv::UMin3AMD;
7057 else
7058 libCall = spv::SMin3AMD;
7059 }
7060 break;
7061 case glslang::EOpMax3:
7062 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7063 if (isFloat)
7064 libCall = spv::FMax3AMD;
7065 else {
7066 if (isUnsigned)
7067 libCall = spv::UMax3AMD;
7068 else
7069 libCall = spv::SMax3AMD;
7070 }
7071 break;
7072 case glslang::EOpMid3:
7073 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7074 if (isFloat)
7075 libCall = spv::FMid3AMD;
7076 else {
7077 if (isUnsigned)
7078 libCall = spv::UMid3AMD;
7079 else
7080 libCall = spv::SMid3AMD;
7081 }
7082 break;
7083
7084 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007085 if (typeProxy == glslang::EbtFloat16)
7086 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007087 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7088 libCall = spv::InterpolateAtVertexAMD;
7089 break;
7090#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007091 case glslang::EOpBarrier:
7092 {
7093 // This is for the extended controlBarrier function, with four operands.
7094 // The unextended barrier() goes through createNoArgOperation.
7095 assert(operands.size() == 4);
7096 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7097 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7098 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7099 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7100 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7101 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7102 }
7103 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7104 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7105 }
7106 return 0;
7107 }
7108 break;
7109 case glslang::EOpMemoryBarrier:
7110 {
7111 // This is for the extended memoryBarrier function, with three operands.
7112 // The unextended memoryBarrier() goes through createNoArgOperation.
7113 assert(operands.size() == 3);
7114 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7115 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7116 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7117 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7118 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7119 }
7120 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7121 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7122 }
7123 return 0;
7124 }
7125 break;
Chao Chen3c366992018-09-19 11:41:59 -07007126
7127#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007128 case glslang::EOpReportIntersectionNV:
7129 {
7130 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007131 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007132 }
7133 break;
7134 case glslang::EOpTraceNV:
7135 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007136 builder.createNoResultOp(spv::OpTraceNV, operands);
7137 return 0;
7138 }
7139 break;
7140 case glslang::EOpExecuteCallableNV:
7141 {
7142 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007143 return 0;
7144 }
7145 break;
Chao Chen3c366992018-09-19 11:41:59 -07007146 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7147 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7148 return 0;
7149#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007150 case glslang::EOpCooperativeMatrixMulAdd:
7151 opCode = spv::OpCooperativeMatrixMulAddNV;
7152 break;
7153
John Kessenich140f3df2015-06-26 16:58:36 -06007154 default:
7155 return 0;
7156 }
7157
7158 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007159 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007160 // Use an extended instruction from the standard library.
7161 // Construct the call arguments, without modifying the original operands vector.
7162 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7163 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007164 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007165 } else if (opCode == spv::OpDot && !isFloat) {
7166 // int dot(int, int)
7167 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7168 const int componentCount = builder.getNumComponents(operands[0]);
7169 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7170 builder.setPrecision(mulOp, precision);
7171 id = builder.createCompositeExtract(mulOp, typeId, 0);
7172 for (int i = 1; i < componentCount; ++i) {
7173 builder.setPrecision(id, precision);
7174 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7175 }
John Kessenich2359bd02015-12-06 19:29:11 -07007176 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007177 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007178 case 0:
7179 // should all be handled by visitAggregate and createNoArgOperation
7180 assert(0);
7181 return 0;
7182 case 1:
7183 // should all be handled by createUnaryOperation
7184 assert(0);
7185 return 0;
7186 case 2:
7187 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7188 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007189 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007190 // anything 3 or over doesn't have l-value operands, so all should be consumed
7191 assert(consumedOperands == operands.size());
7192 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007193 break;
7194 }
7195 }
7196
John Kessenich55e7d112015-11-15 21:33:39 -07007197 // Decode the return types that were structures
7198 switch (op) {
7199 case glslang::EOpAddCarry:
7200 case glslang::EOpSubBorrow:
7201 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7202 id = builder.createCompositeExtract(id, typeId0, 0);
7203 break;
7204 case glslang::EOpUMulExtended:
7205 case glslang::EOpIMulExtended:
7206 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7207 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7208 break;
7209 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007210 {
7211 assert(operands.size() == 2);
7212 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7213 // "exp" is floating-point type (from HLSL intrinsic)
7214 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7215 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7216 builder.createStore(member1, operands[1]);
7217 } else
7218 // "exp" is integer type (from GLSL built-in function)
7219 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7220 id = builder.createCompositeExtract(id, typeId0, 0);
7221 }
John Kessenich55e7d112015-11-15 21:33:39 -07007222 break;
7223 default:
7224 break;
7225 }
7226
John Kessenich32cfd492016-02-02 12:37:46 -07007227 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007228}
7229
Rex Xu9d93a232016-05-05 12:30:44 +08007230// Intrinsics with no arguments (or no return value, and no precision).
7231spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007232{
Jeff Bolz36831c92018-09-05 10:11:41 -05007233 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7234 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007235
7236 switch (op) {
7237 case glslang::EOpEmitVertex:
7238 builder.createNoResultOp(spv::OpEmitVertex);
7239 return 0;
7240 case glslang::EOpEndPrimitive:
7241 builder.createNoResultOp(spv::OpEndPrimitive);
7242 return 0;
7243 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007244 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007245 if (glslangIntermediate->usingVulkanMemoryModel()) {
7246 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7247 spv::MemorySemanticsOutputMemoryKHRMask |
7248 spv::MemorySemanticsAcquireReleaseMask);
7249 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7250 } else {
7251 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7252 }
John Kessenich82979362017-12-11 04:02:24 -07007253 } else {
7254 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7255 spv::MemorySemanticsWorkgroupMemoryMask |
7256 spv::MemorySemanticsAcquireReleaseMask);
7257 }
John Kessenich140f3df2015-06-26 16:58:36 -06007258 return 0;
7259 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007260 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7261 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007262 return 0;
7263 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007264 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7265 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007266 return 0;
7267 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007268 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7269 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007270 return 0;
7271 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007272 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7273 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007274 return 0;
7275 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007276 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7277 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007278 return 0;
7279 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007280 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7281 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007282 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007283 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007284 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007285 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007286 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007287 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007288 case glslang::EOpDeviceMemoryBarrier:
7289 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7290 spv::MemorySemanticsImageMemoryMask |
7291 spv::MemorySemanticsAcquireReleaseMask);
7292 return 0;
7293 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7294 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7295 spv::MemorySemanticsImageMemoryMask |
7296 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007297 return 0;
7298 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007299 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7300 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007301 return 0;
7302 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007303 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7304 spv::MemorySemanticsWorkgroupMemoryMask |
7305 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007306 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007307 case glslang::EOpSubgroupBarrier:
7308 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7309 spv::MemorySemanticsAcquireReleaseMask);
7310 return spv::NoResult;
7311 case glslang::EOpSubgroupMemoryBarrier:
7312 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7313 spv::MemorySemanticsAcquireReleaseMask);
7314 return spv::NoResult;
7315 case glslang::EOpSubgroupMemoryBarrierBuffer:
7316 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7317 spv::MemorySemanticsAcquireReleaseMask);
7318 return spv::NoResult;
7319 case glslang::EOpSubgroupMemoryBarrierImage:
7320 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7321 spv::MemorySemanticsAcquireReleaseMask);
7322 return spv::NoResult;
7323 case glslang::EOpSubgroupMemoryBarrierShared:
7324 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7325 spv::MemorySemanticsAcquireReleaseMask);
7326 return spv::NoResult;
7327 case glslang::EOpSubgroupElect: {
7328 std::vector<spv::Id> operands;
7329 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7330 }
Rex Xu9d93a232016-05-05 12:30:44 +08007331#ifdef AMD_EXTENSIONS
7332 case glslang::EOpTime:
7333 {
7334 std::vector<spv::Id> args; // Dummy arguments
7335 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7336 return builder.setPrecision(id, precision);
7337 }
7338#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007339#ifdef NV_EXTENSIONS
7340 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007341 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007342 return 0;
7343 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007344 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007345 return 0;
7346#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007347 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007348 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007349 return 0;
7350 }
7351}
7352
7353spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7354{
John Kessenich2f273362015-07-18 22:34:27 -06007355 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007356 spv::Id id;
7357 if (symbolValues.end() != iter) {
7358 id = iter->second;
7359 return id;
7360 }
7361
7362 // it was not found, create it
7363 id = createSpvVariable(symbol);
7364 symbolValues[symbol->getId()] = id;
7365
Rex Xuc884b4a2016-06-29 15:03:44 +08007366 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007367 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7368 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7369 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007370#ifdef NV_EXTENSIONS
7371 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7372#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007373 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007374 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007375 if (symbol->getQualifier().hasIndex())
7376 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7377 if (symbol->getQualifier().hasComponent())
7378 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007379 // atomic counters use this:
7380 if (symbol->getQualifier().hasOffset())
7381 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007382 }
7383
scygan2c864272016-05-18 18:09:17 +02007384 if (symbol->getQualifier().hasLocation())
7385 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007386 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007387 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007388 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007389 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007390 }
John Kessenich140f3df2015-06-26 16:58:36 -06007391 if (symbol->getQualifier().hasSet())
7392 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007393 else if (IsDescriptorResource(symbol->getType())) {
7394 // default to 0
7395 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7396 }
John Kessenich140f3df2015-06-26 16:58:36 -06007397 if (symbol->getQualifier().hasBinding())
7398 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007399 else if (IsDescriptorResource(symbol->getType())) {
7400 // default to 0
7401 builder.addDecoration(id, spv::DecorationBinding, 0);
7402 }
John Kessenich6c292d32016-02-15 20:58:50 -07007403 if (symbol->getQualifier().hasAttachment())
7404 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007405 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007406 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007407 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007408 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007409 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7410 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7411 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7412 }
7413 if (symbol->getQualifier().hasXfbOffset())
7414 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007415 }
7416
Rex Xu1da878f2016-02-21 20:59:01 +08007417 if (symbol->getType().isImage()) {
7418 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007419 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007420 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007421 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007422 }
7423
John Kessenich140f3df2015-06-26 16:58:36 -06007424 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007425 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007426 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007427 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007428
John Kessenich5611c6d2018-04-05 11:25:02 -06007429 // nonuniform
7430 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7431
John Kessenichecba76f2017-01-06 00:34:48 -07007432#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007433 if (builtIn == spv::BuiltInSampleMask) {
7434 spv::Decoration decoration;
7435 // GL_NV_sample_mask_override_coverage extension
7436 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007437 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007438 else
7439 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007440 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007441 if (decoration != spv::DecorationMax) {
7442 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7443 }
7444 }
chaoc771d89f2017-01-13 01:10:53 -08007445 else if (builtIn == spv::BuiltInLayer) {
7446 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007447 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007448 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007449 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7450 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7451 }
John Kessenichb41bff62017-08-11 13:07:17 -06007452 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007453 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7454 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007455 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7456 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7457 }
7458 }
7459
chaoc6e5acae2016-12-20 13:28:52 -08007460 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007461 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007462 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007463 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7464 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007465 if (symbol->getQualifier().pervertexNV) {
7466 builder.addDecoration(id, spv::DecorationPerVertexNV);
7467 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7468 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7469 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007470#endif
7471
John Kessenich5d610ee2018-03-07 18:05:55 -07007472 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7473 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7474 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7475 symbol->getType().getQualifier().semanticName);
7476 }
7477
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007478 if (symbol->getBasicType() == glslang::EbtReference) {
7479 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7480 }
7481
John Kessenich140f3df2015-06-26 16:58:36 -06007482 return id;
7483}
7484
Chao Chen3c366992018-09-19 11:41:59 -07007485#ifdef NV_EXTENSIONS
7486// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7487void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7488{
7489 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007490 if (qualifier.perPrimitiveNV) {
7491 // Need to add capability/extension for fragment shader.
7492 // Mesh shader already adds this by default.
7493 if (glslangIntermediate->getStage() == EShLangFragment) {
7494 builder.addCapability(spv::CapabilityMeshShadingNV);
7495 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7496 }
Chao Chen3c366992018-09-19 11:41:59 -07007497 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007498 }
Chao Chen3c366992018-09-19 11:41:59 -07007499 if (qualifier.perViewNV)
7500 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7501 if (qualifier.perTaskNV)
7502 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7503 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007504 if (qualifier.perPrimitiveNV) {
7505 // Need to add capability/extension for fragment shader.
7506 // Mesh shader already adds this by default.
7507 if (glslangIntermediate->getStage() == EShLangFragment) {
7508 builder.addCapability(spv::CapabilityMeshShadingNV);
7509 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7510 }
Chao Chen3c366992018-09-19 11:41:59 -07007511 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007512 }
Chao Chen3c366992018-09-19 11:41:59 -07007513 if (qualifier.perViewNV)
7514 builder.addDecoration(id, spv::DecorationPerViewNV);
7515 if (qualifier.perTaskNV)
7516 builder.addDecoration(id, spv::DecorationPerTaskNV);
7517 }
7518}
7519#endif
7520
John Kessenich55e7d112015-11-15 21:33:39 -07007521// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007522// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007523//
7524// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7525//
7526// Recursively walk the nodes. The nodes form a tree whose leaves are
7527// regular constants, which themselves are trees that createSpvConstant()
7528// recursively walks. So, this function walks the "top" of the tree:
7529// - emit specialization constant-building instructions for specConstant
7530// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007531spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007532{
John Kessenich7cc0e282016-03-20 00:46:02 -06007533 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007534
qining4f4bb812016-04-03 23:55:17 -04007535 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007536 if (! node.getQualifier().specConstant) {
7537 // hand off to the non-spec-constant path
7538 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7539 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007540 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007541 nextConst, false);
7542 }
7543
7544 // We now know we have a specialization constant to build
7545
John Kessenichd94c0032016-05-30 19:29:40 -06007546 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007547 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7548 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7549 std::vector<spv::Id> dimConstId;
7550 for (int dim = 0; dim < 3; ++dim) {
7551 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7552 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007553 if (specConst) {
7554 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7555 glslangIntermediate->getLocalSizeSpecId(dim));
7556 }
qining4f4bb812016-04-03 23:55:17 -04007557 }
7558 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7559 }
7560
7561 // An AST node labelled as specialization constant should be a symbol node.
7562 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7563 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007564 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007565 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007566 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7567 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7568 // will set the builder into spec constant op instruction generating mode.
7569 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007570 result = accessChainLoad(sub_tree->getType());
7571 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007572 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007573 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007574 } else {
7575 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007576 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007577 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007578 builder.addName(result, sn->getName().c_str());
7579 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007580 }
qining4f4bb812016-04-03 23:55:17 -04007581
7582 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7583 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007584 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007585 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007586}
7587
John Kessenich140f3df2015-06-26 16:58:36 -06007588// Use 'consts' as the flattened glslang source of scalar constants to recursively
7589// build the aggregate SPIR-V constant.
7590//
7591// If there are not enough elements present in 'consts', 0 will be substituted;
7592// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7593//
qining08408382016-03-21 09:51:37 -04007594spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007595{
7596 // vector of constants for SPIR-V
7597 std::vector<spv::Id> spvConsts;
7598
7599 // Type is used for struct and array constants
7600 spv::Id typeId = convertGlslangToSpvType(glslangType);
7601
7602 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007603 glslang::TType elementType(glslangType, 0);
7604 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007605 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007606 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007607 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007608 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007609 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007610 } else if (glslangType.isCoopMat()) {
7611 glslang::TType componentType(glslangType.getBasicType());
7612 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007613 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007614 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7615 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007616 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007617 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007618 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7619 bool zero = nextConst >= consts.size();
7620 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007621 case glslang::EbtInt8:
7622 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7623 break;
7624 case glslang::EbtUint8:
7625 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7626 break;
7627 case glslang::EbtInt16:
7628 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7629 break;
7630 case glslang::EbtUint16:
7631 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7632 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007633 case glslang::EbtInt:
7634 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7635 break;
7636 case glslang::EbtUint:
7637 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7638 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007639 case glslang::EbtInt64:
7640 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7641 break;
7642 case glslang::EbtUint64:
7643 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7644 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007645 case glslang::EbtFloat:
7646 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7647 break;
7648 case glslang::EbtDouble:
7649 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7650 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007651 case glslang::EbtFloat16:
7652 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7653 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007654 case glslang::EbtBool:
7655 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7656 break;
7657 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007658 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007659 break;
7660 }
7661 ++nextConst;
7662 }
7663 } else {
7664 // we have a non-aggregate (scalar) constant
7665 bool zero = nextConst >= consts.size();
7666 spv::Id scalar = 0;
7667 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007668 case glslang::EbtInt8:
7669 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7670 break;
7671 case glslang::EbtUint8:
7672 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7673 break;
7674 case glslang::EbtInt16:
7675 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7676 break;
7677 case glslang::EbtUint16:
7678 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7679 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007680 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007681 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007682 break;
7683 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007684 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007685 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007686 case glslang::EbtInt64:
7687 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7688 break;
7689 case glslang::EbtUint64:
7690 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7691 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007692 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007693 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007694 break;
7695 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007696 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007697 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007698 case glslang::EbtFloat16:
7699 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7700 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007701 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007702 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007703 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007704 case glslang::EbtReference:
7705 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7706 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7707 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007708 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007709 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007710 break;
7711 }
7712 ++nextConst;
7713 return scalar;
7714 }
7715
7716 return builder.makeCompositeConstant(typeId, spvConsts);
7717}
7718
John Kessenich7c1aa102015-10-15 13:29:11 -06007719// Return true if the node is a constant or symbol whose reading has no
7720// non-trivial observable cost or effect.
7721bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7722{
7723 // don't know what this is
7724 if (node == nullptr)
7725 return false;
7726
7727 // a constant is safe
7728 if (node->getAsConstantUnion() != nullptr)
7729 return true;
7730
7731 // not a symbol means non-trivial
7732 if (node->getAsSymbolNode() == nullptr)
7733 return false;
7734
7735 // a symbol, depends on what's being read
7736 switch (node->getType().getQualifier().storage) {
7737 case glslang::EvqTemporary:
7738 case glslang::EvqGlobal:
7739 case glslang::EvqIn:
7740 case glslang::EvqInOut:
7741 case glslang::EvqConst:
7742 case glslang::EvqConstReadOnly:
7743 case glslang::EvqUniform:
7744 return true;
7745 default:
7746 return false;
7747 }
qining25262b32016-05-06 17:25:16 -04007748}
John Kessenich7c1aa102015-10-15 13:29:11 -06007749
7750// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007751// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007752// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007753// Return true if trivial.
7754bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7755{
7756 if (node == nullptr)
7757 return false;
7758
John Kessenich84cc15f2017-05-24 16:44:47 -06007759 // count non scalars as trivial, as well as anything coming from HLSL
7760 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007761 return true;
7762
John Kessenich7c1aa102015-10-15 13:29:11 -06007763 // symbols and constants are trivial
7764 if (isTrivialLeaf(node))
7765 return true;
7766
7767 // otherwise, it needs to be a simple operation or one or two leaf nodes
7768
7769 // not a simple operation
7770 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7771 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7772 if (binaryNode == nullptr && unaryNode == nullptr)
7773 return false;
7774
7775 // not on leaf nodes
7776 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7777 return false;
7778
7779 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7780 return false;
7781 }
7782
7783 switch (node->getAsOperator()->getOp()) {
7784 case glslang::EOpLogicalNot:
7785 case glslang::EOpConvIntToBool:
7786 case glslang::EOpConvUintToBool:
7787 case glslang::EOpConvFloatToBool:
7788 case glslang::EOpConvDoubleToBool:
7789 case glslang::EOpEqual:
7790 case glslang::EOpNotEqual:
7791 case glslang::EOpLessThan:
7792 case glslang::EOpGreaterThan:
7793 case glslang::EOpLessThanEqual:
7794 case glslang::EOpGreaterThanEqual:
7795 case glslang::EOpIndexDirect:
7796 case glslang::EOpIndexDirectStruct:
7797 case glslang::EOpLogicalXor:
7798 case glslang::EOpAny:
7799 case glslang::EOpAll:
7800 return true;
7801 default:
7802 return false;
7803 }
7804}
7805
7806// Emit short-circuiting code, where 'right' is never evaluated unless
7807// the left side is true (for &&) or false (for ||).
7808spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7809{
7810 spv::Id boolTypeId = builder.makeBoolType();
7811
7812 // emit left operand
7813 builder.clearAccessChain();
7814 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007815 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007816
7817 // Operands to accumulate OpPhi operands
7818 std::vector<spv::Id> phiOperands;
7819 // accumulate left operand's phi information
7820 phiOperands.push_back(leftId);
7821 phiOperands.push_back(builder.getBuildPoint()->getId());
7822
7823 // Make the two kinds of operation symmetric with a "!"
7824 // || => emit "if (! left) result = right"
7825 // && => emit "if ( left) result = right"
7826 //
7827 // TODO: this runtime "not" for || could be avoided by adding functionality
7828 // to 'builder' to have an "else" without an "then"
7829 if (op == glslang::EOpLogicalOr)
7830 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7831
7832 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007833 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007834
7835 // emit right operand as the "then" part of the "if"
7836 builder.clearAccessChain();
7837 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007838 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007839
7840 // accumulate left operand's phi information
7841 phiOperands.push_back(rightId);
7842 phiOperands.push_back(builder.getBuildPoint()->getId());
7843
7844 // finish the "if"
7845 ifBuilder.makeEndIf();
7846
7847 // phi together the two results
7848 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7849}
7850
Frank Henigman541f7bb2018-01-16 00:18:26 -05007851#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007852// Return type Id of the imported set of extended instructions corresponds to the name.
7853// Import this set if it has not been imported yet.
7854spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7855{
7856 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7857 return extBuiltinMap[name];
7858 else {
Rex Xu51596642016-09-21 18:56:12 +08007859 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007860 spv::Id extBuiltins = builder.import(name);
7861 extBuiltinMap[name] = extBuiltins;
7862 return extBuiltins;
7863 }
7864}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007865#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007866
John Kessenich140f3df2015-06-26 16:58:36 -06007867}; // end anonymous namespace
7868
7869namespace glslang {
7870
John Kessenich68d78fd2015-07-12 19:28:10 -06007871void GetSpirvVersion(std::string& version)
7872{
John Kessenich9e55f632015-07-15 10:03:39 -06007873 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007874 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007875 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007876 version = buf;
7877}
7878
John Kessenicha372a3e2017-11-02 22:32:14 -06007879// For low-order part of the generator's magic number. Bump up
7880// when there is a change in the style (e.g., if SSA form changes,
7881// or a different instruction sequence to do something gets used).
7882int GetSpirvGeneratorVersion()
7883{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007884 // return 1; // start
7885 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007886 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007887 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007888 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007889 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7890 // versions 4 and 6 each generate OpArrayLength as it has long been done
7891 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007892}
7893
John Kessenich140f3df2015-06-26 16:58:36 -06007894// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007895void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007896{
7897 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007898 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007899 if (out.fail())
7900 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007901 for (int i = 0; i < (int)spirv.size(); ++i) {
7902 unsigned int word = spirv[i];
7903 out.write((const char*)&word, 4);
7904 }
7905 out.close();
7906}
7907
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007908// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007909void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007910{
7911 std::ofstream out;
7912 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007913 if (out.fail())
7914 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007915 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007916 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007917 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007918 if (varName != nullptr) {
7919 out << "\t #pragma once" << std::endl;
7920 out << "const uint32_t " << varName << "[] = {" << std::endl;
7921 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007922 const int WORDS_PER_LINE = 8;
7923 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7924 out << "\t";
7925 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7926 const unsigned int word = spirv[i + j];
7927 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7928 if (i + j + 1 < (int)spirv.size()) {
7929 out << ",";
7930 }
7931 }
7932 out << std::endl;
7933 }
Flavio15017db2017-02-15 14:29:33 -08007934 if (varName != nullptr) {
7935 out << "};";
7936 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007937 out.close();
7938}
7939
John Kessenich140f3df2015-06-26 16:58:36 -06007940//
7941// Set up the glslang traversal
7942//
John Kessenich4e11b612018-08-30 16:56:59 -06007943void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007944{
Lei Zhang17535f72016-05-04 15:55:59 -04007945 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007946 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007947}
7948
John Kessenich4e11b612018-08-30 16:56:59 -06007949void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007950 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007951{
John Kessenich140f3df2015-06-26 16:58:36 -06007952 TIntermNode* root = intermediate.getTreeRoot();
7953
7954 if (root == 0)
7955 return;
7956
John Kessenich4e11b612018-08-30 16:56:59 -06007957 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007958 if (options == nullptr)
7959 options = &defaultOptions;
7960
John Kessenich4e11b612018-08-30 16:56:59 -06007961 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007962
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007963 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007964 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007965 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007966 it.dumpSpv(spirv);
7967
GregFfb03a552018-03-29 11:49:14 -06007968#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007969 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7970 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007971 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007972 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007973
John Kessenich4e11b612018-08-30 16:56:59 -06007974 if (options->validate)
7975 SpirvToolsValidate(intermediate, spirv, logger);
7976
John Kessenich717c80a2018-08-23 15:17:10 -06007977 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007978 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007979
GregFcd1f1692017-09-21 18:40:22 -06007980#endif
7981
John Kessenich4e11b612018-08-30 16:56:59 -06007982 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06007983}
7984
7985}; // end namespace glslang