blob: 4ef6cd7fc1dce33e50e7f2005c215bfc1f71adb8 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
John Kessenichb23d2322018-12-14 10:47:35 -07003// Copyright (C) 2015-2018 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080051#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080052 #include "GLSL.ext.NV.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
qining4c912612016-04-01 10:35:16 -040071namespace {
72class SpecConstantOpModeGuard {
73public:
74 SpecConstantOpModeGuard(spv::Builder* builder)
75 : builder_(builder) {
76 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040077 }
78 ~SpecConstantOpModeGuard() {
79 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
80 : builder_->setToNormalCodeGenMode();
81 }
qining40887662016-04-03 22:20:42 -040082 void turnOnSpecConstantOpMode() {
83 builder_->setToSpecConstCodeGenMode();
84 }
qining4c912612016-04-01 10:35:16 -040085
86private:
87 spv::Builder* builder_;
88 bool previous_flag_;
89};
John Kessenichead86222018-03-28 18:01:20 -060090
91struct OpDecorations {
92 spv::Decoration precision;
93 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -060094 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -060095};
96
97} // namespace
qining4c912612016-04-01 10:35:16 -040098
John Kessenich140f3df2015-06-26 16:58:36 -060099//
100// The main holder of information for translating glslang to SPIR-V.
101//
102// Derives from the AST walking base class.
103//
104class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
105public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700106 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
107 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700108 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600109
110 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
111 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
112 void visitConstantUnion(glslang::TIntermConstantUnion*);
113 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
114 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
115 void visitSymbol(glslang::TIntermSymbol* symbol);
116 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
117 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
118 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
119
John Kessenichfca82622016-11-26 13:23:20 -0700120 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700121 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600122
123protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700124 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
125 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
126
Rex Xu17ff3432016-10-14 17:41:45 +0800127 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800128 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600129 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500130 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
131 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
132 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
133 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100134 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700135 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700136 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
137 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700138 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600139 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600140 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John 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,
John Kessenich1f4d0462019-01-12 17:31:41 +07001058 std::vector<unsigned int>& operands) 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;
John Kessenich1f4d0462019-01-12 17:31:41 +07001070 operands.push_back((unsigned int)loopNode.getLoopDependency());
1071 }
1072 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1073 if (loopNode.getMinIterations() > 0) {
1074 control = control | spv::LoopControlMinIterationsMask;
1075 operands.push_back(loopNode.getMinIterations());
1076 }
1077 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1078 control = control | spv::LoopControlMaxIterationsMask;
1079 operands.push_back(loopNode.getMaxIterations());
1080 }
1081 if (loopNode.getIterationMultiple() > 1) {
1082 control = control | spv::LoopControlIterationMultipleMask;
1083 operands.push_back(loopNode.getIterationMultiple());
1084 }
1085 if (loopNode.getPeelCount() > 0) {
1086 control = control | spv::LoopControlPeelCountMask;
1087 operands.push_back(loopNode.getPeelCount());
1088 }
1089 if (loopNode.getPartialCount() > 0) {
1090 control = control | spv::LoopControlPartialCountMask;
1091 operands.push_back(loopNode.getPartialCount());
1092 }
John Kessenicha2858d92018-01-31 08:11:18 -07001093 }
John Kesseniche18fd202018-01-30 11:01:39 -07001094
1095 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001096}
1097
John Kessenicha5c5fb62017-05-05 05:09:58 -06001098// Translate glslang type to SPIR-V storage class.
1099spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1100{
1101 if (type.getQualifier().isPipeInput())
1102 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001103 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001104 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001105
1106 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1107 type.getQualifier().storage == glslang::EvqUniform) {
1108 if (type.getBasicType() == glslang::EbtAtomicUint)
1109 return spv::StorageClassAtomicCounter;
1110 if (type.containsOpaque())
1111 return spv::StorageClassUniformConstant;
1112 }
1113
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001114#ifdef NV_EXTENSIONS
1115 if (type.getQualifier().isUniformOrBuffer() &&
1116 type.getQualifier().layoutShaderRecordNV) {
1117 return spv::StorageClassShaderRecordBufferNV;
1118 }
1119#endif
1120
John Kessenichbed4e4f2017-09-08 02:38:07 -06001121 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001122 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001123 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001124 }
1125
1126 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001127 if (type.getQualifier().layoutPushConstant)
1128 return spv::StorageClassPushConstant;
1129 if (type.getBasicType() == glslang::EbtBlock)
1130 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001131 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001132 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001133
1134 switch (type.getQualifier().storage) {
1135 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1136 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1137 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1138 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001139#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001140 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1141 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1142 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1143 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1144 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001145#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001146 default:
1147 assert(0);
1148 break;
1149 }
1150
1151 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001152}
1153
John Kessenich5611c6d2018-04-05 11:25:02 -06001154// Add capabilities pertaining to how an array is indexed.
1155void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1156 const glslang::TType& indexType)
1157{
1158 if (indexType.getQualifier().isNonUniform()) {
1159 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001160 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001161 if (baseType.getBasicType() == glslang::EbtSampler) {
1162 if (baseType.getQualifier().hasAttachment())
1163 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1164 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1165 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1166 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1167 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1168 else if (baseType.isImage())
1169 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1170 else if (baseType.isTexture())
1171 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1172 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1173 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1174 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1175 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1176 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1177 }
1178 } else {
1179 // assume a dynamically uniform index
1180 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001181 if (baseType.getQualifier().hasAttachment()) {
1182 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001183 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001184 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1185 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001186 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001187 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1188 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001189 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001190 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001191 }
1192 }
1193}
1194
qining25262b32016-05-06 17:25:16 -04001195// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001196// descriptor set.
1197bool IsDescriptorResource(const glslang::TType& type)
1198{
John Kessenichf7497e22016-03-08 21:36:22 -07001199 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001200 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001201 return type.getQualifier().isUniformOrBuffer() &&
1202#ifdef NV_EXTENSIONS
1203 ! type.getQualifier().layoutShaderRecordNV &&
1204#endif
1205 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001206
1207 // non block...
1208 // basically samplerXXX/subpass/sampler/texture are all included
1209 // if they are the global-scope-class, not the function parameter
1210 // (or local, if they ever exist) class.
1211 if (type.getBasicType() == glslang::EbtSampler)
1212 return type.getQualifier().isUniformOrBuffer();
1213
1214 // None of the above.
1215 return false;
1216}
1217
John Kesseniche0b6cad2015-12-24 10:30:13 -07001218void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1219{
1220 if (child.layoutMatrix == glslang::ElmNone)
1221 child.layoutMatrix = parent.layoutMatrix;
1222
1223 if (parent.invariant)
1224 child.invariant = true;
1225 if (parent.nopersp)
1226 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001227#ifdef AMD_EXTENSIONS
1228 if (parent.explicitInterp)
1229 child.explicitInterp = true;
1230#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001231 if (parent.flat)
1232 child.flat = true;
1233 if (parent.centroid)
1234 child.centroid = true;
1235 if (parent.patch)
1236 child.patch = true;
1237 if (parent.sample)
1238 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001239 if (parent.coherent)
1240 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001241 if (parent.devicecoherent)
1242 child.devicecoherent = true;
1243 if (parent.queuefamilycoherent)
1244 child.queuefamilycoherent = true;
1245 if (parent.workgroupcoherent)
1246 child.workgroupcoherent = true;
1247 if (parent.subgroupcoherent)
1248 child.subgroupcoherent = true;
1249 if (parent.nonprivate)
1250 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001251 if (parent.volatil)
1252 child.volatil = true;
1253 if (parent.restrict)
1254 child.restrict = true;
1255 if (parent.readonly)
1256 child.readonly = true;
1257 if (parent.writeonly)
1258 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001259#ifdef NV_EXTENSIONS
1260 if (parent.perPrimitiveNV)
1261 child.perPrimitiveNV = true;
1262 if (parent.perViewNV)
1263 child.perViewNV = true;
1264 if (parent.perTaskNV)
1265 child.perTaskNV = true;
1266#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001267}
1268
John Kessenichf2b7f332016-09-01 17:05:23 -06001269bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001270{
John Kessenich7b9fa252016-01-21 18:56:57 -07001271 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001272 // - struct members might inherit from a struct declaration
1273 // (note that non-block structs don't explicitly inherit,
1274 // only implicitly, meaning no decoration involved)
1275 // - affect decorations on the struct members
1276 // (note smooth does not, and expecting something like volatile
1277 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001278 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001279 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001280}
1281
John Kessenich140f3df2015-06-26 16:58:36 -06001282//
1283// Implement the TGlslangToSpvTraverser class.
1284//
1285
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001286TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001287 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1288 : TIntermTraverser(true, false, true),
1289 options(options),
1290 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001291 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001292 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001293 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001294 glslangIntermediate(glslangIntermediate)
1295{
1296 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1297
1298 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001299 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1300 glslangIntermediate->getVersion());
1301
John Kessenich121853f2017-05-31 17:11:16 -06001302 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001303 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001304 builder.setSourceFile(glslangIntermediate->getSourceFile());
1305
1306 // Set the source shader's text. If for SPV version 1.0, include
1307 // a preamble in comments stating the OpModuleProcessed instructions.
1308 // Otherwise, emit those as actual instructions.
1309 std::string text;
1310 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1311 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001312 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001313 text.append("// OpModuleProcessed ");
1314 text.append(processes[p]);
1315 text.append("\n");
1316 } else
1317 builder.addModuleProcessed(processes[p]);
1318 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001319 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001320 text.append("#line 1\n");
1321 text.append(glslangIntermediate->getSourceText());
1322 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001323 // Pass name and text for all included files
1324 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1325 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1326 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001327 }
John Kessenich140f3df2015-06-26 16:58:36 -06001328 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001329
1330 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1331 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1332
1333 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1334 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1335 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1336 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1337 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001338 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001339 memoryModel = spv::MemoryModelVulkanKHR;
1340 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001341 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001342 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001343 builder.setMemoryModel(addressingModel, memoryModel);
1344
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001345 if (glslangIntermediate->usingVariablePointers()) {
1346 builder.addCapability(spv::CapabilityVariablePointers);
1347 }
1348
John Kessenicheee9d532016-09-19 18:09:30 -06001349 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1350 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001351
1352 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001353 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1354 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001355 builder.addSourceExtension(it->c_str());
1356
1357 // Add the top-level modes for this shader.
1358
John Kessenich92187592016-02-01 13:45:25 -07001359 if (glslangIntermediate->getXfbMode()) {
1360 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001361 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001362 }
John Kessenich140f3df2015-06-26 16:58:36 -06001363
1364 unsigned int mode;
1365 switch (glslangIntermediate->getStage()) {
1366 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001367 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001368 break;
1369
steve-lunarge7412492017-03-23 11:56:07 -06001370 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001371 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001372 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001373
steve-lunarge7412492017-03-23 11:56:07 -06001374 glslang::TLayoutGeometry primitive;
1375
1376 if (glslangIntermediate->getStage() == EShLangTessControl) {
1377 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1378 primitive = glslangIntermediate->getOutputPrimitive();
1379 } else {
1380 primitive = glslangIntermediate->getInputPrimitive();
1381 }
1382
1383 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001384 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1385 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1386 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001387 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001388 }
John Kessenich4016e382016-07-15 11:53:56 -06001389 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001390 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1391
John Kesseniche6903322015-10-13 16:29:02 -06001392 switch (glslangIntermediate->getVertexSpacing()) {
1393 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1394 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1395 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001396 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001397 }
John Kessenich4016e382016-07-15 11:53:56 -06001398 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001399 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1400
1401 switch (glslangIntermediate->getVertexOrder()) {
1402 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1403 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001404 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001405 }
John Kessenich4016e382016-07-15 11:53:56 -06001406 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001407 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1408
1409 if (glslangIntermediate->getPointMode())
1410 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001411 break;
1412
1413 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001414 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001415 switch (glslangIntermediate->getInputPrimitive()) {
1416 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1417 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1418 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001419 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001420 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001421 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001422 }
John Kessenich4016e382016-07-15 11:53:56 -06001423 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001424 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001425
John Kessenich140f3df2015-06-26 16:58:36 -06001426 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1427
1428 switch (glslangIntermediate->getOutputPrimitive()) {
1429 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1430 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1431 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001432 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001433 }
John Kessenich4016e382016-07-15 11:53:56 -06001434 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001435 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1436 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1437 break;
1438
1439 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001440 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001441 if (glslangIntermediate->getPixelCenterInteger())
1442 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001443
John Kessenich140f3df2015-06-26 16:58:36 -06001444 if (glslangIntermediate->getOriginUpperLeft())
1445 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001446 else
1447 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001448
1449 if (glslangIntermediate->getEarlyFragmentTests())
1450 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1451
chaocc1204522017-06-30 17:14:30 -07001452 if (glslangIntermediate->getPostDepthCoverage()) {
1453 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1454 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1455 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1456 }
1457
John Kesseniche6903322015-10-13 16:29:02 -06001458 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001459 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1460 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001461 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001462 }
John Kessenich4016e382016-07-15 11:53:56 -06001463 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001464 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1465
1466 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1467 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001468 break;
1469
1470 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001471 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001472 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1473 glslangIntermediate->getLocalSize(1),
1474 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001475#ifdef NV_EXTENSIONS
1476 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1477 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1478 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1479 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1480 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1481 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1482 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1483 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1484 }
1485#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001486 break;
1487
Chao Chen3c366992018-09-19 11:41:59 -07001488#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001489 case EShLangRayGenNV:
1490 case EShLangIntersectNV:
1491 case EShLangAnyHitNV:
1492 case EShLangClosestHitNV:
1493 case EShLangMissNV:
1494 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001495 builder.addCapability(spv::CapabilityRayTracingNV);
1496 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001497 break;
Chao Chen3c366992018-09-19 11:41:59 -07001498 case EShLangTaskNV:
1499 case EShLangMeshNV:
1500 builder.addCapability(spv::CapabilityMeshShadingNV);
1501 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1502 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1503 glslangIntermediate->getLocalSize(1),
1504 glslangIntermediate->getLocalSize(2));
1505 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1506 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1507 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1508
1509 switch (glslangIntermediate->getOutputPrimitive()) {
1510 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1511 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1512 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1513 default: mode = spv::ExecutionModeMax; break;
1514 }
1515 if (mode != spv::ExecutionModeMax)
1516 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1517 }
1518 break;
1519#endif
1520
John Kessenich140f3df2015-06-26 16:58:36 -06001521 default:
1522 break;
1523 }
John Kessenich140f3df2015-06-26 16:58:36 -06001524}
1525
John Kessenichfca82622016-11-26 13:23:20 -07001526// Finish creating SPV, after the traversal is complete.
1527void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001528{
John Kessenichf04c51b2018-08-03 15:56:12 -06001529 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001530 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001531 builder.setBuildPoint(shaderEntry->getLastBlock());
1532 builder.leaveFunction();
1533 }
1534
John Kessenich7ba63412015-12-20 17:37:07 -07001535 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001536 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1537 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001538
John Kessenichf04c51b2018-08-03 15:56:12 -06001539 // Add capabilities, extensions, remove unneeded decorations, etc.,
1540 // based on the resulting SPIR-V.
1541 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001542}
1543
John Kessenichfca82622016-11-26 13:23:20 -07001544// Write the SPV into 'out'.
1545void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001546{
John Kessenichfca82622016-11-26 13:23:20 -07001547 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001548}
1549
1550//
1551// Implement the traversal functions.
1552//
1553// Return true from interior nodes to have the external traversal
1554// continue on to children. Return false if children were
1555// already processed.
1556//
1557
1558//
qining25262b32016-05-06 17:25:16 -04001559// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001560// - uniform/input reads
1561// - output writes
1562// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1563// - something simple that degenerates into the last bullet
1564//
1565void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1566{
qining75d1d802016-04-06 14:42:01 -04001567 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1568 if (symbol->getType().getQualifier().isSpecConstant())
1569 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1570
John Kessenich140f3df2015-06-26 16:58:36 -06001571 // getSymbolId() will set up all the IO decorations on the first call.
1572 // Formal function parameters were mapped during makeFunctions().
1573 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001574
1575 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1576 if (builder.isPointer(id)) {
John Kessenich7c7731e2019-01-04 16:47:06 +07001577 // Consider adding to the OpEntryPoint interface list.
1578 // Only looking at structures if they have at least one member.
1579 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1580 spv::StorageClass sc = builder.getStorageClass(id);
1581 // Before SPIR-V 1.4, we only want to include Input and Output.
1582 // Starting with SPIR-V 1.4, we want all globals.
1583 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1584 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001585 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001586 }
John Kessenich5f77d862017-09-19 11:09:59 -06001587 }
John Kessenich7ba63412015-12-20 17:37:07 -07001588 }
1589
1590 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001591 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001592 // Prepare to generate code for the access
1593
1594 // L-value chains will be computed left to right. We're on the symbol now,
1595 // which is the left-most part of the access chain, so now is "clear" time,
1596 // followed by setting the base.
1597 builder.clearAccessChain();
1598
1599 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001600 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001601 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001602 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001603 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001604 // These are also pure R-values.
1605 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001606 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001607 builder.setAccessChainRValue(id);
1608 else
1609 builder.setAccessChainLValue(id);
1610 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001611
1612 // Process linkage-only nodes for any special additional interface work.
1613 if (linkageOnly) {
1614 if (glslangIntermediate->getHlslFunctionality1()) {
1615 // Map implicit counter buffers to their originating buffers, which should have been
1616 // seen by now, given earlier pruning of unused counters, and preservation of order
1617 // of declaration.
1618 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1619 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1620 // Save possible originating buffers for counter buffers, keyed by
1621 // making the potential counter-buffer name.
1622 std::string keyName = symbol->getName().c_str();
1623 keyName = glslangIntermediate->addCounterBufferName(keyName);
1624 counterOriginator[keyName] = symbol;
1625 } else {
1626 // Handle a counter buffer, by finding the saved originating buffer.
1627 std::string keyName = symbol->getName().c_str();
1628 auto it = counterOriginator.find(keyName);
1629 if (it != counterOriginator.end()) {
1630 id = getSymbolId(it->second);
1631 if (id != spv::NoResult) {
1632 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001633 if (counterId != spv::NoResult) {
1634 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001635 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001636 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001637 }
1638 }
1639 }
1640 }
1641 }
1642 }
John Kessenich140f3df2015-06-26 16:58:36 -06001643}
1644
1645bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1646{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001647 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001648
qining40887662016-04-03 22:20:42 -04001649 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1650 if (node->getType().getQualifier().isSpecConstant())
1651 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1652
John Kessenich140f3df2015-06-26 16:58:36 -06001653 // First, handle special cases
1654 switch (node->getOp()) {
1655 case glslang::EOpAssign:
1656 case glslang::EOpAddAssign:
1657 case glslang::EOpSubAssign:
1658 case glslang::EOpMulAssign:
1659 case glslang::EOpVectorTimesMatrixAssign:
1660 case glslang::EOpVectorTimesScalarAssign:
1661 case glslang::EOpMatrixTimesScalarAssign:
1662 case glslang::EOpMatrixTimesMatrixAssign:
1663 case glslang::EOpDivAssign:
1664 case glslang::EOpModAssign:
1665 case glslang::EOpAndAssign:
1666 case glslang::EOpInclusiveOrAssign:
1667 case glslang::EOpExclusiveOrAssign:
1668 case glslang::EOpLeftShiftAssign:
1669 case glslang::EOpRightShiftAssign:
1670 // A bin-op assign "a += b" means the same thing as "a = a + b"
1671 // where a is evaluated before b. For a simple assignment, GLSL
1672 // says to evaluate the left before the right. So, always, left
1673 // node then right node.
1674 {
1675 // get the left l-value, save it away
1676 builder.clearAccessChain();
1677 node->getLeft()->traverse(this);
1678 spv::Builder::AccessChain lValue = builder.getAccessChain();
1679
1680 // evaluate the right
1681 builder.clearAccessChain();
1682 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001683 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001684
1685 if (node->getOp() != glslang::EOpAssign) {
1686 // the left is also an r-value
1687 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001688 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001689
1690 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001691 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001692 TranslateNoContractionDecoration(node->getType().getQualifier()),
1693 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001694 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001695 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1696 node->getType().getBasicType());
1697
1698 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001699 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001700 }
1701
1702 // store the result
1703 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001704 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001705
1706 // assignments are expressions having an rValue after they are evaluated...
1707 builder.clearAccessChain();
1708 builder.setAccessChainRValue(rValue);
1709 }
1710 return false;
1711 case glslang::EOpIndexDirect:
1712 case glslang::EOpIndexDirectStruct:
1713 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001714 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001715 // Get the left part of the access chain.
1716 node->getLeft()->traverse(this);
1717
1718 // Add the next element in the chain
1719
David Netoa901ffe2016-06-08 14:11:40 +01001720 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001721 if (! node->getLeft()->getType().isArray() &&
1722 node->getLeft()->getType().isVector() &&
1723 node->getOp() == glslang::EOpIndexDirect) {
1724 // This is essentially a hard-coded vector swizzle of size 1,
1725 // so short circuit the access-chain stuff with a swizzle.
1726 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001727 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001728 int dummySize;
1729 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1730 TranslateCoherent(node->getLeft()->getType()),
1731 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001732 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001733
1734 // Load through a block reference is performed with a dot operator that
1735 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1736 // do a load and reset the access chain.
1737 if (node->getLeft()->getBasicType() == glslang::EbtReference &&
1738 !node->getLeft()->getType().isArray() &&
1739 node->getOp() == glslang::EOpIndexDirectStruct)
1740 {
1741 spv::Id left = accessChainLoad(node->getLeft()->getType());
1742 builder.clearAccessChain();
1743 builder.setAccessChainLValue(left);
1744 }
1745
David Netoa901ffe2016-06-08 14:11:40 +01001746 int spvIndex = glslangIndex;
1747 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1748 node->getOp() == glslang::EOpIndexDirectStruct)
1749 {
1750 // This may be, e.g., an anonymous block-member selection, which generally need
1751 // index remapping due to hidden members in anonymous blocks.
1752 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1753 assert(remapper.size() > 0);
1754 spvIndex = remapper[glslangIndex];
1755 }
John Kessenichebb50532016-05-16 19:22:05 -06001756
David Netoa901ffe2016-06-08 14:11:40 +01001757 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001758 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001759
1760 // Add capabilities here for accessing PointSize and clip/cull distance.
1761 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001762 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001763 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001764 }
1765 }
1766 return false;
1767 case glslang::EOpIndexIndirect:
1768 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001769 // Array, matrix, or vector indirection with variable index.
1770 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001771 // matrices are arrays of vectors, so will also work for a matrix.
1772 // Will use the access chain's 'component' for variable index into a vector.
1773
1774 // This adapter is building access chains left to right.
1775 // Set up the access chain to the left.
1776 node->getLeft()->traverse(this);
1777
1778 // save it so that computing the right side doesn't trash it
1779 spv::Builder::AccessChain partial = builder.getAccessChain();
1780
1781 // compute the next index in the chain
1782 builder.clearAccessChain();
1783 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001784 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001785
John Kessenich5611c6d2018-04-05 11:25:02 -06001786 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1787
John Kessenich140f3df2015-06-26 16:58:36 -06001788 // restore the saved access chain
1789 builder.setAccessChain(partial);
1790
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001791 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1792 int dummySize;
1793 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1794 TranslateCoherent(node->getLeft()->getType()),
1795 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1796 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001797 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001798 }
1799 return false;
1800 case glslang::EOpVectorSwizzle:
1801 {
1802 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001803 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001804 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001805 int dummySize;
1806 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1807 TranslateCoherent(node->getLeft()->getType()),
1808 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001809 }
1810 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001811 case glslang::EOpMatrixSwizzle:
1812 logger->missingFunctionality("matrix swizzle");
1813 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001814 case glslang::EOpLogicalOr:
1815 case glslang::EOpLogicalAnd:
1816 {
1817
1818 // These may require short circuiting, but can sometimes be done as straight
1819 // binary operations. The right operand must be short circuited if it has
1820 // side effects, and should probably be if it is complex.
1821 if (isTrivial(node->getRight()->getAsTyped()))
1822 break; // handle below as a normal binary operation
1823 // otherwise, we need to do dynamic short circuiting on the right operand
1824 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1825 builder.clearAccessChain();
1826 builder.setAccessChainRValue(result);
1827 }
1828 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001829 default:
1830 break;
1831 }
1832
1833 // Assume generic binary op...
1834
John Kessenich32cfd492016-02-02 12:37:46 -07001835 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001836 builder.clearAccessChain();
1837 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001838 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001839
John Kessenich32cfd492016-02-02 12:37:46 -07001840 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001841 builder.clearAccessChain();
1842 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001843 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001844
John Kessenich32cfd492016-02-02 12:37:46 -07001845 // get result
John Kessenichead86222018-03-28 18:01:20 -06001846 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001847 TranslateNoContractionDecoration(node->getType().getQualifier()),
1848 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001849 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001850 convertGlslangToSpvType(node->getType()), left, right,
1851 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001852
John Kessenich50e57562015-12-21 21:21:11 -07001853 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001854 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001855 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001856 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001857 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001858 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001859 return false;
1860 }
John Kessenich140f3df2015-06-26 16:58:36 -06001861}
1862
1863bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1864{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001865 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001866
qining40887662016-04-03 22:20:42 -04001867 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1868 if (node->getType().getQualifier().isSpecConstant())
1869 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1870
John Kessenichfc51d282015-08-19 13:34:18 -06001871 spv::Id result = spv::NoResult;
1872
1873 // try texturing first
1874 result = createImageTextureFunctionCall(node);
1875 if (result != spv::NoResult) {
1876 builder.clearAccessChain();
1877 builder.setAccessChainRValue(result);
1878
1879 return false; // done with this node
1880 }
1881
1882 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001883
1884 if (node->getOp() == glslang::EOpArrayLength) {
1885 // Quite special; won't want to evaluate the operand.
1886
John Kessenich5611c6d2018-04-05 11:25:02 -06001887 // Currently, the front-end does not allow .length() on an array until it is sized,
1888 // except for the last block membeor of an SSBO.
1889 // TODO: If this changes, link-time sized arrays might show up here, and need their
1890 // size extracted.
1891
John Kessenichc9a80832015-09-12 12:17:44 -06001892 // Normal .length() would have been constant folded by the front-end.
1893 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001894 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001895
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001896 spv::Id length;
1897 if (node->getOperand()->getType().isCoopMat()) {
1898 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1899
1900 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
1901 assert(builder.isCooperativeMatrixType(typeId));
1902
1903 length = builder.createCooperativeMatrixLength(typeId);
1904 } else {
1905 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1906 block->traverse(this);
1907 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1908 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
1909 }
John Kessenichc9a80832015-09-12 12:17:44 -06001910
John Kessenich8c869672018-11-28 07:01:37 -07001911 // GLSL semantics say the result of .length() is an int, while SPIR-V says
1912 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
1913 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001914 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
1915 if (builder.isInSpecConstCodeGenMode()) {
1916 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
1917 } else {
1918 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
1919 }
1920 }
John Kessenich8c869672018-11-28 07:01:37 -07001921
John Kessenichc9a80832015-09-12 12:17:44 -06001922 builder.clearAccessChain();
1923 builder.setAccessChainRValue(length);
1924
1925 return false;
1926 }
1927
John Kessenichfc51d282015-08-19 13:34:18 -06001928 // Start by evaluating the operand
1929
John Kessenich8c8505c2016-07-26 12:50:38 -06001930 // Does it need a swizzle inversion? If so, evaluation is inverted;
1931 // operate first on the swizzle base, then apply the swizzle.
1932 spv::Id invertedType = spv::NoType;
1933 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1934 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1935 invertedType = getInvertedSwizzleType(*node->getOperand());
1936
John Kessenich140f3df2015-06-26 16:58:36 -06001937 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001938 if (invertedType != spv::NoType)
1939 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1940 else
1941 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001942
Rex Xufc618912015-09-09 16:42:49 +08001943 spv::Id operand = spv::NoResult;
1944
1945 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1946 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001947 node->getOp() == glslang::EOpAtomicCounter ||
1948 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001949 operand = builder.accessChainGetLValue(); // Special case l-value operands
1950 else
John Kessenich32cfd492016-02-02 12:37:46 -07001951 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001952
John Kessenichead86222018-03-28 18:01:20 -06001953 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001954 TranslateNoContractionDecoration(node->getType().getQualifier()),
1955 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001956
1957 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001958 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001959 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001960
1961 // if not, then possibly an operation
1962 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001963 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001964
1965 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001966 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001967 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001968 builder.addDecoration(result, decorations.nonUniform);
1969 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001970
John Kessenich140f3df2015-06-26 16:58:36 -06001971 builder.clearAccessChain();
1972 builder.setAccessChainRValue(result);
1973
1974 return false; // done with this node
1975 }
1976
1977 // it must be a special case, check...
1978 switch (node->getOp()) {
1979 case glslang::EOpPostIncrement:
1980 case glslang::EOpPostDecrement:
1981 case glslang::EOpPreIncrement:
1982 case glslang::EOpPreDecrement:
1983 {
1984 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001985 spv::Id one = 0;
1986 if (node->getBasicType() == glslang::EbtFloat)
1987 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001988 else if (node->getBasicType() == glslang::EbtDouble)
1989 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001990 else if (node->getBasicType() == glslang::EbtFloat16)
1991 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001992 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1993 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001994 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1995 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001996 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1997 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001998 else
1999 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002000 glslang::TOperator op;
2001 if (node->getOp() == glslang::EOpPreIncrement ||
2002 node->getOp() == glslang::EOpPostIncrement)
2003 op = glslang::EOpAdd;
2004 else
2005 op = glslang::EOpSub;
2006
John Kessenichead86222018-03-28 18:01:20 -06002007 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002008 convertGlslangToSpvType(node->getType()), operand, one,
2009 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002010 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002011
2012 // The result of operation is always stored, but conditionally the
2013 // consumed result. The consumed result is always an r-value.
2014 builder.accessChainStore(result);
2015 builder.clearAccessChain();
2016 if (node->getOp() == glslang::EOpPreIncrement ||
2017 node->getOp() == glslang::EOpPreDecrement)
2018 builder.setAccessChainRValue(result);
2019 else
2020 builder.setAccessChainRValue(operand);
2021 }
2022
2023 return false;
2024
2025 case glslang::EOpEmitStreamVertex:
2026 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2027 return false;
2028 case glslang::EOpEndStreamPrimitive:
2029 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2030 return false;
2031
2032 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002033 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002034 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002035 }
John Kessenich140f3df2015-06-26 16:58:36 -06002036}
2037
2038bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2039{
qining27e04a02016-04-14 16:40:20 -04002040 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2041 if (node->getType().getQualifier().isSpecConstant())
2042 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2043
John Kessenichfc51d282015-08-19 13:34:18 -06002044 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002045 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2046 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002047
2048 // try texturing
2049 result = createImageTextureFunctionCall(node);
2050 if (result != spv::NoResult) {
2051 builder.clearAccessChain();
2052 builder.setAccessChainRValue(result);
2053
2054 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05002055 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08002056#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05002057 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08002058#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05002059 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002060 // "imageStore" is a special case, which has no result
2061 return false;
2062 }
John Kessenichfc51d282015-08-19 13:34:18 -06002063
John Kessenich140f3df2015-06-26 16:58:36 -06002064 glslang::TOperator binOp = glslang::EOpNull;
2065 bool reduceComparison = true;
2066 bool isMatrix = false;
2067 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002068 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002069
2070 assert(node->getOp());
2071
John Kessenichf6640762016-08-01 19:44:00 -06002072 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002073
2074 switch (node->getOp()) {
2075 case glslang::EOpSequence:
2076 {
2077 if (preVisit)
2078 ++sequenceDepth;
2079 else
2080 --sequenceDepth;
2081
2082 if (sequenceDepth == 1) {
2083 // If this is the parent node of all the functions, we want to see them
2084 // early, so all call points have actual SPIR-V functions to reference.
2085 // In all cases, still let the traverser visit the children for us.
2086 makeFunctions(node->getAsAggregate()->getSequence());
2087
John Kessenich6fccb3c2016-09-19 16:01:41 -06002088 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002089 // anything else gets there, so visit out of order, doing them all now.
2090 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2091
John Kessenich6a60c2f2016-12-08 21:01:59 -07002092 // 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 -06002093 // so do them manually.
2094 visitFunctions(node->getAsAggregate()->getSequence());
2095
2096 return false;
2097 }
2098
2099 return true;
2100 }
2101 case glslang::EOpLinkerObjects:
2102 {
2103 if (visit == glslang::EvPreVisit)
2104 linkageOnly = true;
2105 else
2106 linkageOnly = false;
2107
2108 return true;
2109 }
2110 case glslang::EOpComma:
2111 {
2112 // processing from left to right naturally leaves the right-most
2113 // lying around in the access chain
2114 glslang::TIntermSequence& glslangOperands = node->getSequence();
2115 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2116 glslangOperands[i]->traverse(this);
2117
2118 return false;
2119 }
2120 case glslang::EOpFunction:
2121 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002122 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002123 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002124 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002125 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002126 } else {
2127 handleFunctionEntry(node);
2128 }
2129 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002130 if (inEntryPoint)
2131 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002132 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002133 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002134 }
2135
2136 return true;
2137 case glslang::EOpParameters:
2138 // Parameters will have been consumed by EOpFunction processing, but not
2139 // the body, so we still visited the function node's children, making this
2140 // child redundant.
2141 return false;
2142 case glslang::EOpFunctionCall:
2143 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002144 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002145 if (node->isUserDefined())
2146 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002147 // 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 -07002148 if (result) {
2149 builder.clearAccessChain();
2150 builder.setAccessChainRValue(result);
2151 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002152 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002153
2154 return false;
2155 }
2156 case glslang::EOpConstructMat2x2:
2157 case glslang::EOpConstructMat2x3:
2158 case glslang::EOpConstructMat2x4:
2159 case glslang::EOpConstructMat3x2:
2160 case glslang::EOpConstructMat3x3:
2161 case glslang::EOpConstructMat3x4:
2162 case glslang::EOpConstructMat4x2:
2163 case glslang::EOpConstructMat4x3:
2164 case glslang::EOpConstructMat4x4:
2165 case glslang::EOpConstructDMat2x2:
2166 case glslang::EOpConstructDMat2x3:
2167 case glslang::EOpConstructDMat2x4:
2168 case glslang::EOpConstructDMat3x2:
2169 case glslang::EOpConstructDMat3x3:
2170 case glslang::EOpConstructDMat3x4:
2171 case glslang::EOpConstructDMat4x2:
2172 case glslang::EOpConstructDMat4x3:
2173 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002174 case glslang::EOpConstructIMat2x2:
2175 case glslang::EOpConstructIMat2x3:
2176 case glslang::EOpConstructIMat2x4:
2177 case glslang::EOpConstructIMat3x2:
2178 case glslang::EOpConstructIMat3x3:
2179 case glslang::EOpConstructIMat3x4:
2180 case glslang::EOpConstructIMat4x2:
2181 case glslang::EOpConstructIMat4x3:
2182 case glslang::EOpConstructIMat4x4:
2183 case glslang::EOpConstructUMat2x2:
2184 case glslang::EOpConstructUMat2x3:
2185 case glslang::EOpConstructUMat2x4:
2186 case glslang::EOpConstructUMat3x2:
2187 case glslang::EOpConstructUMat3x3:
2188 case glslang::EOpConstructUMat3x4:
2189 case glslang::EOpConstructUMat4x2:
2190 case glslang::EOpConstructUMat4x3:
2191 case glslang::EOpConstructUMat4x4:
2192 case glslang::EOpConstructBMat2x2:
2193 case glslang::EOpConstructBMat2x3:
2194 case glslang::EOpConstructBMat2x4:
2195 case glslang::EOpConstructBMat3x2:
2196 case glslang::EOpConstructBMat3x3:
2197 case glslang::EOpConstructBMat3x4:
2198 case glslang::EOpConstructBMat4x2:
2199 case glslang::EOpConstructBMat4x3:
2200 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002201 case glslang::EOpConstructF16Mat2x2:
2202 case glslang::EOpConstructF16Mat2x3:
2203 case glslang::EOpConstructF16Mat2x4:
2204 case glslang::EOpConstructF16Mat3x2:
2205 case glslang::EOpConstructF16Mat3x3:
2206 case glslang::EOpConstructF16Mat3x4:
2207 case glslang::EOpConstructF16Mat4x2:
2208 case glslang::EOpConstructF16Mat4x3:
2209 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002210 isMatrix = true;
2211 // fall through
2212 case glslang::EOpConstructFloat:
2213 case glslang::EOpConstructVec2:
2214 case glslang::EOpConstructVec3:
2215 case glslang::EOpConstructVec4:
2216 case glslang::EOpConstructDouble:
2217 case glslang::EOpConstructDVec2:
2218 case glslang::EOpConstructDVec3:
2219 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002220 case glslang::EOpConstructFloat16:
2221 case glslang::EOpConstructF16Vec2:
2222 case glslang::EOpConstructF16Vec3:
2223 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002224 case glslang::EOpConstructBool:
2225 case glslang::EOpConstructBVec2:
2226 case glslang::EOpConstructBVec3:
2227 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002228 case glslang::EOpConstructInt8:
2229 case glslang::EOpConstructI8Vec2:
2230 case glslang::EOpConstructI8Vec3:
2231 case glslang::EOpConstructI8Vec4:
2232 case glslang::EOpConstructUint8:
2233 case glslang::EOpConstructU8Vec2:
2234 case glslang::EOpConstructU8Vec3:
2235 case glslang::EOpConstructU8Vec4:
2236 case glslang::EOpConstructInt16:
2237 case glslang::EOpConstructI16Vec2:
2238 case glslang::EOpConstructI16Vec3:
2239 case glslang::EOpConstructI16Vec4:
2240 case glslang::EOpConstructUint16:
2241 case glslang::EOpConstructU16Vec2:
2242 case glslang::EOpConstructU16Vec3:
2243 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002244 case glslang::EOpConstructInt:
2245 case glslang::EOpConstructIVec2:
2246 case glslang::EOpConstructIVec3:
2247 case glslang::EOpConstructIVec4:
2248 case glslang::EOpConstructUint:
2249 case glslang::EOpConstructUVec2:
2250 case glslang::EOpConstructUVec3:
2251 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002252 case glslang::EOpConstructInt64:
2253 case glslang::EOpConstructI64Vec2:
2254 case glslang::EOpConstructI64Vec3:
2255 case glslang::EOpConstructI64Vec4:
2256 case glslang::EOpConstructUint64:
2257 case glslang::EOpConstructU64Vec2:
2258 case glslang::EOpConstructU64Vec3:
2259 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002260 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002261 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002262 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002263 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002264 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002265 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002266 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002267 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002268 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002269 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002270 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002271 else if (node->getOp() == glslang::EOpConstructStruct ||
2272 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2273 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002274 std::vector<spv::Id> constituents;
2275 for (int c = 0; c < (int)arguments.size(); ++c)
2276 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002277 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002278 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002279 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002280 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002281 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002282
2283 builder.clearAccessChain();
2284 builder.setAccessChainRValue(constructed);
2285
2286 return false;
2287 }
2288
2289 // These six are component-wise compares with component-wise results.
2290 // Forward on to createBinaryOperation(), requesting a vector result.
2291 case glslang::EOpLessThan:
2292 case glslang::EOpGreaterThan:
2293 case glslang::EOpLessThanEqual:
2294 case glslang::EOpGreaterThanEqual:
2295 case glslang::EOpVectorEqual:
2296 case glslang::EOpVectorNotEqual:
2297 {
2298 // Map the operation to a binary
2299 binOp = node->getOp();
2300 reduceComparison = false;
2301 switch (node->getOp()) {
2302 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2303 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2304 default: binOp = node->getOp(); break;
2305 }
2306
2307 break;
2308 }
2309 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002310 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002311 binOp = glslang::EOpMul;
2312 break;
2313 case glslang::EOpOuterProduct:
2314 // two vectors multiplied to make a matrix
2315 binOp = glslang::EOpOuterProduct;
2316 break;
2317 case glslang::EOpDot:
2318 {
qining25262b32016-05-06 17:25:16 -04002319 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002320 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002321 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002322 binOp = glslang::EOpMul;
2323 break;
2324 }
2325 case glslang::EOpMod:
2326 // when an aggregate, this is the floating-point mod built-in function,
2327 // which can be emitted by the one in createBinaryOperation()
2328 binOp = glslang::EOpMod;
2329 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002330 case glslang::EOpEmitVertex:
2331 case glslang::EOpEndPrimitive:
2332 case glslang::EOpBarrier:
2333 case glslang::EOpMemoryBarrier:
2334 case glslang::EOpMemoryBarrierAtomicCounter:
2335 case glslang::EOpMemoryBarrierBuffer:
2336 case glslang::EOpMemoryBarrierImage:
2337 case glslang::EOpMemoryBarrierShared:
2338 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002339 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002340 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002341 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002342 case glslang::EOpWorkgroupMemoryBarrier:
2343 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002344 case glslang::EOpSubgroupBarrier:
2345 case glslang::EOpSubgroupMemoryBarrier:
2346 case glslang::EOpSubgroupMemoryBarrierBuffer:
2347 case glslang::EOpSubgroupMemoryBarrierImage:
2348 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002349 noReturnValue = true;
2350 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2351 break;
2352
Jeff Bolz36831c92018-09-05 10:11:41 -05002353 case glslang::EOpAtomicStore:
2354 noReturnValue = true;
2355 // fallthrough
2356 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002357 case glslang::EOpAtomicAdd:
2358 case glslang::EOpAtomicMin:
2359 case glslang::EOpAtomicMax:
2360 case glslang::EOpAtomicAnd:
2361 case glslang::EOpAtomicOr:
2362 case glslang::EOpAtomicXor:
2363 case glslang::EOpAtomicExchange:
2364 case glslang::EOpAtomicCompSwap:
2365 atomic = true;
2366 break;
2367
John Kessenich0d0c6d32017-07-23 16:08:26 -06002368 case glslang::EOpAtomicCounterAdd:
2369 case glslang::EOpAtomicCounterSubtract:
2370 case glslang::EOpAtomicCounterMin:
2371 case glslang::EOpAtomicCounterMax:
2372 case glslang::EOpAtomicCounterAnd:
2373 case glslang::EOpAtomicCounterOr:
2374 case glslang::EOpAtomicCounterXor:
2375 case glslang::EOpAtomicCounterExchange:
2376 case glslang::EOpAtomicCounterCompSwap:
2377 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2378 builder.addCapability(spv::CapabilityAtomicStorageOps);
2379 atomic = true;
2380 break;
2381
Chao Chen3c366992018-09-19 11:41:59 -07002382#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002383 case glslang::EOpIgnoreIntersectionNV:
2384 case glslang::EOpTerminateRayNV:
2385 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002386 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002387 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2388 noReturnValue = true;
2389 break;
2390#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002391 case glslang::EOpCooperativeMatrixLoad:
2392 case glslang::EOpCooperativeMatrixStore:
2393 noReturnValue = true;
2394 break;
Chao Chen3c366992018-09-19 11:41:59 -07002395
John Kessenich140f3df2015-06-26 16:58:36 -06002396 default:
2397 break;
2398 }
2399
2400 //
2401 // See if it maps to a regular operation.
2402 //
John Kessenich140f3df2015-06-26 16:58:36 -06002403 if (binOp != glslang::EOpNull) {
2404 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2405 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2406 assert(left && right);
2407
2408 builder.clearAccessChain();
2409 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002410 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002411
2412 builder.clearAccessChain();
2413 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002414 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002415
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002416 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002417 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002418 TranslateNoContractionDecoration(node->getType().getQualifier()),
2419 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002420 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002421 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002422 left->getType().getBasicType(), reduceComparison);
2423
2424 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002425 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002426 builder.clearAccessChain();
2427 builder.setAccessChainRValue(result);
2428
2429 return false;
2430 }
2431
John Kessenich426394d2015-07-23 10:22:48 -06002432 //
2433 // Create the list of operands.
2434 //
John Kessenich140f3df2015-06-26 16:58:36 -06002435 glslang::TIntermSequence& glslangOperands = node->getSequence();
2436 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002437 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002438 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002439 // special case l-value operands; there are just a few
2440 bool lvalue = false;
2441 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002442 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002443 case glslang::EOpModf:
2444 if (arg == 1)
2445 lvalue = true;
2446 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002447 case glslang::EOpInterpolateAtSample:
2448 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002449#ifdef AMD_EXTENSIONS
2450 case glslang::EOpInterpolateAtVertex:
2451#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002452 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002453 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002454
2455 // Does it need a swizzle inversion? If so, evaluation is inverted;
2456 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002457 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002458 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2459 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2460 }
Rex Xu7a26c172015-12-08 17:12:09 +08002461 break;
Rex Xud4782c12015-09-06 16:30:11 +08002462 case glslang::EOpAtomicAdd:
2463 case glslang::EOpAtomicMin:
2464 case glslang::EOpAtomicMax:
2465 case glslang::EOpAtomicAnd:
2466 case glslang::EOpAtomicOr:
2467 case glslang::EOpAtomicXor:
2468 case glslang::EOpAtomicExchange:
2469 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002470 case glslang::EOpAtomicLoad:
2471 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002472 case glslang::EOpAtomicCounterAdd:
2473 case glslang::EOpAtomicCounterSubtract:
2474 case glslang::EOpAtomicCounterMin:
2475 case glslang::EOpAtomicCounterMax:
2476 case glslang::EOpAtomicCounterAnd:
2477 case glslang::EOpAtomicCounterOr:
2478 case glslang::EOpAtomicCounterXor:
2479 case glslang::EOpAtomicCounterExchange:
2480 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002481 if (arg == 0)
2482 lvalue = true;
2483 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002484 case glslang::EOpAddCarry:
2485 case glslang::EOpSubBorrow:
2486 if (arg == 2)
2487 lvalue = true;
2488 break;
2489 case glslang::EOpUMulExtended:
2490 case glslang::EOpIMulExtended:
2491 if (arg >= 2)
2492 lvalue = true;
2493 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002494 case glslang::EOpCooperativeMatrixLoad:
2495 if (arg == 0 || arg == 1)
2496 lvalue = true;
2497 break;
2498 case glslang::EOpCooperativeMatrixStore:
2499 if (arg == 1)
2500 lvalue = true;
2501 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002502 default:
2503 break;
2504 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002505 builder.clearAccessChain();
2506 if (invertedType != spv::NoType && arg == 0)
2507 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2508 else
2509 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002510
2511 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2512 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2513
2514 if (arg == 1) {
2515 // fold "element" parameter into the access chain
2516 spv::Builder::AccessChain save = builder.getAccessChain();
2517 builder.clearAccessChain();
2518 glslangOperands[2]->traverse(this);
2519
2520 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2521
2522 builder.setAccessChain(save);
2523
2524 // Point to the first element of the array.
2525 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002526 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002527
2528 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2529 unsigned int alignment = builder.getAccessChain().alignment;
2530
2531 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2532 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2533 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2534 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2535 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2536 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2537 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2538 }
2539
2540 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2541
2542 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2543 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2544 }
2545
2546 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2547 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2548 }
2549 } else if (arg == 2) {
2550 continue;
2551 }
2552 }
2553
John Kessenich140f3df2015-06-26 16:58:36 -06002554 if (lvalue)
2555 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002556 else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002557 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002558 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002559 }
John Kessenich140f3df2015-06-26 16:58:36 -06002560 }
John Kessenich426394d2015-07-23 10:22:48 -06002561
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002562 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002563 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2564 std::vector<spv::IdImmediate> idImmOps;
2565
2566 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2567 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2568 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2569 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2570 // get the pointee type
2571 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2572 assert(builder.isCooperativeMatrixType(typeId));
2573 // do the op
2574 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2575 // store the result to the pointer (out param 'm')
2576 builder.createStore(result, operands[0]);
2577 result = 0;
2578 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2579 std::vector<spv::IdImmediate> idImmOps;
2580
2581 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2582 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2583 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2584 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2585 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2586
2587 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2588 result = 0;
2589 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002590 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002591 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002592 } else {
2593 // Pass through to generic operations.
2594 switch (glslangOperands.size()) {
2595 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002596 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002597 break;
2598 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002599 {
2600 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002601 TranslateNoContractionDecoration(node->getType().getQualifier()),
2602 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002603 result = createUnaryOperation(
2604 node->getOp(), decorations,
2605 resultType(), operands.front(),
2606 glslangOperands[0]->getAsTyped()->getBasicType());
2607 }
John Kessenich426394d2015-07-23 10:22:48 -06002608 break;
2609 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002610 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002611 break;
2612 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002613 if (invertedType)
2614 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002615 }
2616
2617 if (noReturnValue)
2618 return false;
2619
2620 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002621 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002622 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002623 } else {
2624 builder.clearAccessChain();
2625 builder.setAccessChainRValue(result);
2626 return false;
2627 }
2628}
2629
John Kessenich433e9ff2017-01-26 20:31:11 -07002630// This path handles both if-then-else and ?:
2631// The if-then-else has a node type of void, while
2632// ?: has either a void or a non-void node type
2633//
2634// Leaving the result, when not void:
2635// GLSL only has r-values as the result of a :?, but
2636// if we have an l-value, that can be more efficient if it will
2637// become the base of a complex r-value expression, because the
2638// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002639bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2640{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002641 // see if OpSelect can handle it
2642 const auto isOpSelectable = [&]() {
2643 if (node->getBasicType() == glslang::EbtVoid)
2644 return false;
2645 // OpSelect can do all other types starting with SPV 1.4
2646 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2647 // pre-1.4, only scalars and vectors can be handled
2648 if ((!node->getType().isScalar() && !node->getType().isVector()))
2649 return false;
2650 }
2651 return true;
2652 };
2653
John Kessenich4bee5312018-02-20 21:29:05 -07002654 // See if it simple and safe, or required, to execute both sides.
2655 // Crucially, side effects must be either semantically required or avoided,
2656 // and there are performance trade-offs.
2657 // Return true if required or a good idea (and safe) to execute both sides,
2658 // false otherwise.
2659 const auto bothSidesPolicy = [&]() -> bool {
2660 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002661 if (node->getTrueBlock() == nullptr ||
2662 node->getFalseBlock() == nullptr)
2663 return false;
2664
John Kessenich4bee5312018-02-20 21:29:05 -07002665 // required? (unless we write additional code to look for side effects
2666 // and make performance trade-offs if none are present)
2667 if (!node->getShortCircuit())
2668 return true;
2669
2670 // if not required to execute both, decide based on performance/practicality...
2671
John Kessenich0c1e71a2019-01-10 18:23:06 +07002672 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002673 return false;
2674
John Kessenich433e9ff2017-01-26 20:31:11 -07002675 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2676 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2677
2678 // return true if a single operand to ? : is okay for OpSelect
2679 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002680 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002681 };
2682
2683 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2684 operandOkay(node->getFalseBlock()->getAsTyped());
2685 };
2686
John Kessenich4bee5312018-02-20 21:29:05 -07002687 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2688 // emit the condition before doing anything with selection
2689 node->getCondition()->traverse(this);
2690 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2691
2692 // Find a way of executing both sides and selecting the right result.
2693 const auto executeBothSides = [&]() -> void {
2694 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002695 node->getTrueBlock()->traverse(this);
2696 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2697 node->getFalseBlock()->traverse(this);
2698 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2699
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002700 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002701
John Kessenich4bee5312018-02-20 21:29:05 -07002702 // done if void
2703 if (node->getBasicType() == glslang::EbtVoid)
2704 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002705
John Kessenich4bee5312018-02-20 21:29:05 -07002706 // emit code to select between trueValue and falseValue
2707
2708 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002709 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002710 // Emit OpSelect for this selection.
2711
2712 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002713 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2714 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002715 condition = builder.smearScalar(spv::NoPrecision, condition,
2716 builder.makeVectorType(builder.makeBoolType(),
2717 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002718 }
John Kessenich4bee5312018-02-20 21:29:05 -07002719
2720 // OpSelect
2721 result = builder.createTriOp(spv::OpSelect,
2722 convertGlslangToSpvType(node->getType()), condition,
2723 trueValue, falseValue);
2724
2725 builder.clearAccessChain();
2726 builder.setAccessChainRValue(result);
2727 } else {
2728 // We need control flow to select the result.
2729 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2730 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2731
2732 // Selection control:
2733 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2734
2735 // make an "if" based on the value created by the condition
2736 spv::Builder::If ifBuilder(condition, control, builder);
2737
2738 // emit the "then" statement
2739 builder.createStore(trueValue, result);
2740 ifBuilder.makeBeginElse();
2741 // emit the "else" statement
2742 builder.createStore(falseValue, result);
2743
2744 // finish off the control flow
2745 ifBuilder.makeEndIf();
2746
2747 builder.clearAccessChain();
2748 builder.setAccessChainLValue(result);
2749 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002750 };
2751
John Kessenich4bee5312018-02-20 21:29:05 -07002752 // Execute the one side needed, as per the condition
2753 const auto executeOneSide = [&]() {
2754 // Always emit control flow.
2755 if (node->getBasicType() != glslang::EbtVoid)
2756 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002757
John Kessenich4bee5312018-02-20 21:29:05 -07002758 // Selection control:
2759 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2760
2761 // make an "if" based on the value created by the condition
2762 spv::Builder::If ifBuilder(condition, control, builder);
2763
2764 // emit the "then" statement
2765 if (node->getTrueBlock() != nullptr) {
2766 node->getTrueBlock()->traverse(this);
2767 if (result != spv::NoResult)
2768 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2769 }
2770
2771 if (node->getFalseBlock() != nullptr) {
2772 ifBuilder.makeBeginElse();
2773 // emit the "else" statement
2774 node->getFalseBlock()->traverse(this);
2775 if (result != spv::NoResult)
2776 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2777 }
2778
2779 // finish off the control flow
2780 ifBuilder.makeEndIf();
2781
2782 if (result != spv::NoResult) {
2783 builder.clearAccessChain();
2784 builder.setAccessChainLValue(result);
2785 }
2786 };
2787
2788 // Try for OpSelect (or a requirement to execute both sides)
2789 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002790 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2791 if (node->getType().getQualifier().isSpecConstant())
2792 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002793 executeBothSides();
2794 } else
2795 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002796
2797 return false;
2798}
2799
2800bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2801{
2802 // emit and get the condition before doing anything with switch
2803 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002804 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002805
Rex Xu57e65922017-07-04 23:23:40 +08002806 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002807 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002808
John Kessenich140f3df2015-06-26 16:58:36 -06002809 // browse the children to sort out code segments
2810 int defaultSegment = -1;
2811 std::vector<TIntermNode*> codeSegments;
2812 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2813 std::vector<int> caseValues;
2814 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2815 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2816 TIntermNode* child = *c;
2817 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002818 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002819 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002820 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002821 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2822 } else
2823 codeSegments.push_back(child);
2824 }
2825
qining25262b32016-05-06 17:25:16 -04002826 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002827 // statements between the last case and the end of the switch statement
2828 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2829 (int)codeSegments.size() == defaultSegment)
2830 codeSegments.push_back(nullptr);
2831
2832 // make the switch statement
2833 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002834 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002835
2836 // emit all the code in the segments
2837 breakForLoop.push(false);
2838 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2839 builder.nextSwitchSegment(segmentBlocks, s);
2840 if (codeSegments[s])
2841 codeSegments[s]->traverse(this);
2842 else
2843 builder.addSwitchBreak();
2844 }
2845 breakForLoop.pop();
2846
2847 builder.endSwitch(segmentBlocks);
2848
2849 return false;
2850}
2851
2852void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2853{
2854 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002855 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002856
2857 builder.clearAccessChain();
2858 builder.setAccessChainRValue(constant);
2859}
2860
2861bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2862{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002863 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002864 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002865
2866 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07002867 std::vector<unsigned int> operands;
2868 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06002869
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002870 // Spec requires back edges to target header blocks, and every header block
2871 // must dominate its merge block. Make a header block first to ensure these
2872 // conditions are met. By definition, it will contain OpLoopMerge, followed
2873 // by a block-ending branch. But we don't want to put any other body/test
2874 // instructions in it, since the body/test may have arbitrary instructions,
2875 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002876 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002877 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07002878 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002879 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002880 spv::Block& test = builder.makeNewBlock();
2881 builder.createBranch(&test);
2882
2883 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002884 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002885 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002886 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2887
2888 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002889 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002890 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002891 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002892 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002893 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002894
2895 builder.setBuildPoint(&blocks.continue_target);
2896 if (node->getTerminal())
2897 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002898 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002899 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002900 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002901 builder.createBranch(&blocks.body);
2902
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002903 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002904 builder.setBuildPoint(&blocks.body);
2905 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002906 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002907 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002908 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002909
2910 builder.setBuildPoint(&blocks.continue_target);
2911 if (node->getTerminal())
2912 node->getTerminal()->traverse(this);
2913 if (node->getTest()) {
2914 node->getTest()->traverse(this);
2915 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002916 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002917 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002918 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002919 // TODO: unless there was a break/return/discard instruction
2920 // somewhere in the body, this is an infinite loop, so we should
2921 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002922 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002923 }
John Kessenich140f3df2015-06-26 16:58:36 -06002924 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002925 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002926 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002927 return false;
2928}
2929
2930bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2931{
2932 if (node->getExpression())
2933 node->getExpression()->traverse(this);
2934
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002935 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002936
John Kessenich140f3df2015-06-26 16:58:36 -06002937 switch (node->getFlowOp()) {
2938 case glslang::EOpKill:
2939 builder.makeDiscard();
2940 break;
2941 case glslang::EOpBreak:
2942 if (breakForLoop.top())
2943 builder.createLoopExit();
2944 else
2945 builder.addSwitchBreak();
2946 break;
2947 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002948 builder.createLoopContinue();
2949 break;
2950 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002951 if (node->getExpression()) {
2952 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2953 spv::Id returnId = accessChainLoad(glslangReturnType);
2954 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2955 builder.clearAccessChain();
2956 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2957 builder.setAccessChainLValue(copyId);
2958 multiTypeStore(glslangReturnType, returnId);
2959 returnId = builder.createLoad(copyId);
2960 }
2961 builder.makeReturn(false, returnId);
2962 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002963 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002964
2965 builder.clearAccessChain();
2966 break;
2967
2968 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002969 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002970 break;
2971 }
2972
2973 return false;
2974}
2975
2976spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2977{
qining25262b32016-05-06 17:25:16 -04002978 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002979 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002980 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002981 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05002982 spv::Id result = createSpvConstant(*node);
2983 if (result != spv::NoResult)
2984 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06002985 }
2986
2987 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002988 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002989 spv::Id spvType = convertGlslangToSpvType(node->getType());
2990
Rex Xucabbb782017-03-24 13:41:14 +08002991 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2992 node->getType().containsBasicType(glslang::EbtInt16) ||
2993 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002994 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002995 switch (storageClass) {
2996 case spv::StorageClassInput:
2997 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002998 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002999 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003000 break;
3001 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07003002 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003003 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06003004 break;
3005 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003006 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003007 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3008 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003009 else
3010 builder.addCapability(spv::CapabilityStorageUniform16);
3011 break;
3012 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003013 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003014 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3015 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3016 break;
3017 default:
3018 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003019 }
3020 }
Rex Xuf89ad982017-04-07 23:22:33 +08003021
John Kessenich312dcfb2018-07-03 13:19:51 -06003022 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3023 node->getType().containsBasicType(glslang::EbtUint8);
3024 if (contains8BitType) {
3025 if (storageClass == spv::StorageClassPushConstant) {
3026 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3027 builder.addCapability(spv::CapabilityStoragePushConstant8);
3028 } else if (storageClass == spv::StorageClassUniform) {
3029 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3030 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003031 } else if (storageClass == spv::StorageClassStorageBuffer) {
3032 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3033 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
John Kessenich312dcfb2018-07-03 13:19:51 -06003034 }
3035 }
3036
John Kessenich140f3df2015-06-26 16:58:36 -06003037 const char* name = node->getName().c_str();
3038 if (glslang::IsAnonymous(name))
3039 name = "";
3040
3041 return builder.createVariable(storageClass, spvType, name);
3042}
3043
3044// Return type Id of the sampled type.
3045spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3046{
3047 switch (sampler.type) {
3048 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003049#ifdef AMD_EXTENSIONS
3050 case glslang::EbtFloat16:
3051 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3052 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3053 return builder.makeFloatType(16);
3054#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003055 case glslang::EbtInt: return builder.makeIntType(32);
3056 case glslang::EbtUint: return builder.makeUintType(32);
3057 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003058 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003059 return builder.makeFloatType(32);
3060 }
3061}
3062
John Kessenich8c8505c2016-07-26 12:50:38 -06003063// If node is a swizzle operation, return the type that should be used if
3064// the swizzle base is first consumed by another operation, before the swizzle
3065// is applied.
3066spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3067{
John Kessenichecba76f2017-01-06 00:34:48 -07003068 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003069 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3070 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3071 else
3072 return spv::NoType;
3073}
3074
3075// When inverting a swizzle with a parent op, this function
3076// will apply the swizzle operation to a completed parent operation.
3077spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3078{
3079 std::vector<unsigned> swizzle;
3080 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3081 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3082}
3083
John Kessenich8c8505c2016-07-26 12:50:38 -06003084// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3085void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3086{
3087 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3088 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3089 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3090}
3091
John Kessenich3ac051e2015-12-20 11:29:16 -07003092// Convert from a glslang type to an SPV type, by calling into a
3093// recursive version of this function. This establishes the inherited
3094// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003095spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003096{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003097 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003098}
3099
3100// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003101// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003102// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003103spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003104 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3105 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003106{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003107 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003108
3109 switch (type.getBasicType()) {
3110 case glslang::EbtVoid:
3111 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003112 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003113 break;
3114 case glslang::EbtFloat:
3115 spvType = builder.makeFloatType(32);
3116 break;
3117 case glslang::EbtDouble:
3118 spvType = builder.makeFloatType(64);
3119 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003120 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003121 spvType = builder.makeFloatType(16);
3122 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003123 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003124 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3125 // a 32-bit int where non-0 means true.
3126 if (explicitLayout != glslang::ElpNone)
3127 spvType = builder.makeUintType(32);
3128 else
3129 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003130 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003131 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003132 spvType = builder.makeIntType(8);
3133 break;
3134 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003135 spvType = builder.makeUintType(8);
3136 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003137 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003138 spvType = builder.makeIntType(16);
3139 break;
3140 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003141 spvType = builder.makeUintType(16);
3142 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003143 case glslang::EbtInt:
3144 spvType = builder.makeIntType(32);
3145 break;
3146 case glslang::EbtUint:
3147 spvType = builder.makeUintType(32);
3148 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003149 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003150 spvType = builder.makeIntType(64);
3151 break;
3152 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003153 spvType = builder.makeUintType(64);
3154 break;
John Kessenich426394d2015-07-23 10:22:48 -06003155 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003156 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003157 spvType = builder.makeUintType(32);
3158 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003159#ifdef NV_EXTENSIONS
3160 case glslang::EbtAccStructNV:
3161 spvType = builder.makeAccelerationStructureNVType();
3162 break;
3163#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003164 case glslang::EbtSampler:
3165 {
3166 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003167 if (sampler.sampler) {
3168 // pure sampler
3169 spvType = builder.makeSamplerType();
3170 } else {
3171 // an image is present, make its type
3172 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3173 sampler.image ? 2 : 1, TranslateImageFormat(type));
3174 if (sampler.combined) {
3175 // already has both image and sampler, make the combined type
3176 spvType = builder.makeSampledImageType(spvType);
3177 }
John Kessenich55e7d112015-11-15 21:33:39 -07003178 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003179 }
John Kessenich140f3df2015-06-26 16:58:36 -06003180 break;
3181 case glslang::EbtStruct:
3182 case glslang::EbtBlock:
3183 {
3184 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003185 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003186
3187 // Try to share structs for different layouts, but not yet for other
3188 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003189 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003190 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003191 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003192 break;
3193
3194 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003195 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003196 memberRemapper[glslangMembers].resize(glslangMembers->size());
3197 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003198 }
3199 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003200 case glslang::EbtReference:
3201 {
3202 // Make the forward pointer, then recurse to convert the structure type, then
3203 // patch up the forward pointer with a real pointer type.
3204 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3205 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3206 forwardPointers[type.getReferentType()] = forwardId;
3207 }
3208 spvType = forwardPointers[type.getReferentType()];
3209 if (!forwardReferenceOnly) {
3210 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3211 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3212 forwardPointers[type.getReferentType()],
3213 referentType);
3214 }
3215 }
3216 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003217 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003218 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003219 break;
3220 }
3221
3222 if (type.isMatrix())
3223 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3224 else {
3225 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3226 if (type.getVectorSize() > 1)
3227 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3228 }
3229
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003230 if (type.isCoopMat()) {
3231 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3232 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3233 if (type.getBasicType() == glslang::EbtFloat16)
3234 builder.addCapability(spv::CapabilityFloat16);
3235
3236 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3237 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3238 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3239
3240 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3241 }
3242
John Kessenich140f3df2015-06-26 16:58:36 -06003243 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003244 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3245
John Kessenichc9a80832015-09-12 12:17:44 -06003246 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003247 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003248 // We need to decorate array strides for types needing explicit layout, except blocks.
3249 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003250 // Use a dummy glslang type for querying internal strides of
3251 // arrays of arrays, but using just a one-dimensional array.
3252 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003253 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3254 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003255
3256 // Will compute the higher-order strides here, rather than making a whole
3257 // pile of types and doing repetitive recursion on their contents.
3258 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3259 }
John Kessenichf8842e52016-01-04 19:22:56 -07003260
3261 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003262 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003263 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003264 if (stride > 0)
3265 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003266 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003267 }
3268 } else {
3269 // single-dimensional array, and don't yet have stride
3270
John Kessenichf8842e52016-01-04 19:22:56 -07003271 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003272 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3273 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003274 }
John Kessenich31ed4832015-09-09 17:51:38 -06003275
John Kessenichead86222018-03-28 18:01:20 -06003276 // Do the outer dimension, which might not be known for a runtime-sized array.
3277 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3278 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003279 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003280 else {
3281 if (!lastBufferBlockMember) {
3282 builder.addExtension("SPV_EXT_descriptor_indexing");
3283 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3284 }
John Kessenichead86222018-03-28 18:01:20 -06003285 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003286 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003287 if (stride > 0)
3288 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003289 }
3290
3291 return spvType;
3292}
3293
John Kessenich0e737842017-03-24 18:38:16 -06003294// TODO: this functionality should exist at a higher level, in creating the AST
3295//
3296// Identify interface members that don't have their required extension turned on.
3297//
3298bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3299{
Chao Chen3c366992018-09-19 11:41:59 -07003300#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003301 auto& extensions = glslangIntermediate->getRequestedExtensions();
3302
Rex Xubcf291a2017-03-29 23:01:36 +08003303 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3304 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3305 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003306 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3307 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3308 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003309
3310 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3311 if (member.getFieldName() == "gl_ViewportMask" &&
3312 extensions.find("GL_NV_viewport_array2") == extensions.end())
3313 return true;
3314 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3315 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3316 return true;
3317 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3318 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3319 return true;
3320 }
3321#endif
John Kessenich0e737842017-03-24 18:38:16 -06003322
3323 return false;
3324};
3325
John Kessenich6090df02016-06-30 21:18:02 -06003326// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3327// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3328// Mutually recursive with convertGlslangToSpvType().
3329spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3330 const glslang::TTypeList* glslangMembers,
3331 glslang::TLayoutPacking explicitLayout,
3332 const glslang::TQualifier& qualifier)
3333{
3334 // Create a vector of struct types for SPIR-V to consume
3335 std::vector<spv::Id> spvMembers;
3336 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 -06003337 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003338 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3339 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3340 if (glslangMember.hiddenMember()) {
3341 ++memberDelta;
3342 if (type.getBasicType() == glslang::EbtBlock)
3343 memberRemapper[glslangMembers][i] = -1;
3344 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003345 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003346 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003347 if (filterMember(glslangMember))
3348 continue;
3349 }
John Kessenich6090df02016-06-30 21:18:02 -06003350 // modify just this child's view of the qualifier
3351 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3352 InheritQualifiers(memberQualifier, qualifier);
3353
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003354 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003355 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003356 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003357
3358 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003359 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3360 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003361
3362 // Make forward pointers for any pointer members, and create a list of members to
3363 // convert to spirv types after creating the struct.
3364 if (glslangMember.getBasicType() == glslang::EbtReference) {
3365 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3366 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3367 }
3368 spvMembers.push_back(
3369 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3370 } else {
3371 spvMembers.push_back(
3372 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3373 }
John Kessenich6090df02016-06-30 21:18:02 -06003374 }
3375 }
3376
3377 // Make the SPIR-V type
3378 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003379 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003380 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3381
3382 // Decorate it
3383 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3384
John Kessenichd72f4882019-01-16 14:55:37 +07003385 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003386 auto it = deferredForwardPointers[i];
3387 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3388 }
3389
John Kessenich6090df02016-06-30 21:18:02 -06003390 return spvType;
3391}
3392
3393void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3394 const glslang::TTypeList* glslangMembers,
3395 glslang::TLayoutPacking explicitLayout,
3396 const glslang::TQualifier& qualifier,
3397 spv::Id spvType)
3398{
3399 // Name and decorate the non-hidden members
3400 int offset = -1;
3401 int locationOffset = 0; // for use within the members of this struct
3402 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3403 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3404 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003405 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003406 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003407 if (filterMember(glslangMember))
3408 continue;
3409 }
John Kessenich6090df02016-06-30 21:18:02 -06003410
3411 // modify just this child's view of the qualifier
3412 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3413 InheritQualifiers(memberQualifier, qualifier);
3414
3415 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003416 if (member < 0)
3417 continue;
3418
3419 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3420 builder.addMemberDecoration(spvType, member,
3421 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3422 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3423 // Add interpolation and auxiliary storage decorations only to
3424 // top-level members of Input and Output storage classes
3425 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3426 type.getQualifier().storage == glslang::EvqVaryingOut) {
3427 if (type.getBasicType() == glslang::EbtBlock ||
3428 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3429 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3430 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003431#ifdef NV_EXTENSIONS
3432 addMeshNVDecoration(spvType, member, memberQualifier);
3433#endif
John Kessenich6090df02016-06-30 21:18:02 -06003434 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003435 }
3436 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003437
John Kessenich5d610ee2018-03-07 18:05:55 -07003438 if (type.getBasicType() == glslang::EbtBlock &&
3439 qualifier.storage == glslang::EvqBuffer) {
3440 // Add memory decorations only to top-level members of shader storage block
3441 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003442 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003443 for (unsigned int i = 0; i < memory.size(); ++i)
3444 builder.addMemberDecoration(spvType, member, memory[i]);
3445 }
John Kessenich6090df02016-06-30 21:18:02 -06003446
John Kessenich5d610ee2018-03-07 18:05:55 -07003447 // Location assignment was already completed correctly by the front end,
3448 // just track whether a member needs to be decorated.
3449 // Ignore member locations if the container is an array, as that's
3450 // ill-specified and decisions have been made to not allow this.
3451 if (! type.isArray() && memberQualifier.hasLocation())
3452 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003453
John Kessenich5d610ee2018-03-07 18:05:55 -07003454 if (qualifier.hasLocation()) // track for upcoming inheritance
3455 locationOffset += glslangIntermediate->computeTypeLocationSize(
3456 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003457
John Kessenich5d610ee2018-03-07 18:05:55 -07003458 // component, XFB, others
3459 if (glslangMember.getQualifier().hasComponent())
3460 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3461 glslangMember.getQualifier().layoutComponent);
3462 if (glslangMember.getQualifier().hasXfbOffset())
3463 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3464 glslangMember.getQualifier().layoutXfbOffset);
3465 else if (explicitLayout != glslang::ElpNone) {
3466 // figure out what to do with offset, which is accumulating
3467 int nextOffset;
3468 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3469 if (offset >= 0)
3470 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3471 offset = nextOffset;
3472 }
John Kessenich6090df02016-06-30 21:18:02 -06003473
John Kessenich5d610ee2018-03-07 18:05:55 -07003474 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3475 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3476 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003477
John Kessenich5d610ee2018-03-07 18:05:55 -07003478 // built-in variable decorations
3479 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3480 if (builtIn != spv::BuiltInMax)
3481 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003482
John Kessenich5611c6d2018-04-05 11:25:02 -06003483 // nonuniform
3484 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3485
John Kessenichead86222018-03-28 18:01:20 -06003486 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3487 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3488 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3489 memberQualifier.semanticName);
3490 }
3491
chaoc771d89f2017-01-13 01:10:53 -08003492#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003493 if (builtIn == spv::BuiltInLayer) {
3494 // SPV_NV_viewport_array2 extension
3495 if (glslangMember.getQualifier().layoutViewportRelative){
3496 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3497 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3498 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003499 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003500 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3501 builder.addMemberDecoration(spvType, member,
3502 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3503 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3504 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3505 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003506 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003507 }
3508 if (glslangMember.getQualifier().layoutPassthrough) {
3509 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3510 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3511 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3512 }
chaoc771d89f2017-01-13 01:10:53 -08003513#endif
John Kessenich6090df02016-06-30 21:18:02 -06003514 }
3515
3516 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003517 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3518 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003519}
3520
John Kessenich6c292d32016-02-15 20:58:50 -07003521// Turn the expression forming the array size into an id.
3522// This is not quite trivial, because of specialization constants.
3523// Sometimes, a raw constant is turned into an Id, and sometimes
3524// a specialization constant expression is.
3525spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3526{
3527 // First, see if this is sized with a node, meaning a specialization constant:
3528 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3529 if (specNode != nullptr) {
3530 builder.clearAccessChain();
3531 specNode->traverse(this);
3532 return accessChainLoad(specNode->getAsTyped()->getType());
3533 }
qining25262b32016-05-06 17:25:16 -04003534
John Kessenich6c292d32016-02-15 20:58:50 -07003535 // Otherwise, need a compile-time (front end) size, get it:
3536 int size = arraySizes.getDimSize(dim);
3537 assert(size > 0);
3538 return builder.makeUintConstant(size);
3539}
3540
John Kessenich103bef92016-02-08 21:38:15 -07003541// Wrap the builder's accessChainLoad to:
3542// - localize handling of RelaxedPrecision
3543// - use the SPIR-V inferred type instead of another conversion of the glslang type
3544// (avoids unnecessary work and possible type punning for structures)
3545// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003546spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3547{
John Kessenich103bef92016-02-08 21:38:15 -07003548 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003549
3550 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3551 coherentFlags |= TranslateCoherent(type);
3552
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003553 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003554 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003555
John Kessenich5611c6d2018-04-05 11:25:02 -06003556 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003557 TranslateNonUniformDecoration(type.getQualifier()),
3558 nominalTypeId,
3559 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003560 TranslateMemoryScope(coherentFlags),
3561 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003562
3563 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003564 if (type.getBasicType() == glslang::EbtBool) {
3565 if (builder.isScalarType(nominalTypeId)) {
3566 // Conversion for bool
3567 spv::Id boolType = builder.makeBoolType();
3568 if (nominalTypeId != boolType)
3569 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3570 } else if (builder.isVectorType(nominalTypeId)) {
3571 // Conversion for bvec
3572 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3573 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3574 if (nominalTypeId != bvecType)
3575 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3576 }
3577 }
John Kessenich103bef92016-02-08 21:38:15 -07003578
3579 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003580}
3581
Rex Xu27253232016-02-23 17:51:09 +08003582// Wrap the builder's accessChainStore to:
3583// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003584//
3585// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003586void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3587{
3588 // Need to convert to abstract types when necessary
3589 if (type.getBasicType() == glslang::EbtBool) {
3590 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3591
3592 if (builder.isScalarType(nominalTypeId)) {
3593 // Conversion for bool
3594 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003595 if (nominalTypeId != boolType) {
3596 // keep these outside arguments, for determinant order-of-evaluation
3597 spv::Id one = builder.makeUintConstant(1);
3598 spv::Id zero = builder.makeUintConstant(0);
3599 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3600 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003601 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003602 } else if (builder.isVectorType(nominalTypeId)) {
3603 // Conversion for bvec
3604 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3605 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003606 if (nominalTypeId != bvecType) {
3607 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003608 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3609 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3610 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003611 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003612 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3613 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003614 }
3615 }
3616
Jeff Bolz36831c92018-09-05 10:11:41 -05003617 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3618 coherentFlags |= TranslateCoherent(type);
3619
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003620 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003621 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003622
Jeff Bolz36831c92018-09-05 10:11:41 -05003623 builder.accessChainStore(rvalue,
3624 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003625 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003626}
3627
John Kessenich4bf71552016-09-02 11:20:21 -06003628// For storing when types match at the glslang level, but not might match at the
3629// SPIR-V level.
3630//
3631// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003632// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003633// as in a member-decorated way.
3634//
3635// NOTE: This function can handle any store request; if it's not special it
3636// simplifies to a simple OpStore.
3637//
3638// Implicitly uses the existing builder.accessChain as the storage target.
3639void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3640{
John Kessenichb3e24e42016-09-11 12:33:43 -06003641 // we only do the complex path here if it's an aggregate
3642 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003643 accessChainStore(type, rValue);
3644 return;
3645 }
3646
John Kessenichb3e24e42016-09-11 12:33:43 -06003647 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003648 spv::Id rType = builder.getTypeId(rValue);
3649 spv::Id lValue = builder.accessChainGetLValue();
3650 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3651 if (lType == rType) {
3652 accessChainStore(type, rValue);
3653 return;
3654 }
3655
John Kessenichb3e24e42016-09-11 12:33:43 -06003656 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003657 // where the two types were the same type in GLSL. This requires member
3658 // by member copy, recursively.
3659
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003660 // SPIR-V 1.4 added an instruction to do help do this.
3661 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3662 // However, bool in uniform space is changed to int, so
3663 // OpCopyLogical does not work for that.
3664 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3665 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3666 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3667 if (lBool == rBool) {
3668 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3669 accessChainStore(type, logicalCopy);
3670 return;
3671 }
3672 }
3673
John Kessenichb3e24e42016-09-11 12:33:43 -06003674 // If an array, copy element by element.
3675 if (type.isArray()) {
3676 glslang::TType glslangElementType(type, 0);
3677 spv::Id elementRType = builder.getContainedTypeId(rType);
3678 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3679 // get the source member
3680 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003681
John Kessenichb3e24e42016-09-11 12:33:43 -06003682 // set up the target storage
3683 builder.clearAccessChain();
3684 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003685 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003686
John Kessenichb3e24e42016-09-11 12:33:43 -06003687 // store the member
3688 multiTypeStore(glslangElementType, elementRValue);
3689 }
3690 } else {
3691 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003692
John Kessenichb3e24e42016-09-11 12:33:43 -06003693 // loop over structure members
3694 const glslang::TTypeList& members = *type.getStruct();
3695 for (int m = 0; m < (int)members.size(); ++m) {
3696 const glslang::TType& glslangMemberType = *members[m].type;
3697
3698 // get the source member
3699 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3700 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3701
3702 // set up the target storage
3703 builder.clearAccessChain();
3704 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003705 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003706
3707 // store the member
3708 multiTypeStore(glslangMemberType, memberRValue);
3709 }
John Kessenich4bf71552016-09-02 11:20:21 -06003710 }
3711}
3712
John Kessenichf85e8062015-12-19 13:57:10 -07003713// Decide whether or not this type should be
3714// decorated with offsets and strides, and if so
3715// whether std140 or std430 rules should be applied.
3716glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003717{
John Kessenichf85e8062015-12-19 13:57:10 -07003718 // has to be a block
3719 if (type.getBasicType() != glslang::EbtBlock)
3720 return glslang::ElpNone;
3721
Chao Chen3c366992018-09-19 11:41:59 -07003722 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003723 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003724 type.getQualifier().storage != glslang::EvqBuffer &&
3725 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003726 return glslang::ElpNone;
3727
3728 // return the layout to use
3729 switch (type.getQualifier().layoutPacking) {
3730 case glslang::ElpStd140:
3731 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003732 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003733 return type.getQualifier().layoutPacking;
3734 default:
3735 return glslang::ElpNone;
3736 }
John Kessenich31ed4832015-09-09 17:51:38 -06003737}
3738
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003739// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003740int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003741{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003742 int size;
John Kessenich49987892015-12-29 17:11:44 -07003743 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003744 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003745
3746 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003747}
3748
John Kessenich49987892015-12-29 17:11:44 -07003749// 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 -07003750// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003751int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003752{
John Kessenich49987892015-12-29 17:11:44 -07003753 glslang::TType elementType;
3754 elementType.shallowCopy(matrixType);
3755 elementType.clearArraySizes();
3756
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003757 int size;
John Kessenich49987892015-12-29 17:11:44 -07003758 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003759 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003760
3761 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003762}
3763
John Kessenich5e4b1242015-08-06 22:53:06 -06003764// Given a member type of a struct, realign the current offset for it, and compute
3765// the next (not yet aligned) offset for the next member, which will get aligned
3766// on the next call.
3767// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3768// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3769// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003770void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003771 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003772{
3773 // this will get a positive value when deemed necessary
3774 nextOffset = -1;
3775
John Kessenich5e4b1242015-08-06 22:53:06 -06003776 // override anything in currentOffset with user-set offset
3777 if (memberType.getQualifier().hasOffset())
3778 currentOffset = memberType.getQualifier().layoutOffset;
3779
3780 // It could be that current linker usage in glslang updated all the layoutOffset,
3781 // in which case the following code does not matter. But, that's not quite right
3782 // once cross-compilation unit GLSL validation is done, as the original user
3783 // settings are needed in layoutOffset, and then the following will come into play.
3784
John Kessenichf85e8062015-12-19 13:57:10 -07003785 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003786 if (! memberType.getQualifier().hasOffset())
3787 currentOffset = -1;
3788
3789 return;
3790 }
3791
John Kessenichf85e8062015-12-19 13:57:10 -07003792 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003793 if (currentOffset < 0)
3794 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003795
John Kessenich5e4b1242015-08-06 22:53:06 -06003796 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3797 // but possibly not yet correctly aligned.
3798
3799 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003800 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003801 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003802
3803 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003804 // TODO: make this consistent in early phases of code:
3805 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3806 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3807 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003808 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003809 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003810 int dummySize;
3811 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3812 if (componentAlignment <= 4)
3813 memberAlignment = componentAlignment;
3814 }
3815
3816 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003817 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003818
3819 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003820 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003821 glslang::RoundToPow2(currentOffset, 16);
3822
John Kessenich5e4b1242015-08-06 22:53:06 -06003823 nextOffset = currentOffset + memberSize;
3824}
3825
David Netoa901ffe2016-06-08 14:11:40 +01003826void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003827{
David Netoa901ffe2016-06-08 14:11:40 +01003828 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3829 switch (glslangBuiltIn)
3830 {
3831 case glslang::EbvClipDistance:
3832 case glslang::EbvCullDistance:
3833 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003834#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003835 case glslang::EbvViewportMaskNV:
3836 case glslang::EbvSecondaryPositionNV:
3837 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003838 case glslang::EbvPositionPerViewNV:
3839 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003840 case glslang::EbvTaskCountNV:
3841 case glslang::EbvPrimitiveCountNV:
3842 case glslang::EbvPrimitiveIndicesNV:
3843 case glslang::EbvClipDistancePerViewNV:
3844 case glslang::EbvCullDistancePerViewNV:
3845 case glslang::EbvLayerPerViewNV:
3846 case glslang::EbvMeshViewCountNV:
3847 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003848#endif
David Netoa901ffe2016-06-08 14:11:40 +01003849 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3850 // Alternately, we could just call this for any glslang built-in, since the
3851 // capability already guards against duplicates.
3852 TranslateBuiltInDecoration(glslangBuiltIn, false);
3853 break;
3854 default:
3855 // Capabilities were already generated when the struct was declared.
3856 break;
3857 }
John Kessenichebb50532016-05-16 19:22:05 -06003858}
3859
John Kessenich6fccb3c2016-09-19 16:01:41 -06003860bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003861{
John Kessenicheee9d532016-09-19 18:09:30 -06003862 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003863}
3864
John Kessenichd41993d2017-09-10 15:21:05 -06003865// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003866// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3867// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003868bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003869{
John Kessenich6a14f782017-12-04 02:48:10 -07003870 assert(qualifier == glslang::EvqIn ||
3871 qualifier == glslang::EvqOut ||
3872 qualifier == glslang::EvqInOut ||
3873 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003874 return qualifier != glslang::EvqConstReadOnly;
3875}
3876
3877// Is parameter pass-by-original?
3878bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3879 bool implicitThisParam)
3880{
3881 if (implicitThisParam) // implicit this
3882 return true;
3883 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003884 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003885 return paramType.containsOpaque() || // sampler, etc.
3886 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3887}
3888
John Kessenich140f3df2015-06-26 16:58:36 -06003889// Make all the functions, skeletally, without actually visiting their bodies.
3890void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3891{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003892 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003893 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3894 if (paramPrecision != spv::NoPrecision)
3895 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003896 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003897 if (type.getBasicType() == glslang::EbtReference) {
3898 // Original and non-writable params pass the pointer directly and
3899 // use restrict/aliased, others are stored to a pointer in Function
3900 // memory and use RestrictPointer/AliasedPointer.
3901 if (originalParam(type.getQualifier().storage, type, false) ||
3902 !writableParam(type.getQualifier().storage)) {
3903 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
3904 } else {
3905 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
3906 }
3907 }
John Kessenichfad62972017-07-18 02:35:46 -06003908 };
3909
John Kessenich140f3df2015-06-26 16:58:36 -06003910 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3911 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003912 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003913 continue;
3914
3915 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003916 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003917 //
qining25262b32016-05-06 17:25:16 -04003918 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003919 // function. What it is an address of varies:
3920 //
John Kessenich4bf71552016-09-02 11:20:21 -06003921 // - "in" parameters not marked as "const" can be written to without modifying the calling
3922 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003923 //
3924 // - "const in" parameters can just be the r-value, as no writes need occur.
3925 //
John Kessenich4bf71552016-09-02 11:20:21 -06003926 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3927 // 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 -06003928
3929 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003930 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003931 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3932
John Kessenichfad62972017-07-18 02:35:46 -06003933 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3934 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003935
John Kessenichfad62972017-07-18 02:35:46 -06003936 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003937 for (int p = 0; p < (int)parameters.size(); ++p) {
3938 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3939 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003940 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003941 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003942 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003943 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3944 else
John Kessenich4bf71552016-09-02 11:20:21 -06003945 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003946 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003947 paramTypes.push_back(typeId);
3948 }
3949
3950 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003951 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3952 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003953 glslFunction->getName().c_str(), paramTypes,
3954 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003955 if (implicitThis)
3956 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003957
3958 // Track function to emit/call later
3959 functionMap[glslFunction->getName().c_str()] = function;
3960
3961 // Set the parameter id's
3962 for (int p = 0; p < (int)parameters.size(); ++p) {
3963 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3964 // give a name too
3965 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3966 }
3967 }
3968}
3969
3970// Process all the initializers, while skipping the functions and link objects
3971void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3972{
3973 builder.setBuildPoint(shaderEntry->getLastBlock());
3974 for (int i = 0; i < (int)initializers.size(); ++i) {
3975 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3976 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3977
3978 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003979 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003980 initializer->traverse(this);
3981 }
3982 }
3983}
3984
3985// Process all the functions, while skipping initializers.
3986void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3987{
3988 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3989 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003990 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003991 node->traverse(this);
3992 }
3993}
3994
3995void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3996{
qining25262b32016-05-06 17:25:16 -04003997 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003998 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003999 currentFunction = functionMap[node->getName().c_str()];
4000 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004001 builder.setBuildPoint(functionBlock);
4002}
4003
Rex Xu04db3f52015-09-16 11:44:02 +08004004void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004005{
Rex Xufc618912015-09-09 16:42:49 +08004006 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004007
4008 glslang::TSampler sampler = {};
4009 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004010#ifdef AMD_EXTENSIONS
4011 bool f16ShadowCompare = false;
4012#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004013 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004014 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4015 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004016#ifdef AMD_EXTENSIONS
4017 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4018#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004019 }
4020
John Kessenich140f3df2015-06-26 16:58:36 -06004021 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4022 builder.clearAccessChain();
4023 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004024
4025 // Special case l-value operands
4026 bool lvalue = false;
4027 switch (node.getOp()) {
4028 case glslang::EOpImageAtomicAdd:
4029 case glslang::EOpImageAtomicMin:
4030 case glslang::EOpImageAtomicMax:
4031 case glslang::EOpImageAtomicAnd:
4032 case glslang::EOpImageAtomicOr:
4033 case glslang::EOpImageAtomicXor:
4034 case glslang::EOpImageAtomicExchange:
4035 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004036 case glslang::EOpImageAtomicLoad:
4037 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004038 if (i == 0)
4039 lvalue = true;
4040 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004041 case glslang::EOpSparseImageLoad:
4042 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4043 lvalue = true;
4044 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004045#ifdef AMD_EXTENSIONS
4046 case glslang::EOpSparseTexture:
4047 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4048 lvalue = true;
4049 break;
4050 case glslang::EOpSparseTextureClamp:
4051 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4052 lvalue = true;
4053 break;
4054 case glslang::EOpSparseTextureLod:
4055 case glslang::EOpSparseTextureOffset:
4056 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4057 lvalue = true;
4058 break;
4059#else
Rex Xu48edadf2015-12-31 16:11:41 +08004060 case glslang::EOpSparseTexture:
4061 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4062 lvalue = true;
4063 break;
4064 case glslang::EOpSparseTextureClamp:
4065 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4066 lvalue = true;
4067 break;
4068 case glslang::EOpSparseTextureLod:
4069 case glslang::EOpSparseTextureOffset:
4070 if (i == 3)
4071 lvalue = true;
4072 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004073#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004074 case glslang::EOpSparseTextureFetch:
4075 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4076 lvalue = true;
4077 break;
4078 case glslang::EOpSparseTextureFetchOffset:
4079 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4080 lvalue = true;
4081 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004082#ifdef AMD_EXTENSIONS
4083 case glslang::EOpSparseTextureLodOffset:
4084 case glslang::EOpSparseTextureGrad:
4085 case glslang::EOpSparseTextureOffsetClamp:
4086 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4087 lvalue = true;
4088 break;
4089 case glslang::EOpSparseTextureGradOffset:
4090 case glslang::EOpSparseTextureGradClamp:
4091 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4092 lvalue = true;
4093 break;
4094 case glslang::EOpSparseTextureGradOffsetClamp:
4095 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4096 lvalue = true;
4097 break;
4098#else
Rex Xu48edadf2015-12-31 16:11:41 +08004099 case glslang::EOpSparseTextureLodOffset:
4100 case glslang::EOpSparseTextureGrad:
4101 case glslang::EOpSparseTextureOffsetClamp:
4102 if (i == 4)
4103 lvalue = true;
4104 break;
4105 case glslang::EOpSparseTextureGradOffset:
4106 case glslang::EOpSparseTextureGradClamp:
4107 if (i == 5)
4108 lvalue = true;
4109 break;
4110 case glslang::EOpSparseTextureGradOffsetClamp:
4111 if (i == 6)
4112 lvalue = true;
4113 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004114#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004115 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004116 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4117 lvalue = true;
4118 break;
4119 case glslang::EOpSparseTextureGatherOffset:
4120 case glslang::EOpSparseTextureGatherOffsets:
4121 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4122 lvalue = true;
4123 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004124#ifdef AMD_EXTENSIONS
4125 case glslang::EOpSparseTextureGatherLod:
4126 if (i == 3)
4127 lvalue = true;
4128 break;
4129 case glslang::EOpSparseTextureGatherLodOffset:
4130 case glslang::EOpSparseTextureGatherLodOffsets:
4131 if (i == 4)
4132 lvalue = true;
4133 break;
Rex Xu129799a2017-07-05 17:23:28 +08004134 case glslang::EOpSparseImageLoadLod:
4135 if (i == 3)
4136 lvalue = true;
4137 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004138#endif
Chao Chen3a137962018-09-19 11:41:27 -07004139#ifdef NV_EXTENSIONS
4140 case glslang::EOpImageSampleFootprintNV:
4141 if (i == 4)
4142 lvalue = true;
4143 break;
4144 case glslang::EOpImageSampleFootprintClampNV:
4145 case glslang::EOpImageSampleFootprintLodNV:
4146 if (i == 5)
4147 lvalue = true;
4148 break;
4149 case glslang::EOpImageSampleFootprintGradNV:
4150 if (i == 6)
4151 lvalue = true;
4152 break;
4153 case glslang::EOpImageSampleFootprintGradClampNV:
4154 if (i == 7)
4155 lvalue = true;
4156 break;
4157#endif
Rex Xufc618912015-09-09 16:42:49 +08004158 default:
4159 break;
4160 }
4161
Rex Xu6b86d492015-09-16 17:48:22 +08004162 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08004163 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08004164 else
John Kessenich32cfd492016-02-02 12:37:46 -07004165 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004166 }
4167}
4168
John Kessenichfc51d282015-08-19 13:34:18 -06004169void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004170{
John Kessenichfc51d282015-08-19 13:34:18 -06004171 builder.clearAccessChain();
4172 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004173 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004174}
John Kessenich140f3df2015-06-26 16:58:36 -06004175
John Kessenichfc51d282015-08-19 13:34:18 -06004176spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4177{
John Kesseniche485c7a2017-05-31 18:50:53 -06004178 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004179 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004180
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004181 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004182
John Kessenichfc51d282015-08-19 13:34:18 -06004183 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004184
John Kessenichf43c7392019-03-31 10:51:57 -06004185 const glslang::TType &imageType = node->getAsAggregate()
4186 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4187 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004188 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004189#ifdef AMD_EXTENSIONS
4190 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004191 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4192 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004193#endif
4194
John Kessenichf43c7392019-03-31 10:51:57 -06004195 const auto signExtensionMask = [&]() {
4196 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4197 if (sampler.type == glslang::EbtUint)
4198 return spv::ImageOperandsZeroExtendMask;
4199 else if (sampler.type == glslang::EbtInt)
4200 return spv::ImageOperandsSignExtendMask;
4201 }
4202 return spv::ImageOperandsMaskNone;
4203 };
4204
John Kessenichfc51d282015-08-19 13:34:18 -06004205 std::vector<spv::Id> arguments;
4206 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08004207 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06004208 else
4209 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004210 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004211
4212 spv::Builder::TextureParameters params = { };
4213 params.sampler = arguments[0];
4214
Rex Xu04db3f52015-09-16 11:44:02 +08004215 glslang::TCrackedTextureOp cracked;
4216 node->crackTexture(sampler, cracked);
4217
amhagan05506bb2017-06-13 16:53:02 -04004218 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004219
John Kessenichfc51d282015-08-19 13:34:18 -06004220 // Check for queries
4221 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004222 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4223 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004224 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004225
John Kessenichfc51d282015-08-19 13:34:18 -06004226 switch (node->getOp()) {
4227 case glslang::EOpImageQuerySize:
4228 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004229 if (arguments.size() > 1) {
4230 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004231 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004232 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004233 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004234 case glslang::EOpImageQuerySamples:
4235 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004236 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004237 case glslang::EOpTextureQueryLod:
4238 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004239 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004240 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004241 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004242 case glslang::EOpSparseTexelsResident:
4243 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004244 default:
4245 assert(0);
4246 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004247 }
John Kessenich140f3df2015-06-26 16:58:36 -06004248 }
4249
LoopDawg4425f242018-02-18 11:40:01 -07004250 int components = node->getType().getVectorSize();
4251
4252 if (node->getOp() == glslang::EOpTextureFetch) {
4253 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4254 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4255 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4256 // here around e.g. which ones return scalars or other types.
4257 components = 4;
4258 }
4259
4260 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4261
4262 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4263
Rex Xufc618912015-09-09 16:42:49 +08004264 // Check for image functions other than queries
4265 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004266 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004267 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004268 spv::IdImmediate image = { true, *(opIt++) };
4269 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004270
4271 // Handle subpass operations
4272 // TODO: GLSL should change to have the "MS" only on the type rather than the
4273 // built-in function.
4274 if (cracked.subpass) {
4275 // add on the (0,0) coordinate
4276 spv::Id zero = builder.makeIntConstant(0);
4277 std::vector<spv::Id> comps;
4278 comps.push_back(zero);
4279 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004280 spv::IdImmediate coord = { true,
4281 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4282 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004283 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4284 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich6c292d32016-02-15 20:58:50 -07004285 if (sampler.ms) {
John Kessenichf43c7392019-03-31 10:51:57 -06004286 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4287 }
4288 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004289 operands.push_back(imageOperands);
John Kessenichf43c7392019-03-31 10:51:57 -06004290 if (sampler.ms) {
4291 spv::IdImmediate imageOperand = { true, *(opIt++) };
4292 operands.push_back(imageOperand);
4293 }
John Kessenich6c292d32016-02-15 20:58:50 -07004294 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004295 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4296 builder.setPrecision(result, precision);
4297 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004298 }
4299
John Kessenich149afc32018-08-14 13:31:43 -06004300 spv::IdImmediate coord = { true, *(opIt++) };
4301 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004302#ifdef AMD_EXTENSIONS
4303 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4304#else
John Kessenich56bab042015-09-16 10:54:31 -06004305 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004306#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004307 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004308 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004309 mask = mask | spv::ImageOperandsSampleMask;
4310 }
Rex Xu129799a2017-07-05 17:23:28 +08004311#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004312 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004313 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4314 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004315 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004316 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004317#endif
4318 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4319 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004320 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004321 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004322 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4323 operands.push_back(imageOperands);
4324 }
4325 if (mask & spv::ImageOperandsSampleMask) {
4326 spv::IdImmediate imageOperand = { true, *opIt++ };
4327 operands.push_back(imageOperand);
4328 }
4329#ifdef AMD_EXTENSIONS
4330 if (mask & spv::ImageOperandsLodMask) {
4331 spv::IdImmediate imageOperand = { true, *opIt++ };
4332 operands.push_back(imageOperand);
4333 }
4334#endif
4335 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004336 spv::IdImmediate imageOperand = { true,
4337 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004338 operands.push_back(imageOperand);
4339 }
4340
John Kessenich149afc32018-08-14 13:31:43 -06004341 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004342 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004343
John Kessenich149afc32018-08-14 13:31:43 -06004344 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004345 builder.setPrecision(result[0], precision);
4346
4347 // If needed, add a conversion constructor to the proper size.
4348 if (components != node->getType().getVectorSize())
4349 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4350
4351 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004352#ifdef AMD_EXTENSIONS
4353 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4354#else
John Kessenich56bab042015-09-16 10:54:31 -06004355 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004356#endif
Rex Xu129799a2017-07-05 17:23:28 +08004357
Jeff Bolz36831c92018-09-05 10:11:41 -05004358 // Push the texel value before the operands
4359#ifdef AMD_EXTENSIONS
4360 if (sampler.ms || cracked.lod) {
4361#else
4362 if (sampler.ms) {
4363#endif
John Kessenich149afc32018-08-14 13:31:43 -06004364 spv::IdImmediate texel = { true, *(opIt + 1) };
4365 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004366 } else {
4367 spv::IdImmediate texel = { true, *opIt };
4368 operands.push_back(texel);
4369 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004370
4371 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4372 if (sampler.ms) {
4373 mask = mask | spv::ImageOperandsSampleMask;
4374 }
4375#ifdef AMD_EXTENSIONS
4376 if (cracked.lod) {
4377 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4378 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4379 mask = mask | spv::ImageOperandsLodMask;
4380 }
4381#endif
4382 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4383 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004384 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004385 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004386 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4387 operands.push_back(imageOperands);
4388 }
4389 if (mask & spv::ImageOperandsSampleMask) {
4390 spv::IdImmediate imageOperand = { true, *opIt++ };
4391 operands.push_back(imageOperand);
4392 }
4393#ifdef AMD_EXTENSIONS
4394 if (mask & spv::ImageOperandsLodMask) {
4395 spv::IdImmediate imageOperand = { true, *opIt++ };
4396 operands.push_back(imageOperand);
4397 }
4398#endif
4399 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004400 spv::IdImmediate imageOperand = { true,
4401 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004402 operands.push_back(imageOperand);
4403 }
4404
John Kessenich56bab042015-09-16 10:54:31 -06004405 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004406 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004407 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004408 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004409#ifdef AMD_EXTENSIONS
John Kessenichf43c7392019-03-31 10:51:57 -06004410 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4411 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004412#else
Rex Xu5eafa472016-02-19 22:24:03 +08004413 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004414#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004415 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004416 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004417 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4418
Jeff Bolz36831c92018-09-05 10:11:41 -05004419 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004420 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004421 mask = mask | spv::ImageOperandsSampleMask;
4422 }
Rex Xu129799a2017-07-05 17:23:28 +08004423#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004424 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004425 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4426 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4427
Jeff Bolz36831c92018-09-05 10:11:41 -05004428 mask = mask | spv::ImageOperandsLodMask;
4429 }
4430#endif
4431 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4432 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004433 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004434 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004435 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004436 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004437 }
4438 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004439 spv::IdImmediate imageOperand = { true, *opIt++ };
4440 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004441 }
4442#ifdef AMD_EXTENSIONS
4443 if (mask & spv::ImageOperandsLodMask) {
4444 spv::IdImmediate imageOperand = { true, *opIt++ };
4445 operands.push_back(imageOperand);
4446 }
Rex Xu129799a2017-07-05 17:23:28 +08004447#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004448 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4449 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4450 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004451 }
4452
4453 // Create the return type that was a special structure
4454 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004455 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004456 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4457 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4458
4459 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4460
4461 // Decode the return type
4462 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4463 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004464 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004465 // Process image atomic operations
4466
4467 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4468 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004469 // For non-MS, the sample value should be 0
4470 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4471 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004472
Jeff Bolz36831c92018-09-05 10:11:41 -05004473 spv::Id resultTypeId;
4474 // imageAtomicStore has a void return type so base the pointer type on
4475 // the type of the value operand.
4476 if (node->getOp() == glslang::EOpImageAtomicStore) {
4477 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4478 } else {
4479 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4480 }
John Kessenich56bab042015-09-16 10:54:31 -06004481 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004482
4483 std::vector<spv::Id> operands;
4484 operands.push_back(pointer);
4485 for (; opIt != arguments.end(); ++opIt)
4486 operands.push_back(*opIt);
4487
John Kessenich8c8505c2016-07-26 12:50:38 -06004488 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004489 }
4490 }
4491
amhagan05506bb2017-06-13 16:53:02 -04004492#ifdef AMD_EXTENSIONS
4493 // Check for fragment mask functions other than queries
4494 if (cracked.fragMask) {
4495 assert(sampler.ms);
4496
4497 auto opIt = arguments.begin();
4498 std::vector<spv::Id> operands;
4499
4500 // Extract the image if necessary
4501 if (builder.isSampledImage(params.sampler))
4502 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4503
4504 operands.push_back(params.sampler);
4505 ++opIt;
4506
4507 if (sampler.isSubpass()) {
4508 // add on the (0,0) coordinate
4509 spv::Id zero = builder.makeIntConstant(0);
4510 std::vector<spv::Id> comps;
4511 comps.push_back(zero);
4512 comps.push_back(zero);
4513 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4514 }
4515
4516 for (; opIt != arguments.end(); ++opIt)
4517 operands.push_back(*opIt);
4518
4519 spv::Op fragMaskOp = spv::OpNop;
4520 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4521 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4522 else if (node->getOp() == glslang::EOpFragmentFetch)
4523 fragMaskOp = spv::OpFragmentFetchAMD;
4524
4525 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4526 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4527 return builder.createOp(fragMaskOp, resultType(), operands);
4528 }
4529#endif
4530
Rex Xufc618912015-09-09 16:42:49 +08004531 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004532 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004533#ifdef NV_EXTENSIONS
4534 bool imageFootprint = node->isImageFootprint();
4535#endif
4536
Rex Xu71519fe2015-11-11 15:35:47 +08004537 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4538
John Kessenichfc51d282015-08-19 13:34:18 -06004539 // check for bias argument
4540 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004541#ifdef AMD_EXTENSIONS
4542 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4543#else
Rex Xu71519fe2015-11-11 15:35:47 +08004544 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004545#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004546 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004547#ifdef AMD_EXTENSIONS
4548 if (cracked.gather)
4549 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004550
4551 if (f16ShadowCompare)
4552 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004553#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004554 if (cracked.offset)
4555 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004556#ifdef AMD_EXTENSIONS
4557 else if (cracked.offsets)
4558 ++nonBiasArgCount;
4559#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004560 if (cracked.grad)
4561 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004562 if (cracked.lodClamp)
4563 ++nonBiasArgCount;
4564 if (sparse)
4565 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004566#ifdef NV_EXTENSIONS
4567 if (imageFootprint)
4568 //Following three extra arguments
4569 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4570 nonBiasArgCount += 3;
4571#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004572 if ((int)arguments.size() > nonBiasArgCount)
4573 bias = true;
4574 }
4575
John Kessenicha5c33d62016-06-02 23:45:21 -06004576 // See if the sampler param should really be just the SPV image part
4577 if (cracked.fetch) {
4578 // a fetch needs to have the image extracted first
4579 if (builder.isSampledImage(params.sampler))
4580 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4581 }
4582
Rex Xu225e0fc2016-11-17 17:47:59 +08004583#ifdef AMD_EXTENSIONS
4584 if (cracked.gather) {
4585 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4586 if (bias || cracked.lod ||
4587 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4588 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004589 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004590 }
4591 }
4592#endif
4593
John Kessenichfc51d282015-08-19 13:34:18 -06004594 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004595
John Kessenichfc51d282015-08-19 13:34:18 -06004596 params.coords = arguments[1];
4597 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004598 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004599
4600 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004601#ifdef AMD_EXTENSIONS
4602 if (cubeCompare || f16ShadowCompare) {
4603#else
Rex Xu48edadf2015-12-31 16:11:41 +08004604 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004605#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004606 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004607 ++extraArgs;
4608 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004609 params.Dref = arguments[2];
4610 ++extraArgs;
4611 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004612 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004613 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004614 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004615 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004616 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004617 dRefComp = builder.getNumComponents(params.coords) - 1;
4618 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004619 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4620 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004621
4622 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004623 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004624 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004625 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004626 } else if (glslangIntermediate->getStage() != EShLangFragment
4627#ifdef NV_EXTENSIONS
4628 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4629 && !(glslangIntermediate->getStage() == EShLangCompute &&
4630 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4631#endif
4632 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004633 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4634 noImplicitLod = true;
4635 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004636
4637 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004638 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004639 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004640 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004641 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004642
4643 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004644 if (cracked.grad) {
4645 params.gradX = arguments[2 + extraArgs];
4646 params.gradY = arguments[3 + extraArgs];
4647 extraArgs += 2;
4648 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004649
4650 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004651 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004652 params.offset = arguments[2 + extraArgs];
4653 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004654 } else if (cracked.offsets) {
4655 params.offsets = arguments[2 + extraArgs];
4656 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004657 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004658
4659 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004660 if (cracked.lodClamp) {
4661 params.lodClamp = arguments[2 + extraArgs];
4662 ++extraArgs;
4663 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004664 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004665 if (sparse) {
4666 params.texelOut = arguments[2 + extraArgs];
4667 ++extraArgs;
4668 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004669
John Kessenich76d4dfc2016-06-16 12:43:23 -06004670 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004671 if (cracked.gather && ! sampler.shadow) {
4672 // default component is 0, if missing, otherwise an argument
4673 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004674 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004675 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004676 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004677 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004678 }
Chao Chen3a137962018-09-19 11:41:27 -07004679#ifdef NV_EXTENSIONS
4680 spv::Id resultStruct = spv::NoResult;
4681 if (imageFootprint) {
4682 //Following three extra arguments
4683 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4684 params.granularity = arguments[2 + extraArgs];
4685 params.coarse = arguments[3 + extraArgs];
4686 resultStruct = arguments[4 + extraArgs];
4687 extraArgs += 3;
4688 }
4689#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004690 // bias
4691 if (bias) {
4692 params.bias = arguments[2 + extraArgs];
4693 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004694 }
John Kessenichfc51d282015-08-19 13:34:18 -06004695
Chao Chen3a137962018-09-19 11:41:27 -07004696#ifdef NV_EXTENSIONS
4697 if (imageFootprint) {
4698 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4699 builder.addCapability(spv::CapabilityImageFootprintNV);
4700
4701
4702 //resultStructType(OpenGL type) contains 5 elements:
4703 //struct gl_TextureFootprint2DNV {
4704 // uvec2 anchor;
4705 // uvec2 offset;
4706 // uvec2 mask;
4707 // uint lod;
4708 // uint granularity;
4709 //};
4710 //or
4711 //struct gl_TextureFootprint3DNV {
4712 // uvec3 anchor;
4713 // uvec3 offset;
4714 // uvec2 mask;
4715 // uint lod;
4716 // uint granularity;
4717 //};
4718 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4719 assert(builder.isStructType(resultStructType));
4720
4721 //resType (SPIR-V type) contains 6 elements:
4722 //Member 0 must be a Boolean type scalar(LOD),
4723 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4724 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4725 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4726 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4727 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4728 std::vector<spv::Id> members;
4729 members.push_back(resultType());
4730 for (int i = 0; i < 5; i++) {
4731 members.push_back(builder.getContainedTypeId(resultStructType, i));
4732 }
4733 spv::Id resType = builder.makeStructType(members, "ResType");
4734
4735 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004736 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4737 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004738
4739 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4740 for (int i = 0; i < 5; i++) {
4741 builder.clearAccessChain();
4742 builder.setAccessChainLValue(resultStruct);
4743
4744 //Accessing to a struct we created, no coherent flag is set
4745 spv::Builder::AccessChain::CoherentFlags flags;
4746 flags.clear();
4747
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004748 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004749 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4750 }
4751 return builder.createCompositeExtract(res, resultType(), 0);
4752 }
4753#endif
4754
John Kessenich65336482016-06-16 14:06:26 -06004755 // projective component (might not to move)
4756 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4757 // are divided by the last component of P."
4758 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4759 // unused components will appear after all used components."
4760 if (cracked.proj) {
4761 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4762 int projTargetComp;
4763 switch (sampler.dim) {
4764 case glslang::Esd1D: projTargetComp = 1; break;
4765 case glslang::Esd2D: projTargetComp = 2; break;
4766 case glslang::EsdRect: projTargetComp = 2; break;
4767 default: projTargetComp = projSourceComp; break;
4768 }
4769 // copy the projective coordinate if we have to
4770 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004771 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004772 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4773 projSourceComp);
4774 params.coords = builder.createCompositeInsert(projComp, params.coords,
4775 builder.getTypeId(params.coords), projTargetComp);
4776 }
4777 }
4778
Jeff Bolz36831c92018-09-05 10:11:41 -05004779 // nonprivate
4780 if (imageType.getQualifier().nonprivate) {
4781 params.nonprivate = true;
4782 }
4783
4784 // volatile
4785 if (imageType.getQualifier().volatil) {
4786 params.volatil = true;
4787 }
4788
St0fFa1184dd2018-04-09 21:08:14 +02004789 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004790 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4791 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004792 );
LoopDawg4425f242018-02-18 11:40:01 -07004793
4794 if (components != node->getType().getVectorSize())
4795 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4796
4797 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004798}
4799
4800spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4801{
4802 // Grab the function's pointer from the previously created function
4803 spv::Function* function = functionMap[node->getName().c_str()];
4804 if (! function)
4805 return 0;
4806
4807 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4808 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4809
4810 // See comments in makeFunctions() for details about the semantics for parameter passing.
4811 //
4812 // These imply we need a four step process:
4813 // 1. Evaluate the arguments
4814 // 2. Allocate and make copies of in, out, and inout arguments
4815 // 3. Make the call
4816 // 4. Copy back the results
4817
John Kessenichd3ed90b2018-05-04 11:43:03 -06004818 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004819 std::vector<spv::Builder::AccessChain> lValues;
4820 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004821 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004822 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004823 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004824 // build l-value
4825 builder.clearAccessChain();
4826 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004827 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004828 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004829 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004830 // save l-value
4831 lValues.push_back(builder.getAccessChain());
4832 } else {
4833 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004834 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004835 }
4836 }
4837
4838 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4839 // copy the original into that space.
4840 //
4841 // Also, build up the list of actual arguments to pass in for the call
4842 int lValueCount = 0;
4843 int rValueCount = 0;
4844 std::vector<spv::Id> spvArgs;
4845 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4846 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004847 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004848 builder.setAccessChain(lValues[lValueCount]);
4849 arg = builder.accessChainGetLValue();
4850 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004851 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004852 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004853 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004854 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4855 // need to copy the input into output space
4856 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004857 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004858 builder.clearAccessChain();
4859 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004860 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004861 }
4862 ++lValueCount;
4863 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004864 // process r-value, which involves a copy for a type mismatch
4865 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4866 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4867 builder.clearAccessChain();
4868 builder.setAccessChainLValue(argCopy);
4869 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4870 arg = builder.createLoad(argCopy);
4871 } else
4872 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004873 ++rValueCount;
4874 }
4875 spvArgs.push_back(arg);
4876 }
4877
4878 // 3. Make the call.
4879 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004880 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004881
4882 // 4. Copy back out an "out" arguments.
4883 lValueCount = 0;
4884 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004885 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004886 ++lValueCount;
4887 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004888 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4889 spv::Id copy = builder.createLoad(spvArgs[a]);
4890 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004891 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004892 }
4893 ++lValueCount;
4894 }
4895 }
4896
4897 return result;
4898}
4899
4900// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004901spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004902 spv::Id typeId, spv::Id left, spv::Id right,
4903 glslang::TBasicType typeProxy, bool reduceComparison)
4904{
John Kessenich66011cb2018-03-06 16:12:04 -07004905 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4906 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004907 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004908
4909 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004910 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004911 bool comparison = false;
4912
4913 switch (op) {
4914 case glslang::EOpAdd:
4915 case glslang::EOpAddAssign:
4916 if (isFloat)
4917 binOp = spv::OpFAdd;
4918 else
4919 binOp = spv::OpIAdd;
4920 break;
4921 case glslang::EOpSub:
4922 case glslang::EOpSubAssign:
4923 if (isFloat)
4924 binOp = spv::OpFSub;
4925 else
4926 binOp = spv::OpISub;
4927 break;
4928 case glslang::EOpMul:
4929 case glslang::EOpMulAssign:
4930 if (isFloat)
4931 binOp = spv::OpFMul;
4932 else
4933 binOp = spv::OpIMul;
4934 break;
4935 case glslang::EOpVectorTimesScalar:
4936 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004937 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004938 if (builder.isVector(right))
4939 std::swap(left, right);
4940 assert(builder.isScalar(right));
4941 needMatchingVectors = false;
4942 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01004943 } else if (isFloat)
4944 binOp = spv::OpFMul;
4945 else
John Kessenichec43d0a2015-07-04 17:17:31 -06004946 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004947 break;
4948 case glslang::EOpVectorTimesMatrix:
4949 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004950 binOp = spv::OpVectorTimesMatrix;
4951 break;
4952 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004953 binOp = spv::OpMatrixTimesVector;
4954 break;
4955 case glslang::EOpMatrixTimesScalar:
4956 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004957 binOp = spv::OpMatrixTimesScalar;
4958 break;
4959 case glslang::EOpMatrixTimesMatrix:
4960 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004961 binOp = spv::OpMatrixTimesMatrix;
4962 break;
4963 case glslang::EOpOuterProduct:
4964 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004965 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004966 break;
4967
4968 case glslang::EOpDiv:
4969 case glslang::EOpDivAssign:
4970 if (isFloat)
4971 binOp = spv::OpFDiv;
4972 else if (isUnsigned)
4973 binOp = spv::OpUDiv;
4974 else
4975 binOp = spv::OpSDiv;
4976 break;
4977 case glslang::EOpMod:
4978 case glslang::EOpModAssign:
4979 if (isFloat)
4980 binOp = spv::OpFMod;
4981 else if (isUnsigned)
4982 binOp = spv::OpUMod;
4983 else
4984 binOp = spv::OpSMod;
4985 break;
4986 case glslang::EOpRightShift:
4987 case glslang::EOpRightShiftAssign:
4988 if (isUnsigned)
4989 binOp = spv::OpShiftRightLogical;
4990 else
4991 binOp = spv::OpShiftRightArithmetic;
4992 break;
4993 case glslang::EOpLeftShift:
4994 case glslang::EOpLeftShiftAssign:
4995 binOp = spv::OpShiftLeftLogical;
4996 break;
4997 case glslang::EOpAnd:
4998 case glslang::EOpAndAssign:
4999 binOp = spv::OpBitwiseAnd;
5000 break;
5001 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005002 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005003 binOp = spv::OpLogicalAnd;
5004 break;
5005 case glslang::EOpInclusiveOr:
5006 case glslang::EOpInclusiveOrAssign:
5007 binOp = spv::OpBitwiseOr;
5008 break;
5009 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005010 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005011 binOp = spv::OpLogicalOr;
5012 break;
5013 case glslang::EOpExclusiveOr:
5014 case glslang::EOpExclusiveOrAssign:
5015 binOp = spv::OpBitwiseXor;
5016 break;
5017 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005018 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005019 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005020 break;
5021
5022 case glslang::EOpLessThan:
5023 case glslang::EOpGreaterThan:
5024 case glslang::EOpLessThanEqual:
5025 case glslang::EOpGreaterThanEqual:
5026 case glslang::EOpEqual:
5027 case glslang::EOpNotEqual:
5028 case glslang::EOpVectorEqual:
5029 case glslang::EOpVectorNotEqual:
5030 comparison = true;
5031 break;
5032 default:
5033 break;
5034 }
5035
John Kessenich7c1aa102015-10-15 13:29:11 -06005036 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005037 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005038 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005039 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5040 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005041 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005042
5043 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005044 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005045 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005046
qining25262b32016-05-06 17:25:16 -04005047 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005048 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005049 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005050 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005051 }
5052
5053 if (! comparison)
5054 return 0;
5055
John Kessenich7c1aa102015-10-15 13:29:11 -06005056 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005057
John Kessenich4583b612016-08-07 19:14:22 -06005058 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005059 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5060 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06005061 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005062 return result;
5063 }
John Kessenich140f3df2015-06-26 16:58:36 -06005064
5065 switch (op) {
5066 case glslang::EOpLessThan:
5067 if (isFloat)
5068 binOp = spv::OpFOrdLessThan;
5069 else if (isUnsigned)
5070 binOp = spv::OpULessThan;
5071 else
5072 binOp = spv::OpSLessThan;
5073 break;
5074 case glslang::EOpGreaterThan:
5075 if (isFloat)
5076 binOp = spv::OpFOrdGreaterThan;
5077 else if (isUnsigned)
5078 binOp = spv::OpUGreaterThan;
5079 else
5080 binOp = spv::OpSGreaterThan;
5081 break;
5082 case glslang::EOpLessThanEqual:
5083 if (isFloat)
5084 binOp = spv::OpFOrdLessThanEqual;
5085 else if (isUnsigned)
5086 binOp = spv::OpULessThanEqual;
5087 else
5088 binOp = spv::OpSLessThanEqual;
5089 break;
5090 case glslang::EOpGreaterThanEqual:
5091 if (isFloat)
5092 binOp = spv::OpFOrdGreaterThanEqual;
5093 else if (isUnsigned)
5094 binOp = spv::OpUGreaterThanEqual;
5095 else
5096 binOp = spv::OpSGreaterThanEqual;
5097 break;
5098 case glslang::EOpEqual:
5099 case glslang::EOpVectorEqual:
5100 if (isFloat)
5101 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005102 else if (isBool)
5103 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005104 else
5105 binOp = spv::OpIEqual;
5106 break;
5107 case glslang::EOpNotEqual:
5108 case glslang::EOpVectorNotEqual:
5109 if (isFloat)
5110 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005111 else if (isBool)
5112 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005113 else
5114 binOp = spv::OpINotEqual;
5115 break;
5116 default:
5117 break;
5118 }
5119
qining25262b32016-05-06 17:25:16 -04005120 if (binOp != spv::OpNop) {
5121 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005122 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005123 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005124 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005125 }
John Kessenich140f3df2015-06-26 16:58:36 -06005126
5127 return 0;
5128}
5129
John Kessenich04bb8a02015-12-12 12:28:14 -07005130//
5131// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5132// These can be any of:
5133//
5134// matrix * scalar
5135// scalar * matrix
5136// matrix * matrix linear algebraic
5137// matrix * vector
5138// vector * matrix
5139// matrix * matrix componentwise
5140// matrix op matrix op in {+, -, /}
5141// matrix op scalar op in {+, -, /}
5142// scalar op matrix op in {+, -, /}
5143//
John Kessenichead86222018-03-28 18:01:20 -06005144spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5145 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005146{
5147 bool firstClass = true;
5148
5149 // First, handle first-class matrix operations (* and matrix/scalar)
5150 switch (op) {
5151 case spv::OpFDiv:
5152 if (builder.isMatrix(left) && builder.isScalar(right)) {
5153 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005154 spv::Id resultType = builder.getTypeId(right);
5155 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005156 op = spv::OpMatrixTimesScalar;
5157 } else
5158 firstClass = false;
5159 break;
5160 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005161 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005162 std::swap(left, right);
5163 assert(builder.isScalar(right));
5164 break;
5165 case spv::OpVectorTimesMatrix:
5166 assert(builder.isVector(left));
5167 assert(builder.isMatrix(right));
5168 break;
5169 case spv::OpMatrixTimesVector:
5170 assert(builder.isMatrix(left));
5171 assert(builder.isVector(right));
5172 break;
5173 case spv::OpMatrixTimesMatrix:
5174 assert(builder.isMatrix(left));
5175 assert(builder.isMatrix(right));
5176 break;
5177 default:
5178 firstClass = false;
5179 break;
5180 }
5181
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005182 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5183 firstClass = true;
5184
qining25262b32016-05-06 17:25:16 -04005185 if (firstClass) {
5186 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005187 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005188 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005189 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005190 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005191
LoopDawg592860c2016-06-09 08:57:35 -06005192 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005193 // The result type of all of them is the same type as the (a) matrix operand.
5194 // The algorithm is to:
5195 // - break the matrix(es) into vectors
5196 // - smear any scalar to a vector
5197 // - do vector operations
5198 // - make a matrix out the vector results
5199 switch (op) {
5200 case spv::OpFAdd:
5201 case spv::OpFSub:
5202 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005203 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005204 case spv::OpFMul:
5205 {
5206 // one time set up...
5207 bool leftMat = builder.isMatrix(left);
5208 bool rightMat = builder.isMatrix(right);
5209 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5210 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5211 spv::Id scalarType = builder.getScalarTypeId(typeId);
5212 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5213 std::vector<spv::Id> results;
5214 spv::Id smearVec = spv::NoResult;
5215 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005216 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005217 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005218 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005219
5220 // do each vector op
5221 for (unsigned int c = 0; c < numCols; ++c) {
5222 std::vector<unsigned int> indexes;
5223 indexes.push_back(c);
5224 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5225 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005226 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005227 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005228 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005229 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005230 }
5231
5232 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005233 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005234 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005235 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005236 }
5237 default:
5238 assert(0);
5239 return spv::NoResult;
5240 }
5241}
5242
John Kessenichead86222018-03-28 18:01:20 -06005243spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
5244 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005245{
5246 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005247 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005248 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005249 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5250 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005251
5252 switch (op) {
5253 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005254 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005255 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005256 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005257 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005258 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005259 unaryOp = spv::OpSNegate;
5260 break;
5261
5262 case glslang::EOpLogicalNot:
5263 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005264 unaryOp = spv::OpLogicalNot;
5265 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005266 case glslang::EOpBitwiseNot:
5267 unaryOp = spv::OpNot;
5268 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005269
John Kessenich140f3df2015-06-26 16:58:36 -06005270 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005271 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005272 break;
5273 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005274 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005275 break;
5276 case glslang::EOpTranspose:
5277 unaryOp = spv::OpTranspose;
5278 break;
5279
5280 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005281 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005282 break;
5283 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005284 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005285 break;
5286 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005287 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005288 break;
5289 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005290 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005291 break;
5292 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005293 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005294 break;
5295 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005296 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005297 break;
5298 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005299 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005300 break;
5301 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005302 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005303 break;
5304
5305 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005306 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005307 break;
5308 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005309 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005310 break;
5311 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005312 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005313 break;
5314 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005315 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005316 break;
5317 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005318 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005319 break;
5320 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005321 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005322 break;
5323
5324 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005325 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005326 break;
5327 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005328 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005329 break;
5330
5331 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005332 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005333 break;
5334 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005335 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005336 break;
5337 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005338 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005339 break;
5340 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005341 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005342 break;
5343 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005344 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005345 break;
5346 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005347 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005348 break;
5349
5350 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005351 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005352 break;
5353 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005354 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005355 break;
5356 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005357 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005358 break;
5359 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005360 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005361 break;
5362 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005363 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005364 break;
5365 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005366 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005367 break;
5368
5369 case glslang::EOpIsNan:
5370 unaryOp = spv::OpIsNan;
5371 break;
5372 case glslang::EOpIsInf:
5373 unaryOp = spv::OpIsInf;
5374 break;
LoopDawg592860c2016-06-09 08:57:35 -06005375 case glslang::EOpIsFinite:
5376 unaryOp = spv::OpIsFinite;
5377 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005378
Rex Xucbc426e2015-12-15 16:03:10 +08005379 case glslang::EOpFloatBitsToInt:
5380 case glslang::EOpFloatBitsToUint:
5381 case glslang::EOpIntBitsToFloat:
5382 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005383 case glslang::EOpDoubleBitsToInt64:
5384 case glslang::EOpDoubleBitsToUint64:
5385 case glslang::EOpInt64BitsToDouble:
5386 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005387 case glslang::EOpFloat16BitsToInt16:
5388 case glslang::EOpFloat16BitsToUint16:
5389 case glslang::EOpInt16BitsToFloat16:
5390 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005391 unaryOp = spv::OpBitcast;
5392 break;
5393
John Kessenich140f3df2015-06-26 16:58:36 -06005394 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005395 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005396 break;
5397 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005398 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005399 break;
5400 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005401 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005402 break;
5403 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005404 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005405 break;
5406 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005407 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005408 break;
5409 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005410 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005411 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005412 case glslang::EOpPackSnorm4x8:
5413 libCall = spv::GLSLstd450PackSnorm4x8;
5414 break;
5415 case glslang::EOpUnpackSnorm4x8:
5416 libCall = spv::GLSLstd450UnpackSnorm4x8;
5417 break;
5418 case glslang::EOpPackUnorm4x8:
5419 libCall = spv::GLSLstd450PackUnorm4x8;
5420 break;
5421 case glslang::EOpUnpackUnorm4x8:
5422 libCall = spv::GLSLstd450UnpackUnorm4x8;
5423 break;
5424 case glslang::EOpPackDouble2x32:
5425 libCall = spv::GLSLstd450PackDouble2x32;
5426 break;
5427 case glslang::EOpUnpackDouble2x32:
5428 libCall = spv::GLSLstd450UnpackDouble2x32;
5429 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005430
Rex Xu8ff43de2016-04-22 16:51:45 +08005431 case glslang::EOpPackInt2x32:
5432 case glslang::EOpUnpackInt2x32:
5433 case glslang::EOpPackUint2x32:
5434 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005435 case glslang::EOpPack16:
5436 case glslang::EOpPack32:
5437 case glslang::EOpPack64:
5438 case glslang::EOpUnpack32:
5439 case glslang::EOpUnpack16:
5440 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005441 case glslang::EOpPackInt2x16:
5442 case glslang::EOpUnpackInt2x16:
5443 case glslang::EOpPackUint2x16:
5444 case glslang::EOpUnpackUint2x16:
5445 case glslang::EOpPackInt4x16:
5446 case glslang::EOpUnpackInt4x16:
5447 case glslang::EOpPackUint4x16:
5448 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005449 case glslang::EOpPackFloat2x16:
5450 case glslang::EOpUnpackFloat2x16:
5451 unaryOp = spv::OpBitcast;
5452 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005453
John Kessenich140f3df2015-06-26 16:58:36 -06005454 case glslang::EOpDPdx:
5455 unaryOp = spv::OpDPdx;
5456 break;
5457 case glslang::EOpDPdy:
5458 unaryOp = spv::OpDPdy;
5459 break;
5460 case glslang::EOpFwidth:
5461 unaryOp = spv::OpFwidth;
5462 break;
5463 case glslang::EOpDPdxFine:
5464 unaryOp = spv::OpDPdxFine;
5465 break;
5466 case glslang::EOpDPdyFine:
5467 unaryOp = spv::OpDPdyFine;
5468 break;
5469 case glslang::EOpFwidthFine:
5470 unaryOp = spv::OpFwidthFine;
5471 break;
5472 case glslang::EOpDPdxCoarse:
5473 unaryOp = spv::OpDPdxCoarse;
5474 break;
5475 case glslang::EOpDPdyCoarse:
5476 unaryOp = spv::OpDPdyCoarse;
5477 break;
5478 case glslang::EOpFwidthCoarse:
5479 unaryOp = spv::OpFwidthCoarse;
5480 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005481 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005482#ifdef AMD_EXTENSIONS
5483 if (typeProxy == glslang::EbtFloat16)
5484 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5485#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005486 libCall = spv::GLSLstd450InterpolateAtCentroid;
5487 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005488 case glslang::EOpAny:
5489 unaryOp = spv::OpAny;
5490 break;
5491 case glslang::EOpAll:
5492 unaryOp = spv::OpAll;
5493 break;
5494
5495 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005496 if (isFloat)
5497 libCall = spv::GLSLstd450FAbs;
5498 else
5499 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005500 break;
5501 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005502 if (isFloat)
5503 libCall = spv::GLSLstd450FSign;
5504 else
5505 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005506 break;
5507
John Kessenichfc51d282015-08-19 13:34:18 -06005508 case glslang::EOpAtomicCounterIncrement:
5509 case glslang::EOpAtomicCounterDecrement:
5510 case glslang::EOpAtomicCounter:
5511 {
5512 // Handle all of the atomics in one place, in createAtomicOperation()
5513 std::vector<spv::Id> operands;
5514 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005515 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005516 }
5517
John Kessenichfc51d282015-08-19 13:34:18 -06005518 case glslang::EOpBitFieldReverse:
5519 unaryOp = spv::OpBitReverse;
5520 break;
5521 case glslang::EOpBitCount:
5522 unaryOp = spv::OpBitCount;
5523 break;
5524 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005525 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005526 break;
5527 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005528 if (isUnsigned)
5529 libCall = spv::GLSLstd450FindUMsb;
5530 else
5531 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005532 break;
5533
Rex Xu574ab042016-04-14 16:53:07 +08005534 case glslang::EOpBallot:
5535 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005536 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005537 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005538 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005539#ifdef AMD_EXTENSIONS
5540 case glslang::EOpMinInvocations:
5541 case glslang::EOpMaxInvocations:
5542 case glslang::EOpAddInvocations:
5543 case glslang::EOpMinInvocationsNonUniform:
5544 case glslang::EOpMaxInvocationsNonUniform:
5545 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005546 case glslang::EOpMinInvocationsInclusiveScan:
5547 case glslang::EOpMaxInvocationsInclusiveScan:
5548 case glslang::EOpAddInvocationsInclusiveScan:
5549 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5550 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5551 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5552 case glslang::EOpMinInvocationsExclusiveScan:
5553 case glslang::EOpMaxInvocationsExclusiveScan:
5554 case glslang::EOpAddInvocationsExclusiveScan:
5555 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5556 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5557 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005558#endif
Rex Xu51596642016-09-21 18:56:12 +08005559 {
5560 std::vector<spv::Id> operands;
5561 operands.push_back(operand);
5562 return createInvocationsOperation(op, typeId, operands, typeProxy);
5563 }
John Kessenich66011cb2018-03-06 16:12:04 -07005564 case glslang::EOpSubgroupAll:
5565 case glslang::EOpSubgroupAny:
5566 case glslang::EOpSubgroupAllEqual:
5567 case glslang::EOpSubgroupBroadcastFirst:
5568 case glslang::EOpSubgroupBallot:
5569 case glslang::EOpSubgroupInverseBallot:
5570 case glslang::EOpSubgroupBallotBitCount:
5571 case glslang::EOpSubgroupBallotInclusiveBitCount:
5572 case glslang::EOpSubgroupBallotExclusiveBitCount:
5573 case glslang::EOpSubgroupBallotFindLSB:
5574 case glslang::EOpSubgroupBallotFindMSB:
5575 case glslang::EOpSubgroupAdd:
5576 case glslang::EOpSubgroupMul:
5577 case glslang::EOpSubgroupMin:
5578 case glslang::EOpSubgroupMax:
5579 case glslang::EOpSubgroupAnd:
5580 case glslang::EOpSubgroupOr:
5581 case glslang::EOpSubgroupXor:
5582 case glslang::EOpSubgroupInclusiveAdd:
5583 case glslang::EOpSubgroupInclusiveMul:
5584 case glslang::EOpSubgroupInclusiveMin:
5585 case glslang::EOpSubgroupInclusiveMax:
5586 case glslang::EOpSubgroupInclusiveAnd:
5587 case glslang::EOpSubgroupInclusiveOr:
5588 case glslang::EOpSubgroupInclusiveXor:
5589 case glslang::EOpSubgroupExclusiveAdd:
5590 case glslang::EOpSubgroupExclusiveMul:
5591 case glslang::EOpSubgroupExclusiveMin:
5592 case glslang::EOpSubgroupExclusiveMax:
5593 case glslang::EOpSubgroupExclusiveAnd:
5594 case glslang::EOpSubgroupExclusiveOr:
5595 case glslang::EOpSubgroupExclusiveXor:
5596 case glslang::EOpSubgroupQuadSwapHorizontal:
5597 case glslang::EOpSubgroupQuadSwapVertical:
5598 case glslang::EOpSubgroupQuadSwapDiagonal: {
5599 std::vector<spv::Id> operands;
5600 operands.push_back(operand);
5601 return createSubgroupOperation(op, typeId, operands, typeProxy);
5602 }
Rex Xu9d93a232016-05-05 12:30:44 +08005603#ifdef AMD_EXTENSIONS
5604 case glslang::EOpMbcnt:
5605 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5606 libCall = spv::MbcntAMD;
5607 break;
5608
5609 case glslang::EOpCubeFaceIndex:
5610 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5611 libCall = spv::CubeFaceIndexAMD;
5612 break;
5613
5614 case glslang::EOpCubeFaceCoord:
5615 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5616 libCall = spv::CubeFaceCoordAMD;
5617 break;
5618#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005619#ifdef NV_EXTENSIONS
5620 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005621 unaryOp = spv::OpGroupNonUniformPartitionNV;
5622 break;
5623#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005624 case glslang::EOpConstructReference:
5625 unaryOp = spv::OpBitcast;
5626 break;
Jeff Bolz88220d52019-05-08 10:24:46 -05005627
5628 case glslang::EOpCopyObject:
5629 unaryOp = spv::OpCopyObject;
5630 break;
5631
John Kessenich140f3df2015-06-26 16:58:36 -06005632 default:
5633 return 0;
5634 }
5635
5636 spv::Id id;
5637 if (libCall >= 0) {
5638 std::vector<spv::Id> args;
5639 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005640 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005641 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005642 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005643 }
John Kessenich140f3df2015-06-26 16:58:36 -06005644
John Kessenichead86222018-03-28 18:01:20 -06005645 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005646 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005647 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005648}
5649
John Kessenich7a53f762016-01-20 11:19:27 -07005650// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005651spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5652 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005653{
5654 // Handle unary operations vector by vector.
5655 // The result type is the same type as the original type.
5656 // The algorithm is to:
5657 // - break the matrix into vectors
5658 // - apply the operation to each vector
5659 // - make a matrix out the vector results
5660
5661 // get the types sorted out
5662 int numCols = builder.getNumColumns(operand);
5663 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005664 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5665 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005666 std::vector<spv::Id> results;
5667
5668 // do each vector op
5669 for (int c = 0; c < numCols; ++c) {
5670 std::vector<unsigned int> indexes;
5671 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005672 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5673 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005674 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005675 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005676 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005677 }
5678
5679 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005680 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005681 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005682 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005683}
5684
John Kessenichad7645f2018-06-04 19:11:25 -06005685// For converting integers where both the bitwidth and the signedness could
5686// change, but only do the width change here. The caller is still responsible
5687// for the signedness conversion.
5688spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005689{
John Kessenichad7645f2018-06-04 19:11:25 -06005690 // Get the result type width, based on the type to convert to.
5691 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005692 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005693 case glslang::EOpConvInt16ToUint8:
5694 case glslang::EOpConvIntToUint8:
5695 case glslang::EOpConvInt64ToUint8:
5696 case glslang::EOpConvUint16ToInt8:
5697 case glslang::EOpConvUintToInt8:
5698 case glslang::EOpConvUint64ToInt8:
5699 width = 8;
5700 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005701 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005702 case glslang::EOpConvIntToUint16:
5703 case glslang::EOpConvInt64ToUint16:
5704 case glslang::EOpConvUint8ToInt16:
5705 case glslang::EOpConvUintToInt16:
5706 case glslang::EOpConvUint64ToInt16:
5707 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005708 break;
5709 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005710 case glslang::EOpConvInt16ToUint:
5711 case glslang::EOpConvInt64ToUint:
5712 case glslang::EOpConvUint8ToInt:
5713 case glslang::EOpConvUint16ToInt:
5714 case glslang::EOpConvUint64ToInt:
5715 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005716 break;
5717 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005718 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005719 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005720 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005721 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005722 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005723 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005724 break;
5725
5726 default:
5727 assert(false && "Default missing");
5728 break;
5729 }
5730
John Kessenichad7645f2018-06-04 19:11:25 -06005731 // Get the conversion operation and result type,
5732 // based on the target width, but the source type.
5733 spv::Id type = spv::NoType;
5734 spv::Op convOp = spv::OpNop;
5735 switch(op) {
5736 case glslang::EOpConvInt8ToUint16:
5737 case glslang::EOpConvInt8ToUint:
5738 case glslang::EOpConvInt8ToUint64:
5739 case glslang::EOpConvInt16ToUint8:
5740 case glslang::EOpConvInt16ToUint:
5741 case glslang::EOpConvInt16ToUint64:
5742 case glslang::EOpConvIntToUint8:
5743 case glslang::EOpConvIntToUint16:
5744 case glslang::EOpConvIntToUint64:
5745 case glslang::EOpConvInt64ToUint8:
5746 case glslang::EOpConvInt64ToUint16:
5747 case glslang::EOpConvInt64ToUint:
5748 convOp = spv::OpSConvert;
5749 type = builder.makeIntType(width);
5750 break;
5751 default:
5752 convOp = spv::OpUConvert;
5753 type = builder.makeUintType(width);
5754 break;
5755 }
5756
John Kessenich66011cb2018-03-06 16:12:04 -07005757 if (vectorSize > 0)
5758 type = builder.makeVectorType(type, vectorSize);
5759
John Kessenichad7645f2018-06-04 19:11:25 -06005760 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005761}
5762
John Kessenichead86222018-03-28 18:01:20 -06005763spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5764 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005765{
5766 spv::Op convOp = spv::OpNop;
5767 spv::Id zero = 0;
5768 spv::Id one = 0;
5769
5770 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5771
5772 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005773 case glslang::EOpConvInt8ToBool:
5774 case glslang::EOpConvUint8ToBool:
5775 zero = builder.makeUint8Constant(0);
5776 zero = makeSmearedConstant(zero, vectorSize);
5777 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005778 case glslang::EOpConvInt16ToBool:
5779 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005780 zero = builder.makeUint16Constant(0);
5781 zero = makeSmearedConstant(zero, vectorSize);
5782 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5783 case glslang::EOpConvIntToBool:
5784 case glslang::EOpConvUintToBool:
5785 zero = builder.makeUintConstant(0);
5786 zero = makeSmearedConstant(zero, vectorSize);
5787 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5788 case glslang::EOpConvInt64ToBool:
5789 case glslang::EOpConvUint64ToBool:
5790 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005791 zero = makeSmearedConstant(zero, vectorSize);
5792 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5793
5794 case glslang::EOpConvFloatToBool:
5795 zero = builder.makeFloatConstant(0.0F);
5796 zero = makeSmearedConstant(zero, vectorSize);
5797 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5798
5799 case glslang::EOpConvDoubleToBool:
5800 zero = builder.makeDoubleConstant(0.0);
5801 zero = makeSmearedConstant(zero, vectorSize);
5802 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5803
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005804 case glslang::EOpConvFloat16ToBool:
5805 zero = builder.makeFloat16Constant(0.0F);
5806 zero = makeSmearedConstant(zero, vectorSize);
5807 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005808
John Kessenich140f3df2015-06-26 16:58:36 -06005809 case glslang::EOpConvBoolToFloat:
5810 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005811 zero = builder.makeFloatConstant(0.0F);
5812 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005813 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005814
John Kessenich140f3df2015-06-26 16:58:36 -06005815 case glslang::EOpConvBoolToDouble:
5816 convOp = spv::OpSelect;
5817 zero = builder.makeDoubleConstant(0.0);
5818 one = builder.makeDoubleConstant(1.0);
5819 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005820
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005821 case glslang::EOpConvBoolToFloat16:
5822 convOp = spv::OpSelect;
5823 zero = builder.makeFloat16Constant(0.0F);
5824 one = builder.makeFloat16Constant(1.0F);
5825 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005826
5827 case glslang::EOpConvBoolToInt8:
5828 zero = builder.makeInt8Constant(0);
5829 one = builder.makeInt8Constant(1);
5830 convOp = spv::OpSelect;
5831 break;
5832
5833 case glslang::EOpConvBoolToUint8:
5834 zero = builder.makeUint8Constant(0);
5835 one = builder.makeUint8Constant(1);
5836 convOp = spv::OpSelect;
5837 break;
5838
5839 case glslang::EOpConvBoolToInt16:
5840 zero = builder.makeInt16Constant(0);
5841 one = builder.makeInt16Constant(1);
5842 convOp = spv::OpSelect;
5843 break;
5844
5845 case glslang::EOpConvBoolToUint16:
5846 zero = builder.makeUint16Constant(0);
5847 one = builder.makeUint16Constant(1);
5848 convOp = spv::OpSelect;
5849 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005850
John Kessenich140f3df2015-06-26 16:58:36 -06005851 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005852 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005853 if (op == glslang::EOpConvBoolToInt64)
5854 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005855 else
5856 zero = builder.makeIntConstant(0);
5857
5858 if (op == glslang::EOpConvBoolToInt64)
5859 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005860 else
5861 one = builder.makeIntConstant(1);
5862
John Kessenich140f3df2015-06-26 16:58:36 -06005863 convOp = spv::OpSelect;
5864 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005865
John Kessenich140f3df2015-06-26 16:58:36 -06005866 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005867 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005868 if (op == glslang::EOpConvBoolToUint64)
5869 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005870 else
5871 zero = builder.makeUintConstant(0);
5872
5873 if (op == glslang::EOpConvBoolToUint64)
5874 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005875 else
5876 one = builder.makeUintConstant(1);
5877
John Kessenich140f3df2015-06-26 16:58:36 -06005878 convOp = spv::OpSelect;
5879 break;
5880
John Kessenich66011cb2018-03-06 16:12:04 -07005881 case glslang::EOpConvInt8ToFloat16:
5882 case glslang::EOpConvInt8ToFloat:
5883 case glslang::EOpConvInt8ToDouble:
5884 case glslang::EOpConvInt16ToFloat16:
5885 case glslang::EOpConvInt16ToFloat:
5886 case glslang::EOpConvInt16ToDouble:
5887 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005888 case glslang::EOpConvIntToFloat:
5889 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005890 case glslang::EOpConvInt64ToFloat:
5891 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005892 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005893 convOp = spv::OpConvertSToF;
5894 break;
5895
John Kessenich66011cb2018-03-06 16:12:04 -07005896 case glslang::EOpConvUint8ToFloat16:
5897 case glslang::EOpConvUint8ToFloat:
5898 case glslang::EOpConvUint8ToDouble:
5899 case glslang::EOpConvUint16ToFloat16:
5900 case glslang::EOpConvUint16ToFloat:
5901 case glslang::EOpConvUint16ToDouble:
5902 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005903 case glslang::EOpConvUintToFloat:
5904 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005905 case glslang::EOpConvUint64ToFloat:
5906 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005907 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005908 convOp = spv::OpConvertUToF;
5909 break;
5910
5911 case glslang::EOpConvDoubleToFloat:
5912 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005913 case glslang::EOpConvDoubleToFloat16:
5914 case glslang::EOpConvFloat16ToDouble:
5915 case glslang::EOpConvFloatToFloat16:
5916 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005917 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005918 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005919 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005920 break;
5921
John Kessenich66011cb2018-03-06 16:12:04 -07005922 case glslang::EOpConvFloat16ToInt8:
5923 case glslang::EOpConvFloatToInt8:
5924 case glslang::EOpConvDoubleToInt8:
5925 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005926 case glslang::EOpConvFloatToInt16:
5927 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005928 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005929 case glslang::EOpConvFloatToInt:
5930 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005931 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005932 case glslang::EOpConvFloatToInt64:
5933 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005934 convOp = spv::OpConvertFToS;
5935 break;
5936
John Kessenich66011cb2018-03-06 16:12:04 -07005937 case glslang::EOpConvUint8ToInt8:
5938 case glslang::EOpConvInt8ToUint8:
5939 case glslang::EOpConvUint16ToInt16:
5940 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005941 case glslang::EOpConvUintToInt:
5942 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005943 case glslang::EOpConvUint64ToInt64:
5944 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005945 if (builder.isInSpecConstCodeGenMode()) {
5946 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005947 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5948 zero = builder.makeUint8Constant(0);
5949 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005950 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005951 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5952 zero = builder.makeUint64Constant(0);
5953 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005954 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005955 }
qining189b2032016-04-12 23:16:20 -04005956 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005957 // Use OpIAdd, instead of OpBitcast to do the conversion when
5958 // generating for OpSpecConstantOp instruction.
5959 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5960 }
5961 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005962 convOp = spv::OpBitcast;
5963 break;
5964
John Kessenich66011cb2018-03-06 16:12:04 -07005965 case glslang::EOpConvFloat16ToUint8:
5966 case glslang::EOpConvFloatToUint8:
5967 case glslang::EOpConvDoubleToUint8:
5968 case glslang::EOpConvFloat16ToUint16:
5969 case glslang::EOpConvFloatToUint16:
5970 case glslang::EOpConvDoubleToUint16:
5971 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005972 case glslang::EOpConvFloatToUint:
5973 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005974 case glslang::EOpConvFloatToUint64:
5975 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005976 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005977 convOp = spv::OpConvertFToU;
5978 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005979
John Kessenich66011cb2018-03-06 16:12:04 -07005980 case glslang::EOpConvInt8ToInt16:
5981 case glslang::EOpConvInt8ToInt:
5982 case glslang::EOpConvInt8ToInt64:
5983 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005984 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005985 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005986 case glslang::EOpConvIntToInt8:
5987 case glslang::EOpConvIntToInt16:
5988 case glslang::EOpConvIntToInt64:
5989 case glslang::EOpConvInt64ToInt8:
5990 case glslang::EOpConvInt64ToInt16:
5991 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005992 convOp = spv::OpSConvert;
5993 break;
5994
John Kessenich66011cb2018-03-06 16:12:04 -07005995 case glslang::EOpConvUint8ToUint16:
5996 case glslang::EOpConvUint8ToUint:
5997 case glslang::EOpConvUint8ToUint64:
5998 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005999 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006000 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006001 case glslang::EOpConvUintToUint8:
6002 case glslang::EOpConvUintToUint16:
6003 case glslang::EOpConvUintToUint64:
6004 case glslang::EOpConvUint64ToUint8:
6005 case glslang::EOpConvUint64ToUint16:
6006 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006007 convOp = spv::OpUConvert;
6008 break;
6009
John Kessenich66011cb2018-03-06 16:12:04 -07006010 case glslang::EOpConvInt8ToUint16:
6011 case glslang::EOpConvInt8ToUint:
6012 case glslang::EOpConvInt8ToUint64:
6013 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006014 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006015 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006016 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006017 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006018 case glslang::EOpConvIntToUint64:
6019 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006020 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006021 case glslang::EOpConvInt64ToUint:
6022 case glslang::EOpConvUint8ToInt16:
6023 case glslang::EOpConvUint8ToInt:
6024 case glslang::EOpConvUint8ToInt64:
6025 case glslang::EOpConvUint16ToInt8:
6026 case glslang::EOpConvUint16ToInt:
6027 case glslang::EOpConvUint16ToInt64:
6028 case glslang::EOpConvUintToInt8:
6029 case glslang::EOpConvUintToInt16:
6030 case glslang::EOpConvUintToInt64:
6031 case glslang::EOpConvUint64ToInt8:
6032 case glslang::EOpConvUint64ToInt16:
6033 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006034 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006035 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006036
6037 if (builder.isInSpecConstCodeGenMode()) {
6038 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006039 switch(op) {
6040 case glslang::EOpConvInt16ToUint8:
6041 case glslang::EOpConvIntToUint8:
6042 case glslang::EOpConvInt64ToUint8:
6043 case glslang::EOpConvUint16ToInt8:
6044 case glslang::EOpConvUintToInt8:
6045 case glslang::EOpConvUint64ToInt8:
6046 zero = builder.makeUint8Constant(0);
6047 break;
6048 case glslang::EOpConvInt8ToUint16:
6049 case glslang::EOpConvIntToUint16:
6050 case glslang::EOpConvInt64ToUint16:
6051 case glslang::EOpConvUint8ToInt16:
6052 case glslang::EOpConvUintToInt16:
6053 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006054 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006055 break;
6056 case glslang::EOpConvInt8ToUint:
6057 case glslang::EOpConvInt16ToUint:
6058 case glslang::EOpConvInt64ToUint:
6059 case glslang::EOpConvUint8ToInt:
6060 case glslang::EOpConvUint16ToInt:
6061 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006062 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006063 break;
6064 case glslang::EOpConvInt8ToUint64:
6065 case glslang::EOpConvInt16ToUint64:
6066 case glslang::EOpConvIntToUint64:
6067 case glslang::EOpConvUint8ToInt64:
6068 case glslang::EOpConvUint16ToInt64:
6069 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006070 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006071 break;
6072 default:
6073 assert(false && "Default missing");
6074 break;
6075 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006076 zero = makeSmearedConstant(zero, vectorSize);
6077 // Use OpIAdd, instead of OpBitcast to do the conversion when
6078 // generating for OpSpecConstantOp instruction.
6079 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6080 }
6081 // For normal run-time conversion instruction, use OpBitcast.
6082 convOp = spv::OpBitcast;
6083 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006084 case glslang::EOpConvUint64ToPtr:
6085 convOp = spv::OpConvertUToPtr;
6086 break;
6087 case glslang::EOpConvPtrToUint64:
6088 convOp = spv::OpConvertPtrToU;
6089 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006090 default:
6091 break;
6092 }
6093
6094 spv::Id result = 0;
6095 if (convOp == spv::OpNop)
6096 return result;
6097
6098 if (convOp == spv::OpSelect) {
6099 zero = makeSmearedConstant(zero, vectorSize);
6100 one = makeSmearedConstant(one, vectorSize);
6101 result = builder.createTriOp(convOp, destType, operand, one, zero);
6102 } else
6103 result = builder.createUnaryOp(convOp, destType, operand);
6104
John Kessenichead86222018-03-28 18:01:20 -06006105 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006106 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006107 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006108}
6109
6110spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6111{
6112 if (vectorSize == 0)
6113 return constant;
6114
6115 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6116 std::vector<spv::Id> components;
6117 for (int c = 0; c < vectorSize; ++c)
6118 components.push_back(constant);
6119 return builder.makeCompositeConstant(vectorTypeId, components);
6120}
6121
John Kessenich426394d2015-07-23 10:22:48 -06006122// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07006123spv::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 -06006124{
6125 spv::Op opCode = spv::OpNop;
6126
6127 switch (op) {
6128 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006129 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006130 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006131 opCode = spv::OpAtomicIAdd;
6132 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006133 case glslang::EOpAtomicCounterSubtract:
6134 opCode = spv::OpAtomicISub;
6135 break;
John Kessenich426394d2015-07-23 10:22:48 -06006136 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006137 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006138 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006139 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006140 break;
6141 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006142 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006143 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006144 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006145 break;
6146 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006147 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006148 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006149 opCode = spv::OpAtomicAnd;
6150 break;
6151 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006152 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006153 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006154 opCode = spv::OpAtomicOr;
6155 break;
6156 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006157 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006158 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006159 opCode = spv::OpAtomicXor;
6160 break;
6161 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006162 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006163 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006164 opCode = spv::OpAtomicExchange;
6165 break;
6166 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006167 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006168 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006169 opCode = spv::OpAtomicCompareExchange;
6170 break;
6171 case glslang::EOpAtomicCounterIncrement:
6172 opCode = spv::OpAtomicIIncrement;
6173 break;
6174 case glslang::EOpAtomicCounterDecrement:
6175 opCode = spv::OpAtomicIDecrement;
6176 break;
6177 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006178 case glslang::EOpImageAtomicLoad:
6179 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006180 opCode = spv::OpAtomicLoad;
6181 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006182 case glslang::EOpAtomicStore:
6183 case glslang::EOpImageAtomicStore:
6184 opCode = spv::OpAtomicStore;
6185 break;
John Kessenich426394d2015-07-23 10:22:48 -06006186 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006187 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006188 break;
6189 }
6190
Rex Xue8fe8b02017-09-26 15:42:56 +08006191 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6192 builder.addCapability(spv::CapabilityInt64Atomics);
6193
John Kessenich426394d2015-07-23 10:22:48 -06006194 // Sort out the operands
6195 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006196 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006197 // - compare-exchange swaps the value and comparator
6198 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006199 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006200 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6201 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6202 spv::Id scopeId;
6203 if (glslangIntermediate->usingVulkanMemoryModel()) {
6204 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6205 } else {
6206 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6207 }
6208 // semantics default to relaxed
6209 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
6210 spv::Id semanticsId2 = semanticsId;
6211
6212 pointerId = operands[0];
6213 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6214 // no additional operands
6215 } else if (opCode == spv::OpAtomicCompareExchange) {
6216 compareId = operands[1];
6217 valueId = operands[2];
6218 if (operands.size() > 3) {
6219 scopeId = operands[3];
6220 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6221 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6222 }
6223 } else if (opCode == spv::OpAtomicLoad) {
6224 if (operands.size() > 1) {
6225 scopeId = operands[1];
6226 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6227 }
6228 } else {
6229 // atomic store or RMW
6230 valueId = operands[1];
6231 if (operands.size() > 2) {
6232 scopeId = operands[2];
6233 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6234 }
Rex Xu04db3f52015-09-16 11:44:02 +08006235 }
John Kessenich426394d2015-07-23 10:22:48 -06006236
Jeff Bolz36831c92018-09-05 10:11:41 -05006237 // Check for capabilities
6238 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
6239 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6240 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6241 }
John Kessenich426394d2015-07-23 10:22:48 -06006242
Jeff Bolz36831c92018-09-05 10:11:41 -05006243 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6244 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6245 }
John Kessenich48d6e792017-10-06 21:21:48 -06006246
Jeff Bolz36831c92018-09-05 10:11:41 -05006247 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6248 spvAtomicOperands.push_back(pointerId);
6249 spvAtomicOperands.push_back(scopeId);
6250 spvAtomicOperands.push_back(semanticsId);
6251 if (opCode == spv::OpAtomicCompareExchange) {
6252 spvAtomicOperands.push_back(semanticsId2);
6253 spvAtomicOperands.push_back(valueId);
6254 spvAtomicOperands.push_back(compareId);
6255 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6256 spvAtomicOperands.push_back(valueId);
6257 }
John Kessenich48d6e792017-10-06 21:21:48 -06006258
Jeff Bolz36831c92018-09-05 10:11:41 -05006259 if (opCode == spv::OpAtomicStore) {
6260 builder.createNoResultOp(opCode, spvAtomicOperands);
6261 return 0;
6262 } else {
6263 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6264
6265 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6266 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6267 if (op == glslang::EOpAtomicCounterDecrement)
6268 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6269
6270 return resultId;
6271 }
John Kessenich426394d2015-07-23 10:22:48 -06006272}
6273
John Kessenich91cef522016-05-05 16:45:40 -06006274// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006275spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006276{
Corentin Walleze7061422018-08-08 15:20:15 +02006277#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006278 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6279 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006280#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006281
Rex Xu51596642016-09-21 18:56:12 +08006282 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006283 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006284 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6285
chaocf200da82016-12-20 12:44:35 -08006286 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6287 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006288 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6289 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006290 } else if (op == glslang::EOpAnyInvocation ||
6291 op == glslang::EOpAllInvocations ||
6292 op == glslang::EOpAllInvocationsEqual) {
6293 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6294 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006295 } else {
6296 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006297#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006298 if (op == glslang::EOpMinInvocationsNonUniform ||
6299 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006300 op == glslang::EOpAddInvocationsNonUniform ||
6301 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6302 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6303 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6304 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6305 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6306 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006307 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006308#endif
Rex Xu51596642016-09-21 18:56:12 +08006309
Rex Xu9d93a232016-05-05 12:30:44 +08006310#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006311 switch (op) {
6312 case glslang::EOpMinInvocations:
6313 case glslang::EOpMaxInvocations:
6314 case glslang::EOpAddInvocations:
6315 case glslang::EOpMinInvocationsNonUniform:
6316 case glslang::EOpMaxInvocationsNonUniform:
6317 case glslang::EOpAddInvocationsNonUniform:
6318 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006319 break;
6320 case glslang::EOpMinInvocationsInclusiveScan:
6321 case glslang::EOpMaxInvocationsInclusiveScan:
6322 case glslang::EOpAddInvocationsInclusiveScan:
6323 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6324 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6325 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6326 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006327 break;
6328 case glslang::EOpMinInvocationsExclusiveScan:
6329 case glslang::EOpMaxInvocationsExclusiveScan:
6330 case glslang::EOpAddInvocationsExclusiveScan:
6331 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6332 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6333 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6334 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006335 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006336 default:
6337 break;
Rex Xu430ef402016-10-14 17:22:23 +08006338 }
John Kessenich149afc32018-08-14 13:31:43 -06006339 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6340 spvGroupOperands.push_back(scope);
6341 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006342 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006343 spvGroupOperands.push_back(groupOp);
6344 }
Rex Xu9d93a232016-05-05 12:30:44 +08006345#endif
Rex Xu51596642016-09-21 18:56:12 +08006346 }
6347
John Kessenich149afc32018-08-14 13:31:43 -06006348 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6349 spv::IdImmediate op = { true, *opIt };
6350 spvGroupOperands.push_back(op);
6351 }
John Kessenich91cef522016-05-05 16:45:40 -06006352
6353 switch (op) {
6354 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006355 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006356 break;
John Kessenich91cef522016-05-05 16:45:40 -06006357 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006358 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006359 break;
John Kessenich91cef522016-05-05 16:45:40 -06006360 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006361 opCode = spv::OpSubgroupAllEqualKHR;
6362 break;
Rex Xu51596642016-09-21 18:56:12 +08006363 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006364 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006365 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006366 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006367 break;
6368 case glslang::EOpReadFirstInvocation:
6369 opCode = spv::OpSubgroupFirstInvocationKHR;
6370 break;
6371 case glslang::EOpBallot:
6372 {
6373 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6374 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6375 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6376 //
6377 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6378 //
6379 spv::Id uintType = builder.makeUintType(32);
6380 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6381 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6382
6383 std::vector<spv::Id> components;
6384 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6385 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6386
6387 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6388 return builder.createUnaryOp(spv::OpBitcast, typeId,
6389 builder.createCompositeConstruct(uvec2Type, components));
6390 }
6391
Rex Xu9d93a232016-05-05 12:30:44 +08006392#ifdef AMD_EXTENSIONS
6393 case glslang::EOpMinInvocations:
6394 case glslang::EOpMaxInvocations:
6395 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006396 case glslang::EOpMinInvocationsInclusiveScan:
6397 case glslang::EOpMaxInvocationsInclusiveScan:
6398 case glslang::EOpAddInvocationsInclusiveScan:
6399 case glslang::EOpMinInvocationsExclusiveScan:
6400 case glslang::EOpMaxInvocationsExclusiveScan:
6401 case glslang::EOpAddInvocationsExclusiveScan:
6402 if (op == glslang::EOpMinInvocations ||
6403 op == glslang::EOpMinInvocationsInclusiveScan ||
6404 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006405 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006406 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006407 else {
6408 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006409 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006410 else
Rex Xu51596642016-09-21 18:56:12 +08006411 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006412 }
Rex Xu430ef402016-10-14 17:22:23 +08006413 } else if (op == glslang::EOpMaxInvocations ||
6414 op == glslang::EOpMaxInvocationsInclusiveScan ||
6415 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006416 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006417 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006418 else {
6419 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006420 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006421 else
Rex Xu51596642016-09-21 18:56:12 +08006422 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006423 }
6424 } else {
6425 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006426 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006427 else
Rex Xu51596642016-09-21 18:56:12 +08006428 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006429 }
6430
Rex Xu2bbbe062016-08-23 15:41:05 +08006431 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006432 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006433
6434 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006435 case glslang::EOpMinInvocationsNonUniform:
6436 case glslang::EOpMaxInvocationsNonUniform:
6437 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006438 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6439 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6440 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6441 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6442 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6443 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6444 if (op == glslang::EOpMinInvocationsNonUniform ||
6445 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6446 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006447 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006448 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006449 else {
6450 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006451 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006452 else
Rex Xu51596642016-09-21 18:56:12 +08006453 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006454 }
6455 }
Rex Xu430ef402016-10-14 17:22:23 +08006456 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6457 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6458 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006459 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006460 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006461 else {
6462 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006463 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006464 else
Rex Xu51596642016-09-21 18:56:12 +08006465 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006466 }
6467 }
6468 else {
6469 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006470 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006471 else
Rex Xu51596642016-09-21 18:56:12 +08006472 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006473 }
6474
Rex Xu2bbbe062016-08-23 15:41:05 +08006475 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006476 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006477
6478 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006479#endif
John Kessenich91cef522016-05-05 16:45:40 -06006480 default:
6481 logger->missingFunctionality("invocation operation");
6482 return spv::NoResult;
6483 }
Rex Xu51596642016-09-21 18:56:12 +08006484
6485 assert(opCode != spv::OpNop);
6486 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006487}
6488
Rex Xu2bbbe062016-08-23 15:41:05 +08006489// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006490spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6491 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006492{
Rex Xub7072052016-09-26 15:53:40 +08006493#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006494 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6495 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006496 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006497 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006498 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6499 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6500 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006501#else
6502 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6503 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006504 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6505 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006506#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006507
6508 // Handle group invocation operations scalar by scalar.
6509 // The result type is the same type as the original type.
6510 // The algorithm is to:
6511 // - break the vector into scalars
6512 // - apply the operation to each scalar
6513 // - make a vector out the scalar results
6514
6515 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006516 int numComponents = builder.getNumComponents(operands[0]);
6517 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006518 std::vector<spv::Id> results;
6519
6520 // do each scalar op
6521 for (int comp = 0; comp < numComponents; ++comp) {
6522 std::vector<unsigned int> indexes;
6523 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006524 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6525 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006526 if (op == spv::OpSubgroupReadInvocationKHR) {
6527 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006528 spv::IdImmediate operand = { true, operands[1] };
6529 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006530 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006531 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6532 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006533 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006534 spv::IdImmediate operand = { true, operands[1] };
6535 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006536 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006537 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6538 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006539 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006540 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006541 spvGroupOperands.push_back(scalar);
6542 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006543
Rex Xub7072052016-09-26 15:53:40 +08006544 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006545 }
6546
6547 // put the pieces together
6548 return builder.createCompositeConstruct(typeId, results);
6549}
Rex Xu2bbbe062016-08-23 15:41:05 +08006550
John Kessenich66011cb2018-03-06 16:12:04 -07006551// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006552spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6553 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006554{
6555 // Add the required capabilities.
6556 switch (op) {
6557 case glslang::EOpSubgroupElect:
6558 builder.addCapability(spv::CapabilityGroupNonUniform);
6559 break;
6560 case glslang::EOpSubgroupAll:
6561 case glslang::EOpSubgroupAny:
6562 case glslang::EOpSubgroupAllEqual:
6563 builder.addCapability(spv::CapabilityGroupNonUniform);
6564 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6565 break;
6566 case glslang::EOpSubgroupBroadcast:
6567 case glslang::EOpSubgroupBroadcastFirst:
6568 case glslang::EOpSubgroupBallot:
6569 case glslang::EOpSubgroupInverseBallot:
6570 case glslang::EOpSubgroupBallotBitExtract:
6571 case glslang::EOpSubgroupBallotBitCount:
6572 case glslang::EOpSubgroupBallotInclusiveBitCount:
6573 case glslang::EOpSubgroupBallotExclusiveBitCount:
6574 case glslang::EOpSubgroupBallotFindLSB:
6575 case glslang::EOpSubgroupBallotFindMSB:
6576 builder.addCapability(spv::CapabilityGroupNonUniform);
6577 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6578 break;
6579 case glslang::EOpSubgroupShuffle:
6580 case glslang::EOpSubgroupShuffleXor:
6581 builder.addCapability(spv::CapabilityGroupNonUniform);
6582 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6583 break;
6584 case glslang::EOpSubgroupShuffleUp:
6585 case glslang::EOpSubgroupShuffleDown:
6586 builder.addCapability(spv::CapabilityGroupNonUniform);
6587 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6588 break;
6589 case glslang::EOpSubgroupAdd:
6590 case glslang::EOpSubgroupMul:
6591 case glslang::EOpSubgroupMin:
6592 case glslang::EOpSubgroupMax:
6593 case glslang::EOpSubgroupAnd:
6594 case glslang::EOpSubgroupOr:
6595 case glslang::EOpSubgroupXor:
6596 case glslang::EOpSubgroupInclusiveAdd:
6597 case glslang::EOpSubgroupInclusiveMul:
6598 case glslang::EOpSubgroupInclusiveMin:
6599 case glslang::EOpSubgroupInclusiveMax:
6600 case glslang::EOpSubgroupInclusiveAnd:
6601 case glslang::EOpSubgroupInclusiveOr:
6602 case glslang::EOpSubgroupInclusiveXor:
6603 case glslang::EOpSubgroupExclusiveAdd:
6604 case glslang::EOpSubgroupExclusiveMul:
6605 case glslang::EOpSubgroupExclusiveMin:
6606 case glslang::EOpSubgroupExclusiveMax:
6607 case glslang::EOpSubgroupExclusiveAnd:
6608 case glslang::EOpSubgroupExclusiveOr:
6609 case glslang::EOpSubgroupExclusiveXor:
6610 builder.addCapability(spv::CapabilityGroupNonUniform);
6611 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6612 break;
6613 case glslang::EOpSubgroupClusteredAdd:
6614 case glslang::EOpSubgroupClusteredMul:
6615 case glslang::EOpSubgroupClusteredMin:
6616 case glslang::EOpSubgroupClusteredMax:
6617 case glslang::EOpSubgroupClusteredAnd:
6618 case glslang::EOpSubgroupClusteredOr:
6619 case glslang::EOpSubgroupClusteredXor:
6620 builder.addCapability(spv::CapabilityGroupNonUniform);
6621 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6622 break;
6623 case glslang::EOpSubgroupQuadBroadcast:
6624 case glslang::EOpSubgroupQuadSwapHorizontal:
6625 case glslang::EOpSubgroupQuadSwapVertical:
6626 case glslang::EOpSubgroupQuadSwapDiagonal:
6627 builder.addCapability(spv::CapabilityGroupNonUniform);
6628 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6629 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006630#ifdef NV_EXTENSIONS
6631 case glslang::EOpSubgroupPartitionedAdd:
6632 case glslang::EOpSubgroupPartitionedMul:
6633 case glslang::EOpSubgroupPartitionedMin:
6634 case glslang::EOpSubgroupPartitionedMax:
6635 case glslang::EOpSubgroupPartitionedAnd:
6636 case glslang::EOpSubgroupPartitionedOr:
6637 case glslang::EOpSubgroupPartitionedXor:
6638 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6639 case glslang::EOpSubgroupPartitionedInclusiveMul:
6640 case glslang::EOpSubgroupPartitionedInclusiveMin:
6641 case glslang::EOpSubgroupPartitionedInclusiveMax:
6642 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6643 case glslang::EOpSubgroupPartitionedInclusiveOr:
6644 case glslang::EOpSubgroupPartitionedInclusiveXor:
6645 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6646 case glslang::EOpSubgroupPartitionedExclusiveMul:
6647 case glslang::EOpSubgroupPartitionedExclusiveMin:
6648 case glslang::EOpSubgroupPartitionedExclusiveMax:
6649 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6650 case glslang::EOpSubgroupPartitionedExclusiveOr:
6651 case glslang::EOpSubgroupPartitionedExclusiveXor:
6652 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6653 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6654 break;
6655#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006656 default: assert(0 && "Unhandled subgroup operation!");
6657 }
6658
6659 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6660 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6661 const bool isBool = typeProxy == glslang::EbtBool;
6662
6663 spv::Op opCode = spv::OpNop;
6664
6665 // Figure out which opcode to use.
6666 switch (op) {
6667 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6668 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6669 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6670 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6671 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6672 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6673 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6674 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6675 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6676 case glslang::EOpSubgroupBallotBitCount:
6677 case glslang::EOpSubgroupBallotInclusiveBitCount:
6678 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6679 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6680 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6681 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6682 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6683 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6684 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6685 case glslang::EOpSubgroupAdd:
6686 case glslang::EOpSubgroupInclusiveAdd:
6687 case glslang::EOpSubgroupExclusiveAdd:
6688 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006689#ifdef NV_EXTENSIONS
6690 case glslang::EOpSubgroupPartitionedAdd:
6691 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6692 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6693#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006694 if (isFloat) {
6695 opCode = spv::OpGroupNonUniformFAdd;
6696 } else {
6697 opCode = spv::OpGroupNonUniformIAdd;
6698 }
6699 break;
6700 case glslang::EOpSubgroupMul:
6701 case glslang::EOpSubgroupInclusiveMul:
6702 case glslang::EOpSubgroupExclusiveMul:
6703 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006704#ifdef NV_EXTENSIONS
6705 case glslang::EOpSubgroupPartitionedMul:
6706 case glslang::EOpSubgroupPartitionedInclusiveMul:
6707 case glslang::EOpSubgroupPartitionedExclusiveMul:
6708#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006709 if (isFloat) {
6710 opCode = spv::OpGroupNonUniformFMul;
6711 } else {
6712 opCode = spv::OpGroupNonUniformIMul;
6713 }
6714 break;
6715 case glslang::EOpSubgroupMin:
6716 case glslang::EOpSubgroupInclusiveMin:
6717 case glslang::EOpSubgroupExclusiveMin:
6718 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006719#ifdef NV_EXTENSIONS
6720 case glslang::EOpSubgroupPartitionedMin:
6721 case glslang::EOpSubgroupPartitionedInclusiveMin:
6722 case glslang::EOpSubgroupPartitionedExclusiveMin:
6723#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006724 if (isFloat) {
6725 opCode = spv::OpGroupNonUniformFMin;
6726 } else if (isUnsigned) {
6727 opCode = spv::OpGroupNonUniformUMin;
6728 } else {
6729 opCode = spv::OpGroupNonUniformSMin;
6730 }
6731 break;
6732 case glslang::EOpSubgroupMax:
6733 case glslang::EOpSubgroupInclusiveMax:
6734 case glslang::EOpSubgroupExclusiveMax:
6735 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006736#ifdef NV_EXTENSIONS
6737 case glslang::EOpSubgroupPartitionedMax:
6738 case glslang::EOpSubgroupPartitionedInclusiveMax:
6739 case glslang::EOpSubgroupPartitionedExclusiveMax:
6740#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006741 if (isFloat) {
6742 opCode = spv::OpGroupNonUniformFMax;
6743 } else if (isUnsigned) {
6744 opCode = spv::OpGroupNonUniformUMax;
6745 } else {
6746 opCode = spv::OpGroupNonUniformSMax;
6747 }
6748 break;
6749 case glslang::EOpSubgroupAnd:
6750 case glslang::EOpSubgroupInclusiveAnd:
6751 case glslang::EOpSubgroupExclusiveAnd:
6752 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006753#ifdef NV_EXTENSIONS
6754 case glslang::EOpSubgroupPartitionedAnd:
6755 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6756 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6757#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006758 if (isBool) {
6759 opCode = spv::OpGroupNonUniformLogicalAnd;
6760 } else {
6761 opCode = spv::OpGroupNonUniformBitwiseAnd;
6762 }
6763 break;
6764 case glslang::EOpSubgroupOr:
6765 case glslang::EOpSubgroupInclusiveOr:
6766 case glslang::EOpSubgroupExclusiveOr:
6767 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006768#ifdef NV_EXTENSIONS
6769 case glslang::EOpSubgroupPartitionedOr:
6770 case glslang::EOpSubgroupPartitionedInclusiveOr:
6771 case glslang::EOpSubgroupPartitionedExclusiveOr:
6772#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006773 if (isBool) {
6774 opCode = spv::OpGroupNonUniformLogicalOr;
6775 } else {
6776 opCode = spv::OpGroupNonUniformBitwiseOr;
6777 }
6778 break;
6779 case glslang::EOpSubgroupXor:
6780 case glslang::EOpSubgroupInclusiveXor:
6781 case glslang::EOpSubgroupExclusiveXor:
6782 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006783#ifdef NV_EXTENSIONS
6784 case glslang::EOpSubgroupPartitionedXor:
6785 case glslang::EOpSubgroupPartitionedInclusiveXor:
6786 case glslang::EOpSubgroupPartitionedExclusiveXor:
6787#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006788 if (isBool) {
6789 opCode = spv::OpGroupNonUniformLogicalXor;
6790 } else {
6791 opCode = spv::OpGroupNonUniformBitwiseXor;
6792 }
6793 break;
6794 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6795 case glslang::EOpSubgroupQuadSwapHorizontal:
6796 case glslang::EOpSubgroupQuadSwapVertical:
6797 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6798 default: assert(0 && "Unhandled subgroup operation!");
6799 }
6800
John Kessenich149afc32018-08-14 13:31:43 -06006801 // get the right Group Operation
6802 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006803 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006804 default:
6805 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006806 case glslang::EOpSubgroupBallotBitCount:
6807 case glslang::EOpSubgroupAdd:
6808 case glslang::EOpSubgroupMul:
6809 case glslang::EOpSubgroupMin:
6810 case glslang::EOpSubgroupMax:
6811 case glslang::EOpSubgroupAnd:
6812 case glslang::EOpSubgroupOr:
6813 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006814 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006815 break;
6816 case glslang::EOpSubgroupBallotInclusiveBitCount:
6817 case glslang::EOpSubgroupInclusiveAdd:
6818 case glslang::EOpSubgroupInclusiveMul:
6819 case glslang::EOpSubgroupInclusiveMin:
6820 case glslang::EOpSubgroupInclusiveMax:
6821 case glslang::EOpSubgroupInclusiveAnd:
6822 case glslang::EOpSubgroupInclusiveOr:
6823 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006824 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006825 break;
6826 case glslang::EOpSubgroupBallotExclusiveBitCount:
6827 case glslang::EOpSubgroupExclusiveAdd:
6828 case glslang::EOpSubgroupExclusiveMul:
6829 case glslang::EOpSubgroupExclusiveMin:
6830 case glslang::EOpSubgroupExclusiveMax:
6831 case glslang::EOpSubgroupExclusiveAnd:
6832 case glslang::EOpSubgroupExclusiveOr:
6833 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006834 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006835 break;
6836 case glslang::EOpSubgroupClusteredAdd:
6837 case glslang::EOpSubgroupClusteredMul:
6838 case glslang::EOpSubgroupClusteredMin:
6839 case glslang::EOpSubgroupClusteredMax:
6840 case glslang::EOpSubgroupClusteredAnd:
6841 case glslang::EOpSubgroupClusteredOr:
6842 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006843 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006844 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006845#ifdef NV_EXTENSIONS
6846 case glslang::EOpSubgroupPartitionedAdd:
6847 case glslang::EOpSubgroupPartitionedMul:
6848 case glslang::EOpSubgroupPartitionedMin:
6849 case glslang::EOpSubgroupPartitionedMax:
6850 case glslang::EOpSubgroupPartitionedAnd:
6851 case glslang::EOpSubgroupPartitionedOr:
6852 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006853 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006854 break;
6855 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6856 case glslang::EOpSubgroupPartitionedInclusiveMul:
6857 case glslang::EOpSubgroupPartitionedInclusiveMin:
6858 case glslang::EOpSubgroupPartitionedInclusiveMax:
6859 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6860 case glslang::EOpSubgroupPartitionedInclusiveOr:
6861 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006862 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006863 break;
6864 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6865 case glslang::EOpSubgroupPartitionedExclusiveMul:
6866 case glslang::EOpSubgroupPartitionedExclusiveMin:
6867 case glslang::EOpSubgroupPartitionedExclusiveMax:
6868 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6869 case glslang::EOpSubgroupPartitionedExclusiveOr:
6870 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006871 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006872 break;
6873#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006874 }
6875
John Kessenich149afc32018-08-14 13:31:43 -06006876 // build the instruction
6877 std::vector<spv::IdImmediate> spvGroupOperands;
6878
6879 // Every operation begins with the Execution Scope operand.
6880 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6881 spvGroupOperands.push_back(executionScope);
6882
6883 // Next, for all operations that use a Group Operation, push that as an operand.
6884 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006885 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006886 spvGroupOperands.push_back(groupOperand);
6887 }
6888
John Kessenich66011cb2018-03-06 16:12:04 -07006889 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006890 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6891 spv::IdImmediate operand = { true, *opIt };
6892 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006893 }
6894
6895 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006896 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006897 switch (op) {
6898 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006899 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6900 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6901 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6902 }
6903 if (directionId != spv::NoResult) {
6904 spv::IdImmediate direction = { true, directionId };
6905 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006906 }
6907
6908 return builder.createOp(opCode, typeId, spvGroupOperands);
6909}
6910
John Kessenich5e4b1242015-08-06 22:53:06 -06006911spv::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 -06006912{
John Kessenich66011cb2018-03-06 16:12:04 -07006913 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6914 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006915
John Kessenich140f3df2015-06-26 16:58:36 -06006916 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006917 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006918 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006919 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006920 spv::Id typeId0 = 0;
6921 if (consumedOperands > 0)
6922 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006923 spv::Id typeId1 = 0;
6924 if (consumedOperands > 1)
6925 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006926 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006927
6928 switch (op) {
6929 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006930 if (isFloat)
6931 libCall = spv::GLSLstd450FMin;
6932 else if (isUnsigned)
6933 libCall = spv::GLSLstd450UMin;
6934 else
6935 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006936 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006937 break;
6938 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006939 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006940 break;
6941 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006942 if (isFloat)
6943 libCall = spv::GLSLstd450FMax;
6944 else if (isUnsigned)
6945 libCall = spv::GLSLstd450UMax;
6946 else
6947 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006948 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006949 break;
6950 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006951 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006952 break;
6953 case glslang::EOpDot:
6954 opCode = spv::OpDot;
6955 break;
6956 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006957 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006958 break;
6959
6960 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006961 if (isFloat)
6962 libCall = spv::GLSLstd450FClamp;
6963 else if (isUnsigned)
6964 libCall = spv::GLSLstd450UClamp;
6965 else
6966 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006967 builder.promoteScalar(precision, operands.front(), operands[1]);
6968 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006969 break;
6970 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006971 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6972 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006973 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006974 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006975 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006976 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006977 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006978 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006979 break;
6980 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006981 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006982 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006983 break;
6984 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006985 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006986 builder.promoteScalar(precision, operands[0], operands[2]);
6987 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006988 break;
6989
6990 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006991 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006992 break;
6993 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006994 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006995 break;
6996 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006997 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006998 break;
6999 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007000 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007001 break;
7002 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007003 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007004 break;
Rex Xu7a26c172015-12-08 17:12:09 +08007005 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007006#ifdef AMD_EXTENSIONS
7007 if (typeProxy == glslang::EbtFloat16)
7008 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7009#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007010 libCall = spv::GLSLstd450InterpolateAtSample;
7011 break;
7012 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007013#ifdef AMD_EXTENSIONS
7014 if (typeProxy == glslang::EbtFloat16)
7015 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7016#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007017 libCall = spv::GLSLstd450InterpolateAtOffset;
7018 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007019 case glslang::EOpAddCarry:
7020 opCode = spv::OpIAddCarry;
7021 typeId = builder.makeStructResultType(typeId0, typeId0);
7022 consumedOperands = 2;
7023 break;
7024 case glslang::EOpSubBorrow:
7025 opCode = spv::OpISubBorrow;
7026 typeId = builder.makeStructResultType(typeId0, typeId0);
7027 consumedOperands = 2;
7028 break;
7029 case glslang::EOpUMulExtended:
7030 opCode = spv::OpUMulExtended;
7031 typeId = builder.makeStructResultType(typeId0, typeId0);
7032 consumedOperands = 2;
7033 break;
7034 case glslang::EOpIMulExtended:
7035 opCode = spv::OpSMulExtended;
7036 typeId = builder.makeStructResultType(typeId0, typeId0);
7037 consumedOperands = 2;
7038 break;
7039 case glslang::EOpBitfieldExtract:
7040 if (isUnsigned)
7041 opCode = spv::OpBitFieldUExtract;
7042 else
7043 opCode = spv::OpBitFieldSExtract;
7044 break;
7045 case glslang::EOpBitfieldInsert:
7046 opCode = spv::OpBitFieldInsert;
7047 break;
7048
7049 case glslang::EOpFma:
7050 libCall = spv::GLSLstd450Fma;
7051 break;
7052 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007053 {
7054 libCall = spv::GLSLstd450FrexpStruct;
7055 assert(builder.isPointerType(typeId1));
7056 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007057 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007058#ifdef AMD_EXTENSIONS
7059 if (width == 16)
7060 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7061 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
7062#endif
Rex Xu470026f2017-03-29 17:12:40 +08007063 if (builder.getNumComponents(operands[0]) == 1)
7064 frexpIntType = builder.makeIntegerType(width, true);
7065 else
7066 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7067 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7068 consumedOperands = 1;
7069 }
John Kessenich55e7d112015-11-15 21:33:39 -07007070 break;
7071 case glslang::EOpLdexp:
7072 libCall = spv::GLSLstd450Ldexp;
7073 break;
7074
Rex Xu574ab042016-04-14 16:53:07 +08007075 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007076 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007077
John Kessenich66011cb2018-03-06 16:12:04 -07007078 case glslang::EOpSubgroupBroadcast:
7079 case glslang::EOpSubgroupBallotBitExtract:
7080 case glslang::EOpSubgroupShuffle:
7081 case glslang::EOpSubgroupShuffleXor:
7082 case glslang::EOpSubgroupShuffleUp:
7083 case glslang::EOpSubgroupShuffleDown:
7084 case glslang::EOpSubgroupClusteredAdd:
7085 case glslang::EOpSubgroupClusteredMul:
7086 case glslang::EOpSubgroupClusteredMin:
7087 case glslang::EOpSubgroupClusteredMax:
7088 case glslang::EOpSubgroupClusteredAnd:
7089 case glslang::EOpSubgroupClusteredOr:
7090 case glslang::EOpSubgroupClusteredXor:
7091 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007092#ifdef NV_EXTENSIONS
7093 case glslang::EOpSubgroupPartitionedAdd:
7094 case glslang::EOpSubgroupPartitionedMul:
7095 case glslang::EOpSubgroupPartitionedMin:
7096 case glslang::EOpSubgroupPartitionedMax:
7097 case glslang::EOpSubgroupPartitionedAnd:
7098 case glslang::EOpSubgroupPartitionedOr:
7099 case glslang::EOpSubgroupPartitionedXor:
7100 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7101 case glslang::EOpSubgroupPartitionedInclusiveMul:
7102 case glslang::EOpSubgroupPartitionedInclusiveMin:
7103 case glslang::EOpSubgroupPartitionedInclusiveMax:
7104 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7105 case glslang::EOpSubgroupPartitionedInclusiveOr:
7106 case glslang::EOpSubgroupPartitionedInclusiveXor:
7107 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7108 case glslang::EOpSubgroupPartitionedExclusiveMul:
7109 case glslang::EOpSubgroupPartitionedExclusiveMin:
7110 case glslang::EOpSubgroupPartitionedExclusiveMax:
7111 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7112 case glslang::EOpSubgroupPartitionedExclusiveOr:
7113 case glslang::EOpSubgroupPartitionedExclusiveXor:
7114#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007115 return createSubgroupOperation(op, typeId, operands, typeProxy);
7116
Rex Xu9d93a232016-05-05 12:30:44 +08007117#ifdef AMD_EXTENSIONS
7118 case glslang::EOpSwizzleInvocations:
7119 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7120 libCall = spv::SwizzleInvocationsAMD;
7121 break;
7122 case glslang::EOpSwizzleInvocationsMasked:
7123 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7124 libCall = spv::SwizzleInvocationsMaskedAMD;
7125 break;
7126 case glslang::EOpWriteInvocation:
7127 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7128 libCall = spv::WriteInvocationAMD;
7129 break;
7130
7131 case glslang::EOpMin3:
7132 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7133 if (isFloat)
7134 libCall = spv::FMin3AMD;
7135 else {
7136 if (isUnsigned)
7137 libCall = spv::UMin3AMD;
7138 else
7139 libCall = spv::SMin3AMD;
7140 }
7141 break;
7142 case glslang::EOpMax3:
7143 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7144 if (isFloat)
7145 libCall = spv::FMax3AMD;
7146 else {
7147 if (isUnsigned)
7148 libCall = spv::UMax3AMD;
7149 else
7150 libCall = spv::SMax3AMD;
7151 }
7152 break;
7153 case glslang::EOpMid3:
7154 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7155 if (isFloat)
7156 libCall = spv::FMid3AMD;
7157 else {
7158 if (isUnsigned)
7159 libCall = spv::UMid3AMD;
7160 else
7161 libCall = spv::SMid3AMD;
7162 }
7163 break;
7164
7165 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007166 if (typeProxy == glslang::EbtFloat16)
7167 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007168 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7169 libCall = spv::InterpolateAtVertexAMD;
7170 break;
7171#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007172 case glslang::EOpBarrier:
7173 {
7174 // This is for the extended controlBarrier function, with four operands.
7175 // The unextended barrier() goes through createNoArgOperation.
7176 assert(operands.size() == 4);
7177 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7178 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7179 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7180 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7181 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7182 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7183 }
7184 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7185 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7186 }
7187 return 0;
7188 }
7189 break;
7190 case glslang::EOpMemoryBarrier:
7191 {
7192 // This is for the extended memoryBarrier function, with three operands.
7193 // The unextended memoryBarrier() goes through createNoArgOperation.
7194 assert(operands.size() == 3);
7195 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7196 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7197 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7198 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7199 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7200 }
7201 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7202 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7203 }
7204 return 0;
7205 }
7206 break;
Chao Chen3c366992018-09-19 11:41:59 -07007207
7208#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007209 case glslang::EOpReportIntersectionNV:
7210 {
7211 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007212 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007213 }
7214 break;
7215 case glslang::EOpTraceNV:
7216 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007217 builder.createNoResultOp(spv::OpTraceNV, operands);
7218 return 0;
7219 }
7220 break;
7221 case glslang::EOpExecuteCallableNV:
7222 {
7223 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007224 return 0;
7225 }
7226 break;
Chao Chen3c366992018-09-19 11:41:59 -07007227 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7228 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7229 return 0;
7230#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007231 case glslang::EOpCooperativeMatrixMulAdd:
7232 opCode = spv::OpCooperativeMatrixMulAddNV;
7233 break;
7234
John Kessenich140f3df2015-06-26 16:58:36 -06007235 default:
7236 return 0;
7237 }
7238
7239 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007240 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007241 // Use an extended instruction from the standard library.
7242 // Construct the call arguments, without modifying the original operands vector.
7243 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7244 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007245 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007246 } else if (opCode == spv::OpDot && !isFloat) {
7247 // int dot(int, int)
7248 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7249 const int componentCount = builder.getNumComponents(operands[0]);
7250 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7251 builder.setPrecision(mulOp, precision);
7252 id = builder.createCompositeExtract(mulOp, typeId, 0);
7253 for (int i = 1; i < componentCount; ++i) {
7254 builder.setPrecision(id, precision);
7255 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7256 }
John Kessenich2359bd02015-12-06 19:29:11 -07007257 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007258 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007259 case 0:
7260 // should all be handled by visitAggregate and createNoArgOperation
7261 assert(0);
7262 return 0;
7263 case 1:
7264 // should all be handled by createUnaryOperation
7265 assert(0);
7266 return 0;
7267 case 2:
7268 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7269 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007270 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007271 // anything 3 or over doesn't have l-value operands, so all should be consumed
7272 assert(consumedOperands == operands.size());
7273 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007274 break;
7275 }
7276 }
7277
John Kessenich55e7d112015-11-15 21:33:39 -07007278 // Decode the return types that were structures
7279 switch (op) {
7280 case glslang::EOpAddCarry:
7281 case glslang::EOpSubBorrow:
7282 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7283 id = builder.createCompositeExtract(id, typeId0, 0);
7284 break;
7285 case glslang::EOpUMulExtended:
7286 case glslang::EOpIMulExtended:
7287 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7288 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7289 break;
7290 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007291 {
7292 assert(operands.size() == 2);
7293 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7294 // "exp" is floating-point type (from HLSL intrinsic)
7295 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7296 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7297 builder.createStore(member1, operands[1]);
7298 } else
7299 // "exp" is integer type (from GLSL built-in function)
7300 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7301 id = builder.createCompositeExtract(id, typeId0, 0);
7302 }
John Kessenich55e7d112015-11-15 21:33:39 -07007303 break;
7304 default:
7305 break;
7306 }
7307
John Kessenich32cfd492016-02-02 12:37:46 -07007308 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007309}
7310
Rex Xu9d93a232016-05-05 12:30:44 +08007311// Intrinsics with no arguments (or no return value, and no precision).
7312spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007313{
Jeff Bolz36831c92018-09-05 10:11:41 -05007314 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7315 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007316
7317 switch (op) {
7318 case glslang::EOpEmitVertex:
7319 builder.createNoResultOp(spv::OpEmitVertex);
7320 return 0;
7321 case glslang::EOpEndPrimitive:
7322 builder.createNoResultOp(spv::OpEndPrimitive);
7323 return 0;
7324 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007325 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007326 if (glslangIntermediate->usingVulkanMemoryModel()) {
7327 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7328 spv::MemorySemanticsOutputMemoryKHRMask |
7329 spv::MemorySemanticsAcquireReleaseMask);
7330 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7331 } else {
7332 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7333 }
John Kessenich82979362017-12-11 04:02:24 -07007334 } else {
7335 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7336 spv::MemorySemanticsWorkgroupMemoryMask |
7337 spv::MemorySemanticsAcquireReleaseMask);
7338 }
John Kessenich140f3df2015-06-26 16:58:36 -06007339 return 0;
7340 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007341 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7342 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007343 return 0;
7344 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007345 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7346 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007347 return 0;
7348 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007349 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7350 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007351 return 0;
7352 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007353 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7354 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007355 return 0;
7356 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007357 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7358 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007359 return 0;
7360 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007361 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7362 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007363 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007364 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007365 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007366 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007367 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007368 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007369 case glslang::EOpDeviceMemoryBarrier:
7370 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7371 spv::MemorySemanticsImageMemoryMask |
7372 spv::MemorySemanticsAcquireReleaseMask);
7373 return 0;
7374 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7375 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7376 spv::MemorySemanticsImageMemoryMask |
7377 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007378 return 0;
7379 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007380 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7381 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007382 return 0;
7383 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007384 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7385 spv::MemorySemanticsWorkgroupMemoryMask |
7386 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007387 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007388 case glslang::EOpSubgroupBarrier:
7389 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7390 spv::MemorySemanticsAcquireReleaseMask);
7391 return spv::NoResult;
7392 case glslang::EOpSubgroupMemoryBarrier:
7393 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7394 spv::MemorySemanticsAcquireReleaseMask);
7395 return spv::NoResult;
7396 case glslang::EOpSubgroupMemoryBarrierBuffer:
7397 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7398 spv::MemorySemanticsAcquireReleaseMask);
7399 return spv::NoResult;
7400 case glslang::EOpSubgroupMemoryBarrierImage:
7401 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7402 spv::MemorySemanticsAcquireReleaseMask);
7403 return spv::NoResult;
7404 case glslang::EOpSubgroupMemoryBarrierShared:
7405 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7406 spv::MemorySemanticsAcquireReleaseMask);
7407 return spv::NoResult;
7408 case glslang::EOpSubgroupElect: {
7409 std::vector<spv::Id> operands;
7410 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7411 }
Rex Xu9d93a232016-05-05 12:30:44 +08007412#ifdef AMD_EXTENSIONS
7413 case glslang::EOpTime:
7414 {
7415 std::vector<spv::Id> args; // Dummy arguments
7416 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7417 return builder.setPrecision(id, precision);
7418 }
7419#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007420#ifdef NV_EXTENSIONS
7421 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007422 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007423 return 0;
7424 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007425 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007426 return 0;
7427#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007428 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007429 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007430 return 0;
7431 }
7432}
7433
7434spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7435{
John Kessenich2f273362015-07-18 22:34:27 -06007436 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007437 spv::Id id;
7438 if (symbolValues.end() != iter) {
7439 id = iter->second;
7440 return id;
7441 }
7442
7443 // it was not found, create it
7444 id = createSpvVariable(symbol);
7445 symbolValues[symbol->getId()] = id;
7446
Rex Xuc884b4a2016-06-29 15:03:44 +08007447 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007448 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7449 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7450 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007451#ifdef NV_EXTENSIONS
7452 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7453#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007454 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007455 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007456 if (symbol->getQualifier().hasIndex())
7457 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7458 if (symbol->getQualifier().hasComponent())
7459 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007460 // atomic counters use this:
7461 if (symbol->getQualifier().hasOffset())
7462 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007463 }
7464
scygan2c864272016-05-18 18:09:17 +02007465 if (symbol->getQualifier().hasLocation())
7466 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007467 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007468 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007469 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007470 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007471 }
John Kessenich140f3df2015-06-26 16:58:36 -06007472 if (symbol->getQualifier().hasSet())
7473 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007474 else if (IsDescriptorResource(symbol->getType())) {
7475 // default to 0
7476 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7477 }
John Kessenich140f3df2015-06-26 16:58:36 -06007478 if (symbol->getQualifier().hasBinding())
7479 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007480 else if (IsDescriptorResource(symbol->getType())) {
7481 // default to 0
7482 builder.addDecoration(id, spv::DecorationBinding, 0);
7483 }
John Kessenich6c292d32016-02-15 20:58:50 -07007484 if (symbol->getQualifier().hasAttachment())
7485 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007486 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007487 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007488 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007489 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007490 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7491 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7492 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7493 }
7494 if (symbol->getQualifier().hasXfbOffset())
7495 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007496 }
7497
Rex Xu1da878f2016-02-21 20:59:01 +08007498 if (symbol->getType().isImage()) {
7499 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007500 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007501 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007502 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007503 }
7504
John Kessenich140f3df2015-06-26 16:58:36 -06007505 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007506 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007507 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007508 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007509
John Kessenich5611c6d2018-04-05 11:25:02 -06007510 // nonuniform
7511 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7512
John Kessenichecba76f2017-01-06 00:34:48 -07007513#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007514 if (builtIn == spv::BuiltInSampleMask) {
7515 spv::Decoration decoration;
7516 // GL_NV_sample_mask_override_coverage extension
7517 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007518 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007519 else
7520 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007521 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007522 if (decoration != spv::DecorationMax) {
7523 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7524 }
7525 }
chaoc771d89f2017-01-13 01:10:53 -08007526 else if (builtIn == spv::BuiltInLayer) {
7527 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007528 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007529 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007530 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7531 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7532 }
John Kessenichb41bff62017-08-11 13:07:17 -06007533 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007534 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7535 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007536 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7537 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7538 }
7539 }
7540
chaoc6e5acae2016-12-20 13:28:52 -08007541 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007542 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007543 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007544 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7545 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007546 if (symbol->getQualifier().pervertexNV) {
7547 builder.addDecoration(id, spv::DecorationPerVertexNV);
7548 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7549 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7550 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007551#endif
7552
John Kessenich5d610ee2018-03-07 18:05:55 -07007553 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7554 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7555 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7556 symbol->getType().getQualifier().semanticName);
7557 }
7558
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007559 if (symbol->getBasicType() == glslang::EbtReference) {
7560 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7561 }
7562
John Kessenich140f3df2015-06-26 16:58:36 -06007563 return id;
7564}
7565
Chao Chen3c366992018-09-19 11:41:59 -07007566#ifdef NV_EXTENSIONS
7567// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7568void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7569{
7570 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007571 if (qualifier.perPrimitiveNV) {
7572 // Need to add capability/extension for fragment shader.
7573 // Mesh shader already adds this by default.
7574 if (glslangIntermediate->getStage() == EShLangFragment) {
7575 builder.addCapability(spv::CapabilityMeshShadingNV);
7576 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7577 }
Chao Chen3c366992018-09-19 11:41:59 -07007578 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007579 }
Chao Chen3c366992018-09-19 11:41:59 -07007580 if (qualifier.perViewNV)
7581 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7582 if (qualifier.perTaskNV)
7583 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7584 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007585 if (qualifier.perPrimitiveNV) {
7586 // Need to add capability/extension for fragment shader.
7587 // Mesh shader already adds this by default.
7588 if (glslangIntermediate->getStage() == EShLangFragment) {
7589 builder.addCapability(spv::CapabilityMeshShadingNV);
7590 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7591 }
Chao Chen3c366992018-09-19 11:41:59 -07007592 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007593 }
Chao Chen3c366992018-09-19 11:41:59 -07007594 if (qualifier.perViewNV)
7595 builder.addDecoration(id, spv::DecorationPerViewNV);
7596 if (qualifier.perTaskNV)
7597 builder.addDecoration(id, spv::DecorationPerTaskNV);
7598 }
7599}
7600#endif
7601
John Kessenich55e7d112015-11-15 21:33:39 -07007602// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007603// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007604//
7605// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7606//
7607// Recursively walk the nodes. The nodes form a tree whose leaves are
7608// regular constants, which themselves are trees that createSpvConstant()
7609// recursively walks. So, this function walks the "top" of the tree:
7610// - emit specialization constant-building instructions for specConstant
7611// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007612spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007613{
John Kessenich7cc0e282016-03-20 00:46:02 -06007614 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007615
qining4f4bb812016-04-03 23:55:17 -04007616 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007617 if (! node.getQualifier().specConstant) {
7618 // hand off to the non-spec-constant path
7619 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7620 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007621 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007622 nextConst, false);
7623 }
7624
7625 // We now know we have a specialization constant to build
7626
John Kessenichd94c0032016-05-30 19:29:40 -06007627 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007628 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7629 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7630 std::vector<spv::Id> dimConstId;
7631 for (int dim = 0; dim < 3; ++dim) {
7632 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7633 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007634 if (specConst) {
7635 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7636 glslangIntermediate->getLocalSizeSpecId(dim));
7637 }
qining4f4bb812016-04-03 23:55:17 -04007638 }
7639 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7640 }
7641
7642 // An AST node labelled as specialization constant should be a symbol node.
7643 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7644 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007645 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007646 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007647 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7648 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7649 // will set the builder into spec constant op instruction generating mode.
7650 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007651 result = accessChainLoad(sub_tree->getType());
7652 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007653 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007654 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007655 } else {
7656 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007657 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007658 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007659 builder.addName(result, sn->getName().c_str());
7660 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007661 }
qining4f4bb812016-04-03 23:55:17 -04007662
7663 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7664 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007665 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007666 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007667}
7668
John Kessenich140f3df2015-06-26 16:58:36 -06007669// Use 'consts' as the flattened glslang source of scalar constants to recursively
7670// build the aggregate SPIR-V constant.
7671//
7672// If there are not enough elements present in 'consts', 0 will be substituted;
7673// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7674//
qining08408382016-03-21 09:51:37 -04007675spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007676{
7677 // vector of constants for SPIR-V
7678 std::vector<spv::Id> spvConsts;
7679
7680 // Type is used for struct and array constants
7681 spv::Id typeId = convertGlslangToSpvType(glslangType);
7682
7683 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007684 glslang::TType elementType(glslangType, 0);
7685 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007686 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007687 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007688 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007689 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007690 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007691 } else if (glslangType.isCoopMat()) {
7692 glslang::TType componentType(glslangType.getBasicType());
7693 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007694 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007695 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7696 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007697 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007698 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007699 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7700 bool zero = nextConst >= consts.size();
7701 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007702 case glslang::EbtInt8:
7703 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7704 break;
7705 case glslang::EbtUint8:
7706 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7707 break;
7708 case glslang::EbtInt16:
7709 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7710 break;
7711 case glslang::EbtUint16:
7712 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7713 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007714 case glslang::EbtInt:
7715 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7716 break;
7717 case glslang::EbtUint:
7718 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7719 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007720 case glslang::EbtInt64:
7721 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7722 break;
7723 case glslang::EbtUint64:
7724 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7725 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007726 case glslang::EbtFloat:
7727 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7728 break;
7729 case glslang::EbtDouble:
7730 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7731 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007732 case glslang::EbtFloat16:
7733 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7734 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007735 case glslang::EbtBool:
7736 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7737 break;
7738 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007739 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007740 break;
7741 }
7742 ++nextConst;
7743 }
7744 } else {
7745 // we have a non-aggregate (scalar) constant
7746 bool zero = nextConst >= consts.size();
7747 spv::Id scalar = 0;
7748 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007749 case glslang::EbtInt8:
7750 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7751 break;
7752 case glslang::EbtUint8:
7753 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7754 break;
7755 case glslang::EbtInt16:
7756 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7757 break;
7758 case glslang::EbtUint16:
7759 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7760 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007761 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007762 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007763 break;
7764 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007765 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007766 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007767 case glslang::EbtInt64:
7768 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7769 break;
7770 case glslang::EbtUint64:
7771 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7772 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007773 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007774 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007775 break;
7776 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007777 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007778 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007779 case glslang::EbtFloat16:
7780 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7781 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007782 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007783 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007784 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007785 case glslang::EbtReference:
7786 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7787 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7788 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007789 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007790 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007791 break;
7792 }
7793 ++nextConst;
7794 return scalar;
7795 }
7796
7797 return builder.makeCompositeConstant(typeId, spvConsts);
7798}
7799
John Kessenich7c1aa102015-10-15 13:29:11 -06007800// Return true if the node is a constant or symbol whose reading has no
7801// non-trivial observable cost or effect.
7802bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7803{
7804 // don't know what this is
7805 if (node == nullptr)
7806 return false;
7807
7808 // a constant is safe
7809 if (node->getAsConstantUnion() != nullptr)
7810 return true;
7811
7812 // not a symbol means non-trivial
7813 if (node->getAsSymbolNode() == nullptr)
7814 return false;
7815
7816 // a symbol, depends on what's being read
7817 switch (node->getType().getQualifier().storage) {
7818 case glslang::EvqTemporary:
7819 case glslang::EvqGlobal:
7820 case glslang::EvqIn:
7821 case glslang::EvqInOut:
7822 case glslang::EvqConst:
7823 case glslang::EvqConstReadOnly:
7824 case glslang::EvqUniform:
7825 return true;
7826 default:
7827 return false;
7828 }
qining25262b32016-05-06 17:25:16 -04007829}
John Kessenich7c1aa102015-10-15 13:29:11 -06007830
7831// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007832// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007833// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007834// Return true if trivial.
7835bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7836{
7837 if (node == nullptr)
7838 return false;
7839
John Kessenich84cc15f2017-05-24 16:44:47 -06007840 // count non scalars as trivial, as well as anything coming from HLSL
7841 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007842 return true;
7843
John Kessenich7c1aa102015-10-15 13:29:11 -06007844 // symbols and constants are trivial
7845 if (isTrivialLeaf(node))
7846 return true;
7847
7848 // otherwise, it needs to be a simple operation or one or two leaf nodes
7849
7850 // not a simple operation
7851 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7852 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7853 if (binaryNode == nullptr && unaryNode == nullptr)
7854 return false;
7855
7856 // not on leaf nodes
7857 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7858 return false;
7859
7860 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7861 return false;
7862 }
7863
7864 switch (node->getAsOperator()->getOp()) {
7865 case glslang::EOpLogicalNot:
7866 case glslang::EOpConvIntToBool:
7867 case glslang::EOpConvUintToBool:
7868 case glslang::EOpConvFloatToBool:
7869 case glslang::EOpConvDoubleToBool:
7870 case glslang::EOpEqual:
7871 case glslang::EOpNotEqual:
7872 case glslang::EOpLessThan:
7873 case glslang::EOpGreaterThan:
7874 case glslang::EOpLessThanEqual:
7875 case glslang::EOpGreaterThanEqual:
7876 case glslang::EOpIndexDirect:
7877 case glslang::EOpIndexDirectStruct:
7878 case glslang::EOpLogicalXor:
7879 case glslang::EOpAny:
7880 case glslang::EOpAll:
7881 return true;
7882 default:
7883 return false;
7884 }
7885}
7886
7887// Emit short-circuiting code, where 'right' is never evaluated unless
7888// the left side is true (for &&) or false (for ||).
7889spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7890{
7891 spv::Id boolTypeId = builder.makeBoolType();
7892
7893 // emit left operand
7894 builder.clearAccessChain();
7895 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007896 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007897
7898 // Operands to accumulate OpPhi operands
7899 std::vector<spv::Id> phiOperands;
7900 // accumulate left operand's phi information
7901 phiOperands.push_back(leftId);
7902 phiOperands.push_back(builder.getBuildPoint()->getId());
7903
7904 // Make the two kinds of operation symmetric with a "!"
7905 // || => emit "if (! left) result = right"
7906 // && => emit "if ( left) result = right"
7907 //
7908 // TODO: this runtime "not" for || could be avoided by adding functionality
7909 // to 'builder' to have an "else" without an "then"
7910 if (op == glslang::EOpLogicalOr)
7911 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7912
7913 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007914 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007915
7916 // emit right operand as the "then" part of the "if"
7917 builder.clearAccessChain();
7918 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007919 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007920
7921 // accumulate left operand's phi information
7922 phiOperands.push_back(rightId);
7923 phiOperands.push_back(builder.getBuildPoint()->getId());
7924
7925 // finish the "if"
7926 ifBuilder.makeEndIf();
7927
7928 // phi together the two results
7929 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7930}
7931
Frank Henigman541f7bb2018-01-16 00:18:26 -05007932#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007933// Return type Id of the imported set of extended instructions corresponds to the name.
7934// Import this set if it has not been imported yet.
7935spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7936{
7937 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7938 return extBuiltinMap[name];
7939 else {
Rex Xu51596642016-09-21 18:56:12 +08007940 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007941 spv::Id extBuiltins = builder.import(name);
7942 extBuiltinMap[name] = extBuiltins;
7943 return extBuiltins;
7944 }
7945}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007946#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007947
John Kessenich140f3df2015-06-26 16:58:36 -06007948}; // end anonymous namespace
7949
7950namespace glslang {
7951
John Kessenich68d78fd2015-07-12 19:28:10 -06007952void GetSpirvVersion(std::string& version)
7953{
John Kessenich9e55f632015-07-15 10:03:39 -06007954 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007955 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007956 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007957 version = buf;
7958}
7959
John Kessenicha372a3e2017-11-02 22:32:14 -06007960// For low-order part of the generator's magic number. Bump up
7961// when there is a change in the style (e.g., if SSA form changes,
7962// or a different instruction sequence to do something gets used).
7963int GetSpirvGeneratorVersion()
7964{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007965 // return 1; // start
7966 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007967 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007968 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007969 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007970 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7971 // versions 4 and 6 each generate OpArrayLength as it has long been done
7972 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007973}
7974
John Kessenich140f3df2015-06-26 16:58:36 -06007975// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007976void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007977{
7978 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007979 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007980 if (out.fail())
7981 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007982 for (int i = 0; i < (int)spirv.size(); ++i) {
7983 unsigned int word = spirv[i];
7984 out.write((const char*)&word, 4);
7985 }
7986 out.close();
7987}
7988
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007989// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007990void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007991{
7992 std::ofstream out;
7993 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007994 if (out.fail())
7995 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007996 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007997 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007998 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007999 if (varName != nullptr) {
8000 out << "\t #pragma once" << std::endl;
8001 out << "const uint32_t " << varName << "[] = {" << std::endl;
8002 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008003 const int WORDS_PER_LINE = 8;
8004 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8005 out << "\t";
8006 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8007 const unsigned int word = spirv[i + j];
8008 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8009 if (i + j + 1 < (int)spirv.size()) {
8010 out << ",";
8011 }
8012 }
8013 out << std::endl;
8014 }
Flavio15017db2017-02-15 14:29:33 -08008015 if (varName != nullptr) {
8016 out << "};";
8017 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008018 out.close();
8019}
8020
John Kessenich140f3df2015-06-26 16:58:36 -06008021//
8022// Set up the glslang traversal
8023//
John Kessenich4e11b612018-08-30 16:56:59 -06008024void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008025{
Lei Zhang17535f72016-05-04 15:55:59 -04008026 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008027 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008028}
8029
John Kessenich4e11b612018-08-30 16:56:59 -06008030void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008031 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008032{
John Kessenich140f3df2015-06-26 16:58:36 -06008033 TIntermNode* root = intermediate.getTreeRoot();
8034
8035 if (root == 0)
8036 return;
8037
John Kessenich4e11b612018-08-30 16:56:59 -06008038 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008039 if (options == nullptr)
8040 options = &defaultOptions;
8041
John Kessenich4e11b612018-08-30 16:56:59 -06008042 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008043
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008044 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008045 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008046 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008047 it.dumpSpv(spirv);
8048
GregFfb03a552018-03-29 11:49:14 -06008049#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008050 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8051 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06008052 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06008053 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06008054
John Kessenich4e11b612018-08-30 16:56:59 -06008055 if (options->validate)
8056 SpirvToolsValidate(intermediate, spirv, logger);
8057
John Kessenich717c80a2018-08-23 15:17:10 -06008058 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008059 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008060
GregFcd1f1692017-09-21 18:40:22 -06008061#endif
8062
John Kessenich4e11b612018-08-30 16:56:59 -06008063 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008064}
8065
8066}; // end namespace glslang