blob: 312e06ade56f5955bcec081e541213e9d466f857 [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
Daniel Koch593a4e02019-05-27 16:46:31 -0400891 // ray tracing
Chao Chenb50c02e2018-09-19 11:42:24 -0700892 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;
Daniel Koch593a4e02019-05-27 16:46:31 -0400920
921 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700922 case glslang::EbvBaryCoordNV:
923 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
924 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
925 return spv::BuiltInBaryCoordNV;
926 case glslang::EbvBaryCoordNoPerspNV:
927 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
928 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
929 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400930
931 // mesh shaders
932 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700933 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400934 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700935 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400936 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700937 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400938 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700939 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400940 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700941 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400942 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700943 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400944 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700945 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400946 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700947 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400948#endif
Daniel Koch2cb2f192019-06-04 08:43:32 -0400949
950 // sm builtins
951 case glslang::EbvWarpsPerSM:
952 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
953 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
954 return spv::BuiltInWarpsPerSMNV;
955 case glslang::EbvSMCount:
956 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
957 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
958 return spv::BuiltInSMCountNV;
959 case glslang::EbvWarpID:
960 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
961 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
962 return spv::BuiltInWarpIDNV;
963 case glslang::EbvSMID:
964 builder.addExtension(spv::E_SPV_NV_shader_sm_builtins);
965 builder.addCapability(spv::CapabilityShaderSMBuiltinsNV);
966 return spv::BuiltInSMIDNV;
Rex Xu3e783f92017-02-22 16:44:48 +0800967 default:
968 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600969 }
970}
971
Rex Xufc618912015-09-09 16:42:49 +0800972// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700973spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800974{
975 assert(type.getBasicType() == glslang::EbtSampler);
976
John Kessenich5d0fa972016-02-15 11:57:00 -0700977 // Check for capabilities
978 switch (type.getQualifier().layoutFormat) {
979 case glslang::ElfRg32f:
980 case glslang::ElfRg16f:
981 case glslang::ElfR11fG11fB10f:
982 case glslang::ElfR16f:
983 case glslang::ElfRgba16:
984 case glslang::ElfRgb10A2:
985 case glslang::ElfRg16:
986 case glslang::ElfRg8:
987 case glslang::ElfR16:
988 case glslang::ElfR8:
989 case glslang::ElfRgba16Snorm:
990 case glslang::ElfRg16Snorm:
991 case glslang::ElfRg8Snorm:
992 case glslang::ElfR16Snorm:
993 case glslang::ElfR8Snorm:
994
995 case glslang::ElfRg32i:
996 case glslang::ElfRg16i:
997 case glslang::ElfRg8i:
998 case glslang::ElfR16i:
999 case glslang::ElfR8i:
1000
1001 case glslang::ElfRgb10a2ui:
1002 case glslang::ElfRg32ui:
1003 case glslang::ElfRg16ui:
1004 case glslang::ElfRg8ui:
1005 case glslang::ElfR16ui:
1006 case glslang::ElfR8ui:
1007 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
1008 break;
1009
1010 default:
1011 break;
1012 }
1013
1014 // do the translation
Rex Xufc618912015-09-09 16:42:49 +08001015 switch (type.getQualifier().layoutFormat) {
1016 case glslang::ElfNone: return spv::ImageFormatUnknown;
1017 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1018 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1019 case glslang::ElfR32f: return spv::ImageFormatR32f;
1020 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1021 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1022 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1023 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1024 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1025 case glslang::ElfR16f: return spv::ImageFormatR16f;
1026 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1027 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1028 case glslang::ElfRg16: return spv::ImageFormatRg16;
1029 case glslang::ElfRg8: return spv::ImageFormatRg8;
1030 case glslang::ElfR16: return spv::ImageFormatR16;
1031 case glslang::ElfR8: return spv::ImageFormatR8;
1032 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1033 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1034 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1035 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1036 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1037 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1038 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1039 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1040 case glslang::ElfR32i: return spv::ImageFormatR32i;
1041 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1042 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1043 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1044 case glslang::ElfR16i: return spv::ImageFormatR16i;
1045 case glslang::ElfR8i: return spv::ImageFormatR8i;
1046 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1047 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1048 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1049 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1050 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1051 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1052 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1053 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1054 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1055 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001056 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001057 }
1058}
1059
John Kesseniche18fd202018-01-30 11:01:39 -07001060spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001061{
John Kesseniche18fd202018-01-30 11:01:39 -07001062 if (selectionNode.getFlatten())
1063 return spv::SelectionControlFlattenMask;
1064 if (selectionNode.getDontFlatten())
1065 return spv::SelectionControlDontFlattenMask;
1066 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001067}
1068
John Kesseniche18fd202018-01-30 11:01:39 -07001069spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001070{
John Kesseniche18fd202018-01-30 11:01:39 -07001071 if (switchNode.getFlatten())
1072 return spv::SelectionControlFlattenMask;
1073 if (switchNode.getDontFlatten())
1074 return spv::SelectionControlDontFlattenMask;
1075 return spv::SelectionControlMaskNone;
1076}
1077
John Kessenicha2858d92018-01-31 08:11:18 -07001078// return a non-0 dependency if the dependency argument must be set
1079spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001080 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001081{
1082 spv::LoopControlMask control = spv::LoopControlMaskNone;
1083
1084 if (loopNode.getDontUnroll())
1085 control = control | spv::LoopControlDontUnrollMask;
1086 if (loopNode.getUnroll())
1087 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001088 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001089 control = control | spv::LoopControlDependencyInfiniteMask;
1090 else if (loopNode.getLoopDependency() > 0) {
1091 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001092 operands.push_back((unsigned int)loopNode.getLoopDependency());
1093 }
1094 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1095 if (loopNode.getMinIterations() > 0) {
1096 control = control | spv::LoopControlMinIterationsMask;
1097 operands.push_back(loopNode.getMinIterations());
1098 }
1099 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1100 control = control | spv::LoopControlMaxIterationsMask;
1101 operands.push_back(loopNode.getMaxIterations());
1102 }
1103 if (loopNode.getIterationMultiple() > 1) {
1104 control = control | spv::LoopControlIterationMultipleMask;
1105 operands.push_back(loopNode.getIterationMultiple());
1106 }
1107 if (loopNode.getPeelCount() > 0) {
1108 control = control | spv::LoopControlPeelCountMask;
1109 operands.push_back(loopNode.getPeelCount());
1110 }
1111 if (loopNode.getPartialCount() > 0) {
1112 control = control | spv::LoopControlPartialCountMask;
1113 operands.push_back(loopNode.getPartialCount());
1114 }
John Kessenicha2858d92018-01-31 08:11:18 -07001115 }
John Kesseniche18fd202018-01-30 11:01:39 -07001116
1117 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001118}
1119
John Kessenicha5c5fb62017-05-05 05:09:58 -06001120// Translate glslang type to SPIR-V storage class.
1121spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1122{
1123 if (type.getQualifier().isPipeInput())
1124 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001125 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001126 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001127
1128 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1129 type.getQualifier().storage == glslang::EvqUniform) {
1130 if (type.getBasicType() == glslang::EbtAtomicUint)
1131 return spv::StorageClassAtomicCounter;
1132 if (type.containsOpaque())
1133 return spv::StorageClassUniformConstant;
1134 }
1135
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001136#ifdef NV_EXTENSIONS
1137 if (type.getQualifier().isUniformOrBuffer() &&
1138 type.getQualifier().layoutShaderRecordNV) {
1139 return spv::StorageClassShaderRecordBufferNV;
1140 }
1141#endif
1142
John Kessenichbed4e4f2017-09-08 02:38:07 -06001143 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001144 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001145 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001146 }
1147
1148 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001149 if (type.getQualifier().layoutPushConstant)
1150 return spv::StorageClassPushConstant;
1151 if (type.getBasicType() == glslang::EbtBlock)
1152 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001153 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001154 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001155
1156 switch (type.getQualifier().storage) {
1157 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1158 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1159 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1160 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001161#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001162 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1163 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1164 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1165 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1166 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001167#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001168 default:
1169 assert(0);
1170 break;
1171 }
1172
1173 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001174}
1175
John Kessenich5611c6d2018-04-05 11:25:02 -06001176// Add capabilities pertaining to how an array is indexed.
1177void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1178 const glslang::TType& indexType)
1179{
1180 if (indexType.getQualifier().isNonUniform()) {
1181 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001182 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001183 if (baseType.getBasicType() == glslang::EbtSampler) {
1184 if (baseType.getQualifier().hasAttachment())
1185 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1186 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1187 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1188 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1189 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1190 else if (baseType.isImage())
1191 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1192 else if (baseType.isTexture())
1193 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1194 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1195 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1196 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1197 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1198 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1199 }
1200 } else {
1201 // assume a dynamically uniform index
1202 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001203 if (baseType.getQualifier().hasAttachment()) {
1204 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001205 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001206 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1207 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001208 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001209 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1210 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001211 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001212 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001213 }
1214 }
1215}
1216
qining25262b32016-05-06 17:25:16 -04001217// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001218// descriptor set.
1219bool IsDescriptorResource(const glslang::TType& type)
1220{
John Kessenichf7497e22016-03-08 21:36:22 -07001221 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001222 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001223 return type.getQualifier().isUniformOrBuffer() &&
1224#ifdef NV_EXTENSIONS
1225 ! type.getQualifier().layoutShaderRecordNV &&
1226#endif
1227 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001228
1229 // non block...
1230 // basically samplerXXX/subpass/sampler/texture are all included
1231 // if they are the global-scope-class, not the function parameter
1232 // (or local, if they ever exist) class.
1233 if (type.getBasicType() == glslang::EbtSampler)
1234 return type.getQualifier().isUniformOrBuffer();
1235
1236 // None of the above.
1237 return false;
1238}
1239
John Kesseniche0b6cad2015-12-24 10:30:13 -07001240void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1241{
1242 if (child.layoutMatrix == glslang::ElmNone)
1243 child.layoutMatrix = parent.layoutMatrix;
1244
1245 if (parent.invariant)
1246 child.invariant = true;
1247 if (parent.nopersp)
1248 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001249#ifdef AMD_EXTENSIONS
1250 if (parent.explicitInterp)
1251 child.explicitInterp = true;
1252#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001253 if (parent.flat)
1254 child.flat = true;
1255 if (parent.centroid)
1256 child.centroid = true;
1257 if (parent.patch)
1258 child.patch = true;
1259 if (parent.sample)
1260 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001261 if (parent.coherent)
1262 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001263 if (parent.devicecoherent)
1264 child.devicecoherent = true;
1265 if (parent.queuefamilycoherent)
1266 child.queuefamilycoherent = true;
1267 if (parent.workgroupcoherent)
1268 child.workgroupcoherent = true;
1269 if (parent.subgroupcoherent)
1270 child.subgroupcoherent = true;
1271 if (parent.nonprivate)
1272 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001273 if (parent.volatil)
1274 child.volatil = true;
1275 if (parent.restrict)
1276 child.restrict = true;
1277 if (parent.readonly)
1278 child.readonly = true;
1279 if (parent.writeonly)
1280 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001281#ifdef NV_EXTENSIONS
1282 if (parent.perPrimitiveNV)
1283 child.perPrimitiveNV = true;
1284 if (parent.perViewNV)
1285 child.perViewNV = true;
1286 if (parent.perTaskNV)
1287 child.perTaskNV = true;
1288#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001289}
1290
John Kessenichf2b7f332016-09-01 17:05:23 -06001291bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001292{
John Kessenich7b9fa252016-01-21 18:56:57 -07001293 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001294 // - struct members might inherit from a struct declaration
1295 // (note that non-block structs don't explicitly inherit,
1296 // only implicitly, meaning no decoration involved)
1297 // - affect decorations on the struct members
1298 // (note smooth does not, and expecting something like volatile
1299 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001300 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001301 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001302}
1303
John Kessenich140f3df2015-06-26 16:58:36 -06001304//
1305// Implement the TGlslangToSpvTraverser class.
1306//
1307
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001308TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001309 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1310 : TIntermTraverser(true, false, true),
1311 options(options),
1312 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001313 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001314 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001315 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001316 glslangIntermediate(glslangIntermediate)
1317{
1318 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1319
1320 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001321 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1322 glslangIntermediate->getVersion());
1323
John Kessenich121853f2017-05-31 17:11:16 -06001324 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001325 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001326 builder.setSourceFile(glslangIntermediate->getSourceFile());
1327
1328 // Set the source shader's text. If for SPV version 1.0, include
1329 // a preamble in comments stating the OpModuleProcessed instructions.
1330 // Otherwise, emit those as actual instructions.
1331 std::string text;
1332 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1333 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001334 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001335 text.append("// OpModuleProcessed ");
1336 text.append(processes[p]);
1337 text.append("\n");
1338 } else
1339 builder.addModuleProcessed(processes[p]);
1340 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001341 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001342 text.append("#line 1\n");
1343 text.append(glslangIntermediate->getSourceText());
1344 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001345 // Pass name and text for all included files
1346 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1347 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1348 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001349 }
John Kessenich140f3df2015-06-26 16:58:36 -06001350 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001351
1352 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1353 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1354
1355 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1356 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1357 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1358 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1359 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001360 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001361 memoryModel = spv::MemoryModelVulkanKHR;
1362 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001363 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001364 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001365 builder.setMemoryModel(addressingModel, memoryModel);
1366
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001367 if (glslangIntermediate->usingVariablePointers()) {
1368 builder.addCapability(spv::CapabilityVariablePointers);
1369 }
1370
John Kessenicheee9d532016-09-19 18:09:30 -06001371 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1372 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001373
1374 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001375 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1376 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001377 builder.addSourceExtension(it->c_str());
1378
1379 // Add the top-level modes for this shader.
1380
John Kessenich92187592016-02-01 13:45:25 -07001381 if (glslangIntermediate->getXfbMode()) {
1382 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001383 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001384 }
John Kessenich140f3df2015-06-26 16:58:36 -06001385
1386 unsigned int mode;
1387 switch (glslangIntermediate->getStage()) {
1388 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001389 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001390 break;
1391
steve-lunarge7412492017-03-23 11:56:07 -06001392 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001393 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001394 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001395
steve-lunarge7412492017-03-23 11:56:07 -06001396 glslang::TLayoutGeometry primitive;
1397
1398 if (glslangIntermediate->getStage() == EShLangTessControl) {
1399 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1400 primitive = glslangIntermediate->getOutputPrimitive();
1401 } else {
1402 primitive = glslangIntermediate->getInputPrimitive();
1403 }
1404
1405 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001406 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1407 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1408 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001409 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001410 }
John Kessenich4016e382016-07-15 11:53:56 -06001411 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001412 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1413
John Kesseniche6903322015-10-13 16:29:02 -06001414 switch (glslangIntermediate->getVertexSpacing()) {
1415 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1416 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1417 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001418 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001419 }
John Kessenich4016e382016-07-15 11:53:56 -06001420 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001421 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1422
1423 switch (glslangIntermediate->getVertexOrder()) {
1424 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1425 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001426 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001427 }
John Kessenich4016e382016-07-15 11:53:56 -06001428 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001429 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1430
1431 if (glslangIntermediate->getPointMode())
1432 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001433 break;
1434
1435 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001436 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001437 switch (glslangIntermediate->getInputPrimitive()) {
1438 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1439 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1440 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001441 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001442 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001443 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001444 }
John Kessenich4016e382016-07-15 11:53:56 -06001445 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001446 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001447
John Kessenich140f3df2015-06-26 16:58:36 -06001448 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1449
1450 switch (glslangIntermediate->getOutputPrimitive()) {
1451 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1452 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1453 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001454 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001455 }
John Kessenich4016e382016-07-15 11:53:56 -06001456 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001457 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1458 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1459 break;
1460
1461 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001462 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001463 if (glslangIntermediate->getPixelCenterInteger())
1464 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001465
John Kessenich140f3df2015-06-26 16:58:36 -06001466 if (glslangIntermediate->getOriginUpperLeft())
1467 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001468 else
1469 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001470
1471 if (glslangIntermediate->getEarlyFragmentTests())
1472 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1473
chaocc1204522017-06-30 17:14:30 -07001474 if (glslangIntermediate->getPostDepthCoverage()) {
1475 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1476 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1477 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1478 }
1479
John Kesseniche6903322015-10-13 16:29:02 -06001480 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001481 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1482 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001483 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001484 }
John Kessenich4016e382016-07-15 11:53:56 -06001485 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001486 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1487
1488 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1489 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05001490
1491 switch (glslangIntermediate->getInterlockOrdering()) {
1492 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT; break;
1493 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT; break;
1494 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT; break;
1495 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT; break;
1496 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT; break;
1497 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT; break;
1498 default: mode = spv::ExecutionModeMax; break;
1499 }
1500 if (mode != spv::ExecutionModeMax) {
1501 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1502 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1503 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1504 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1505 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1506 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1507 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1508 } else {
1509 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1510 }
1511 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1512 }
1513
John Kessenich140f3df2015-06-26 16:58:36 -06001514 break;
1515
1516 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001517 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001518 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1519 glslangIntermediate->getLocalSize(1),
1520 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001521#ifdef NV_EXTENSIONS
1522 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1523 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1524 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1525 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1526 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1527 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1528 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1529 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1530 }
1531#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001532 break;
1533
Chao Chen3c366992018-09-19 11:41:59 -07001534#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001535 case EShLangRayGenNV:
1536 case EShLangIntersectNV:
1537 case EShLangAnyHitNV:
1538 case EShLangClosestHitNV:
1539 case EShLangMissNV:
1540 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001541 builder.addCapability(spv::CapabilityRayTracingNV);
1542 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001543 break;
Chao Chen3c366992018-09-19 11:41:59 -07001544 case EShLangTaskNV:
1545 case EShLangMeshNV:
1546 builder.addCapability(spv::CapabilityMeshShadingNV);
1547 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1548 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1549 glslangIntermediate->getLocalSize(1),
1550 glslangIntermediate->getLocalSize(2));
1551 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1552 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1553 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1554
1555 switch (glslangIntermediate->getOutputPrimitive()) {
1556 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1557 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1558 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1559 default: mode = spv::ExecutionModeMax; break;
1560 }
1561 if (mode != spv::ExecutionModeMax)
1562 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1563 }
1564 break;
1565#endif
1566
John Kessenich140f3df2015-06-26 16:58:36 -06001567 default:
1568 break;
1569 }
John Kessenich140f3df2015-06-26 16:58:36 -06001570}
1571
John Kessenichfca82622016-11-26 13:23:20 -07001572// Finish creating SPV, after the traversal is complete.
1573void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001574{
John Kessenichf04c51b2018-08-03 15:56:12 -06001575 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001576 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001577 builder.setBuildPoint(shaderEntry->getLastBlock());
1578 builder.leaveFunction();
1579 }
1580
John Kessenich7ba63412015-12-20 17:37:07 -07001581 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001582 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1583 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001584
John Kessenichf04c51b2018-08-03 15:56:12 -06001585 // Add capabilities, extensions, remove unneeded decorations, etc.,
1586 // based on the resulting SPIR-V.
1587 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001588}
1589
John Kessenichfca82622016-11-26 13:23:20 -07001590// Write the SPV into 'out'.
1591void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001592{
John Kessenichfca82622016-11-26 13:23:20 -07001593 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001594}
1595
1596//
1597// Implement the traversal functions.
1598//
1599// Return true from interior nodes to have the external traversal
1600// continue on to children. Return false if children were
1601// already processed.
1602//
1603
1604//
qining25262b32016-05-06 17:25:16 -04001605// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001606// - uniform/input reads
1607// - output writes
1608// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1609// - something simple that degenerates into the last bullet
1610//
1611void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1612{
qining75d1d802016-04-06 14:42:01 -04001613 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1614 if (symbol->getType().getQualifier().isSpecConstant())
1615 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1616
John Kessenich140f3df2015-06-26 16:58:36 -06001617 // getSymbolId() will set up all the IO decorations on the first call.
1618 // Formal function parameters were mapped during makeFunctions().
1619 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001620
1621 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1622 if (builder.isPointer(id)) {
John Kessenich7c7731e2019-01-04 16:47:06 +07001623 // Consider adding to the OpEntryPoint interface list.
1624 // Only looking at structures if they have at least one member.
1625 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1626 spv::StorageClass sc = builder.getStorageClass(id);
1627 // Before SPIR-V 1.4, we only want to include Input and Output.
1628 // Starting with SPIR-V 1.4, we want all globals.
1629 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1630 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001631 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001632 }
John Kessenich5f77d862017-09-19 11:09:59 -06001633 }
John Kessenich7ba63412015-12-20 17:37:07 -07001634 }
1635
1636 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001637 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001638 // Prepare to generate code for the access
1639
1640 // L-value chains will be computed left to right. We're on the symbol now,
1641 // which is the left-most part of the access chain, so now is "clear" time,
1642 // followed by setting the base.
1643 builder.clearAccessChain();
1644
1645 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001646 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001647 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001648 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001649 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001650 // These are also pure R-values.
1651 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001652 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001653 builder.setAccessChainRValue(id);
1654 else
1655 builder.setAccessChainLValue(id);
1656 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001657
1658 // Process linkage-only nodes for any special additional interface work.
1659 if (linkageOnly) {
1660 if (glslangIntermediate->getHlslFunctionality1()) {
1661 // Map implicit counter buffers to their originating buffers, which should have been
1662 // seen by now, given earlier pruning of unused counters, and preservation of order
1663 // of declaration.
1664 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1665 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1666 // Save possible originating buffers for counter buffers, keyed by
1667 // making the potential counter-buffer name.
1668 std::string keyName = symbol->getName().c_str();
1669 keyName = glslangIntermediate->addCounterBufferName(keyName);
1670 counterOriginator[keyName] = symbol;
1671 } else {
1672 // Handle a counter buffer, by finding the saved originating buffer.
1673 std::string keyName = symbol->getName().c_str();
1674 auto it = counterOriginator.find(keyName);
1675 if (it != counterOriginator.end()) {
1676 id = getSymbolId(it->second);
1677 if (id != spv::NoResult) {
1678 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001679 if (counterId != spv::NoResult) {
1680 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001681 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001682 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001683 }
1684 }
1685 }
1686 }
1687 }
1688 }
John Kessenich140f3df2015-06-26 16:58:36 -06001689}
1690
1691bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1692{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001693 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001694
qining40887662016-04-03 22:20:42 -04001695 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1696 if (node->getType().getQualifier().isSpecConstant())
1697 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1698
John Kessenich140f3df2015-06-26 16:58:36 -06001699 // First, handle special cases
1700 switch (node->getOp()) {
1701 case glslang::EOpAssign:
1702 case glslang::EOpAddAssign:
1703 case glslang::EOpSubAssign:
1704 case glslang::EOpMulAssign:
1705 case glslang::EOpVectorTimesMatrixAssign:
1706 case glslang::EOpVectorTimesScalarAssign:
1707 case glslang::EOpMatrixTimesScalarAssign:
1708 case glslang::EOpMatrixTimesMatrixAssign:
1709 case glslang::EOpDivAssign:
1710 case glslang::EOpModAssign:
1711 case glslang::EOpAndAssign:
1712 case glslang::EOpInclusiveOrAssign:
1713 case glslang::EOpExclusiveOrAssign:
1714 case glslang::EOpLeftShiftAssign:
1715 case glslang::EOpRightShiftAssign:
1716 // A bin-op assign "a += b" means the same thing as "a = a + b"
1717 // where a is evaluated before b. For a simple assignment, GLSL
1718 // says to evaluate the left before the right. So, always, left
1719 // node then right node.
1720 {
1721 // get the left l-value, save it away
1722 builder.clearAccessChain();
1723 node->getLeft()->traverse(this);
1724 spv::Builder::AccessChain lValue = builder.getAccessChain();
1725
1726 // evaluate the right
1727 builder.clearAccessChain();
1728 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001729 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001730
1731 if (node->getOp() != glslang::EOpAssign) {
1732 // the left is also an r-value
1733 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001734 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001735
1736 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001737 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001738 TranslateNoContractionDecoration(node->getType().getQualifier()),
1739 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001740 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001741 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1742 node->getType().getBasicType());
1743
1744 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001745 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001746 }
1747
1748 // store the result
1749 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001750 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001751
1752 // assignments are expressions having an rValue after they are evaluated...
1753 builder.clearAccessChain();
1754 builder.setAccessChainRValue(rValue);
1755 }
1756 return false;
1757 case glslang::EOpIndexDirect:
1758 case glslang::EOpIndexDirectStruct:
1759 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001760 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001761 // Get the left part of the access chain.
1762 node->getLeft()->traverse(this);
1763
1764 // Add the next element in the chain
1765
David Netoa901ffe2016-06-08 14:11:40 +01001766 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001767 if (! node->getLeft()->getType().isArray() &&
1768 node->getLeft()->getType().isVector() &&
1769 node->getOp() == glslang::EOpIndexDirect) {
1770 // This is essentially a hard-coded vector swizzle of size 1,
1771 // so short circuit the access-chain stuff with a swizzle.
1772 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001773 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001774 int dummySize;
1775 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1776 TranslateCoherent(node->getLeft()->getType()),
1777 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001778 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001779
1780 // Load through a block reference is performed with a dot operator that
1781 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1782 // do a load and reset the access chain.
1783 if (node->getLeft()->getBasicType() == glslang::EbtReference &&
1784 !node->getLeft()->getType().isArray() &&
1785 node->getOp() == glslang::EOpIndexDirectStruct)
1786 {
1787 spv::Id left = accessChainLoad(node->getLeft()->getType());
1788 builder.clearAccessChain();
1789 builder.setAccessChainLValue(left);
1790 }
1791
David Netoa901ffe2016-06-08 14:11:40 +01001792 int spvIndex = glslangIndex;
1793 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1794 node->getOp() == glslang::EOpIndexDirectStruct)
1795 {
1796 // This may be, e.g., an anonymous block-member selection, which generally need
1797 // index remapping due to hidden members in anonymous blocks.
1798 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1799 assert(remapper.size() > 0);
1800 spvIndex = remapper[glslangIndex];
1801 }
John Kessenichebb50532016-05-16 19:22:05 -06001802
David Netoa901ffe2016-06-08 14:11:40 +01001803 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001804 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001805
1806 // Add capabilities here for accessing PointSize and clip/cull distance.
1807 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001808 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001809 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001810 }
1811 }
1812 return false;
1813 case glslang::EOpIndexIndirect:
1814 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001815 // Array, matrix, or vector indirection with variable index.
1816 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001817 // matrices are arrays of vectors, so will also work for a matrix.
1818 // Will use the access chain's 'component' for variable index into a vector.
1819
1820 // This adapter is building access chains left to right.
1821 // Set up the access chain to the left.
1822 node->getLeft()->traverse(this);
1823
1824 // save it so that computing the right side doesn't trash it
1825 spv::Builder::AccessChain partial = builder.getAccessChain();
1826
1827 // compute the next index in the chain
1828 builder.clearAccessChain();
1829 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001830 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001831
John Kessenich5611c6d2018-04-05 11:25:02 -06001832 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1833
John Kessenich140f3df2015-06-26 16:58:36 -06001834 // restore the saved access chain
1835 builder.setAccessChain(partial);
1836
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001837 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1838 int dummySize;
1839 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1840 TranslateCoherent(node->getLeft()->getType()),
1841 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1842 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001843 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001844 }
1845 return false;
1846 case glslang::EOpVectorSwizzle:
1847 {
1848 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001849 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001850 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001851 int dummySize;
1852 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1853 TranslateCoherent(node->getLeft()->getType()),
1854 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001855 }
1856 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001857 case glslang::EOpMatrixSwizzle:
1858 logger->missingFunctionality("matrix swizzle");
1859 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001860 case glslang::EOpLogicalOr:
1861 case glslang::EOpLogicalAnd:
1862 {
1863
1864 // These may require short circuiting, but can sometimes be done as straight
1865 // binary operations. The right operand must be short circuited if it has
1866 // side effects, and should probably be if it is complex.
1867 if (isTrivial(node->getRight()->getAsTyped()))
1868 break; // handle below as a normal binary operation
1869 // otherwise, we need to do dynamic short circuiting on the right operand
1870 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1871 builder.clearAccessChain();
1872 builder.setAccessChainRValue(result);
1873 }
1874 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001875 default:
1876 break;
1877 }
1878
1879 // Assume generic binary op...
1880
John Kessenich32cfd492016-02-02 12:37:46 -07001881 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001882 builder.clearAccessChain();
1883 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001884 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001885
John Kessenich32cfd492016-02-02 12:37:46 -07001886 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001887 builder.clearAccessChain();
1888 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001889 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001890
John Kessenich32cfd492016-02-02 12:37:46 -07001891 // get result
John Kessenichead86222018-03-28 18:01:20 -06001892 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001893 TranslateNoContractionDecoration(node->getType().getQualifier()),
1894 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001895 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001896 convertGlslangToSpvType(node->getType()), left, right,
1897 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001898
John Kessenich50e57562015-12-21 21:21:11 -07001899 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001900 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001901 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001902 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001903 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001904 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001905 return false;
1906 }
John Kessenich140f3df2015-06-26 16:58:36 -06001907}
1908
1909bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1910{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001911 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001912
qining40887662016-04-03 22:20:42 -04001913 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1914 if (node->getType().getQualifier().isSpecConstant())
1915 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1916
John Kessenichfc51d282015-08-19 13:34:18 -06001917 spv::Id result = spv::NoResult;
1918
1919 // try texturing first
1920 result = createImageTextureFunctionCall(node);
1921 if (result != spv::NoResult) {
1922 builder.clearAccessChain();
1923 builder.setAccessChainRValue(result);
1924
1925 return false; // done with this node
1926 }
1927
1928 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001929
1930 if (node->getOp() == glslang::EOpArrayLength) {
1931 // Quite special; won't want to evaluate the operand.
1932
John Kessenich5611c6d2018-04-05 11:25:02 -06001933 // Currently, the front-end does not allow .length() on an array until it is sized,
1934 // except for the last block membeor of an SSBO.
1935 // TODO: If this changes, link-time sized arrays might show up here, and need their
1936 // size extracted.
1937
John Kessenichc9a80832015-09-12 12:17:44 -06001938 // Normal .length() would have been constant folded by the front-end.
1939 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001940 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001941
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001942 spv::Id length;
1943 if (node->getOperand()->getType().isCoopMat()) {
1944 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1945
1946 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
1947 assert(builder.isCooperativeMatrixType(typeId));
1948
1949 length = builder.createCooperativeMatrixLength(typeId);
1950 } else {
1951 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1952 block->traverse(this);
1953 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1954 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
1955 }
John Kessenichc9a80832015-09-12 12:17:44 -06001956
John Kessenich8c869672018-11-28 07:01:37 -07001957 // GLSL semantics say the result of .length() is an int, while SPIR-V says
1958 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
1959 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001960 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
1961 if (builder.isInSpecConstCodeGenMode()) {
1962 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
1963 } else {
1964 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
1965 }
1966 }
John Kessenich8c869672018-11-28 07:01:37 -07001967
John Kessenichc9a80832015-09-12 12:17:44 -06001968 builder.clearAccessChain();
1969 builder.setAccessChainRValue(length);
1970
1971 return false;
1972 }
1973
John Kessenichfc51d282015-08-19 13:34:18 -06001974 // Start by evaluating the operand
1975
John Kessenich8c8505c2016-07-26 12:50:38 -06001976 // Does it need a swizzle inversion? If so, evaluation is inverted;
1977 // operate first on the swizzle base, then apply the swizzle.
1978 spv::Id invertedType = spv::NoType;
1979 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1980 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1981 invertedType = getInvertedSwizzleType(*node->getOperand());
1982
John Kessenich140f3df2015-06-26 16:58:36 -06001983 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001984 if (invertedType != spv::NoType)
1985 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1986 else
1987 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001988
Rex Xufc618912015-09-09 16:42:49 +08001989 spv::Id operand = spv::NoResult;
1990
1991 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1992 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001993 node->getOp() == glslang::EOpAtomicCounter ||
1994 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001995 operand = builder.accessChainGetLValue(); // Special case l-value operands
1996 else
John Kessenich32cfd492016-02-02 12:37:46 -07001997 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001998
John Kessenichead86222018-03-28 18:01:20 -06001999 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06002000 TranslateNoContractionDecoration(node->getType().getQualifier()),
2001 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06002002
2003 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06002004 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06002005 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002006
2007 // if not, then possibly an operation
2008 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06002009 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06002010
2011 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06002012 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06002013 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06002014 builder.addDecoration(result, decorations.nonUniform);
2015 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002016
John Kessenich140f3df2015-06-26 16:58:36 -06002017 builder.clearAccessChain();
2018 builder.setAccessChainRValue(result);
2019
2020 return false; // done with this node
2021 }
2022
2023 // it must be a special case, check...
2024 switch (node->getOp()) {
2025 case glslang::EOpPostIncrement:
2026 case glslang::EOpPostDecrement:
2027 case glslang::EOpPreIncrement:
2028 case glslang::EOpPreDecrement:
2029 {
2030 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002031 spv::Id one = 0;
2032 if (node->getBasicType() == glslang::EbtFloat)
2033 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08002034 else if (node->getBasicType() == glslang::EbtDouble)
2035 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002036 else if (node->getBasicType() == glslang::EbtFloat16)
2037 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002038 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2039 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002040 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2041 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002042 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2043 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08002044 else
2045 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002046 glslang::TOperator op;
2047 if (node->getOp() == glslang::EOpPreIncrement ||
2048 node->getOp() == glslang::EOpPostIncrement)
2049 op = glslang::EOpAdd;
2050 else
2051 op = glslang::EOpSub;
2052
John Kessenichead86222018-03-28 18:01:20 -06002053 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002054 convertGlslangToSpvType(node->getType()), operand, one,
2055 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002056 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002057
2058 // The result of operation is always stored, but conditionally the
2059 // consumed result. The consumed result is always an r-value.
2060 builder.accessChainStore(result);
2061 builder.clearAccessChain();
2062 if (node->getOp() == glslang::EOpPreIncrement ||
2063 node->getOp() == glslang::EOpPreDecrement)
2064 builder.setAccessChainRValue(result);
2065 else
2066 builder.setAccessChainRValue(operand);
2067 }
2068
2069 return false;
2070
2071 case glslang::EOpEmitStreamVertex:
2072 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2073 return false;
2074 case glslang::EOpEndStreamPrimitive:
2075 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2076 return false;
2077
2078 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002079 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002080 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002081 }
John Kessenich140f3df2015-06-26 16:58:36 -06002082}
2083
2084bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2085{
qining27e04a02016-04-14 16:40:20 -04002086 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2087 if (node->getType().getQualifier().isSpecConstant())
2088 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2089
John Kessenichfc51d282015-08-19 13:34:18 -06002090 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002091 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2092 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002093
2094 // try texturing
2095 result = createImageTextureFunctionCall(node);
2096 if (result != spv::NoResult) {
2097 builder.clearAccessChain();
2098 builder.setAccessChainRValue(result);
2099
2100 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05002101 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08002102#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05002103 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08002104#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05002105 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002106 // "imageStore" is a special case, which has no result
2107 return false;
2108 }
John Kessenichfc51d282015-08-19 13:34:18 -06002109
John Kessenich140f3df2015-06-26 16:58:36 -06002110 glslang::TOperator binOp = glslang::EOpNull;
2111 bool reduceComparison = true;
2112 bool isMatrix = false;
2113 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002114 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002115
2116 assert(node->getOp());
2117
John Kessenichf6640762016-08-01 19:44:00 -06002118 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002119
2120 switch (node->getOp()) {
2121 case glslang::EOpSequence:
2122 {
2123 if (preVisit)
2124 ++sequenceDepth;
2125 else
2126 --sequenceDepth;
2127
2128 if (sequenceDepth == 1) {
2129 // If this is the parent node of all the functions, we want to see them
2130 // early, so all call points have actual SPIR-V functions to reference.
2131 // In all cases, still let the traverser visit the children for us.
2132 makeFunctions(node->getAsAggregate()->getSequence());
2133
John Kessenich6fccb3c2016-09-19 16:01:41 -06002134 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002135 // anything else gets there, so visit out of order, doing them all now.
2136 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2137
John Kessenich6a60c2f2016-12-08 21:01:59 -07002138 // 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 -06002139 // so do them manually.
2140 visitFunctions(node->getAsAggregate()->getSequence());
2141
2142 return false;
2143 }
2144
2145 return true;
2146 }
2147 case glslang::EOpLinkerObjects:
2148 {
2149 if (visit == glslang::EvPreVisit)
2150 linkageOnly = true;
2151 else
2152 linkageOnly = false;
2153
2154 return true;
2155 }
2156 case glslang::EOpComma:
2157 {
2158 // processing from left to right naturally leaves the right-most
2159 // lying around in the access chain
2160 glslang::TIntermSequence& glslangOperands = node->getSequence();
2161 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2162 glslangOperands[i]->traverse(this);
2163
2164 return false;
2165 }
2166 case glslang::EOpFunction:
2167 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002168 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002169 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002170 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002171 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002172 } else {
2173 handleFunctionEntry(node);
2174 }
2175 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002176 if (inEntryPoint)
2177 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002178 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002179 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002180 }
2181
2182 return true;
2183 case glslang::EOpParameters:
2184 // Parameters will have been consumed by EOpFunction processing, but not
2185 // the body, so we still visited the function node's children, making this
2186 // child redundant.
2187 return false;
2188 case glslang::EOpFunctionCall:
2189 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002190 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002191 if (node->isUserDefined())
2192 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002193 // 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 -07002194 if (result) {
2195 builder.clearAccessChain();
2196 builder.setAccessChainRValue(result);
2197 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002198 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002199
2200 return false;
2201 }
2202 case glslang::EOpConstructMat2x2:
2203 case glslang::EOpConstructMat2x3:
2204 case glslang::EOpConstructMat2x4:
2205 case glslang::EOpConstructMat3x2:
2206 case glslang::EOpConstructMat3x3:
2207 case glslang::EOpConstructMat3x4:
2208 case glslang::EOpConstructMat4x2:
2209 case glslang::EOpConstructMat4x3:
2210 case glslang::EOpConstructMat4x4:
2211 case glslang::EOpConstructDMat2x2:
2212 case glslang::EOpConstructDMat2x3:
2213 case glslang::EOpConstructDMat2x4:
2214 case glslang::EOpConstructDMat3x2:
2215 case glslang::EOpConstructDMat3x3:
2216 case glslang::EOpConstructDMat3x4:
2217 case glslang::EOpConstructDMat4x2:
2218 case glslang::EOpConstructDMat4x3:
2219 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002220 case glslang::EOpConstructIMat2x2:
2221 case glslang::EOpConstructIMat2x3:
2222 case glslang::EOpConstructIMat2x4:
2223 case glslang::EOpConstructIMat3x2:
2224 case glslang::EOpConstructIMat3x3:
2225 case glslang::EOpConstructIMat3x4:
2226 case glslang::EOpConstructIMat4x2:
2227 case glslang::EOpConstructIMat4x3:
2228 case glslang::EOpConstructIMat4x4:
2229 case glslang::EOpConstructUMat2x2:
2230 case glslang::EOpConstructUMat2x3:
2231 case glslang::EOpConstructUMat2x4:
2232 case glslang::EOpConstructUMat3x2:
2233 case glslang::EOpConstructUMat3x3:
2234 case glslang::EOpConstructUMat3x4:
2235 case glslang::EOpConstructUMat4x2:
2236 case glslang::EOpConstructUMat4x3:
2237 case glslang::EOpConstructUMat4x4:
2238 case glslang::EOpConstructBMat2x2:
2239 case glslang::EOpConstructBMat2x3:
2240 case glslang::EOpConstructBMat2x4:
2241 case glslang::EOpConstructBMat3x2:
2242 case glslang::EOpConstructBMat3x3:
2243 case glslang::EOpConstructBMat3x4:
2244 case glslang::EOpConstructBMat4x2:
2245 case glslang::EOpConstructBMat4x3:
2246 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002247 case glslang::EOpConstructF16Mat2x2:
2248 case glslang::EOpConstructF16Mat2x3:
2249 case glslang::EOpConstructF16Mat2x4:
2250 case glslang::EOpConstructF16Mat3x2:
2251 case glslang::EOpConstructF16Mat3x3:
2252 case glslang::EOpConstructF16Mat3x4:
2253 case glslang::EOpConstructF16Mat4x2:
2254 case glslang::EOpConstructF16Mat4x3:
2255 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002256 isMatrix = true;
2257 // fall through
2258 case glslang::EOpConstructFloat:
2259 case glslang::EOpConstructVec2:
2260 case glslang::EOpConstructVec3:
2261 case glslang::EOpConstructVec4:
2262 case glslang::EOpConstructDouble:
2263 case glslang::EOpConstructDVec2:
2264 case glslang::EOpConstructDVec3:
2265 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002266 case glslang::EOpConstructFloat16:
2267 case glslang::EOpConstructF16Vec2:
2268 case glslang::EOpConstructF16Vec3:
2269 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002270 case glslang::EOpConstructBool:
2271 case glslang::EOpConstructBVec2:
2272 case glslang::EOpConstructBVec3:
2273 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002274 case glslang::EOpConstructInt8:
2275 case glslang::EOpConstructI8Vec2:
2276 case glslang::EOpConstructI8Vec3:
2277 case glslang::EOpConstructI8Vec4:
2278 case glslang::EOpConstructUint8:
2279 case glslang::EOpConstructU8Vec2:
2280 case glslang::EOpConstructU8Vec3:
2281 case glslang::EOpConstructU8Vec4:
2282 case glslang::EOpConstructInt16:
2283 case glslang::EOpConstructI16Vec2:
2284 case glslang::EOpConstructI16Vec3:
2285 case glslang::EOpConstructI16Vec4:
2286 case glslang::EOpConstructUint16:
2287 case glslang::EOpConstructU16Vec2:
2288 case glslang::EOpConstructU16Vec3:
2289 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002290 case glslang::EOpConstructInt:
2291 case glslang::EOpConstructIVec2:
2292 case glslang::EOpConstructIVec3:
2293 case glslang::EOpConstructIVec4:
2294 case glslang::EOpConstructUint:
2295 case glslang::EOpConstructUVec2:
2296 case glslang::EOpConstructUVec3:
2297 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002298 case glslang::EOpConstructInt64:
2299 case glslang::EOpConstructI64Vec2:
2300 case glslang::EOpConstructI64Vec3:
2301 case glslang::EOpConstructI64Vec4:
2302 case glslang::EOpConstructUint64:
2303 case glslang::EOpConstructU64Vec2:
2304 case glslang::EOpConstructU64Vec3:
2305 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002306 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002307 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002308 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002309 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002310 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002311 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002312 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002313 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002314 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002315 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002316 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002317 else if (node->getOp() == glslang::EOpConstructStruct ||
2318 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2319 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002320 std::vector<spv::Id> constituents;
2321 for (int c = 0; c < (int)arguments.size(); ++c)
2322 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002323 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002324 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002325 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002326 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002327 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002328
2329 builder.clearAccessChain();
2330 builder.setAccessChainRValue(constructed);
2331
2332 return false;
2333 }
2334
2335 // These six are component-wise compares with component-wise results.
2336 // Forward on to createBinaryOperation(), requesting a vector result.
2337 case glslang::EOpLessThan:
2338 case glslang::EOpGreaterThan:
2339 case glslang::EOpLessThanEqual:
2340 case glslang::EOpGreaterThanEqual:
2341 case glslang::EOpVectorEqual:
2342 case glslang::EOpVectorNotEqual:
2343 {
2344 // Map the operation to a binary
2345 binOp = node->getOp();
2346 reduceComparison = false;
2347 switch (node->getOp()) {
2348 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2349 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2350 default: binOp = node->getOp(); break;
2351 }
2352
2353 break;
2354 }
2355 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002356 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002357 binOp = glslang::EOpMul;
2358 break;
2359 case glslang::EOpOuterProduct:
2360 // two vectors multiplied to make a matrix
2361 binOp = glslang::EOpOuterProduct;
2362 break;
2363 case glslang::EOpDot:
2364 {
qining25262b32016-05-06 17:25:16 -04002365 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002366 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002367 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002368 binOp = glslang::EOpMul;
2369 break;
2370 }
2371 case glslang::EOpMod:
2372 // when an aggregate, this is the floating-point mod built-in function,
2373 // which can be emitted by the one in createBinaryOperation()
2374 binOp = glslang::EOpMod;
2375 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002376 case glslang::EOpEmitVertex:
2377 case glslang::EOpEndPrimitive:
2378 case glslang::EOpBarrier:
2379 case glslang::EOpMemoryBarrier:
2380 case glslang::EOpMemoryBarrierAtomicCounter:
2381 case glslang::EOpMemoryBarrierBuffer:
2382 case glslang::EOpMemoryBarrierImage:
2383 case glslang::EOpMemoryBarrierShared:
2384 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002385 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002386 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002387 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002388 case glslang::EOpWorkgroupMemoryBarrier:
2389 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002390 case glslang::EOpSubgroupBarrier:
2391 case glslang::EOpSubgroupMemoryBarrier:
2392 case glslang::EOpSubgroupMemoryBarrierBuffer:
2393 case glslang::EOpSubgroupMemoryBarrierImage:
2394 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002395 noReturnValue = true;
2396 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2397 break;
2398
Jeff Bolz36831c92018-09-05 10:11:41 -05002399 case glslang::EOpAtomicStore:
2400 noReturnValue = true;
2401 // fallthrough
2402 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002403 case glslang::EOpAtomicAdd:
2404 case glslang::EOpAtomicMin:
2405 case glslang::EOpAtomicMax:
2406 case glslang::EOpAtomicAnd:
2407 case glslang::EOpAtomicOr:
2408 case glslang::EOpAtomicXor:
2409 case glslang::EOpAtomicExchange:
2410 case glslang::EOpAtomicCompSwap:
2411 atomic = true;
2412 break;
2413
John Kessenich0d0c6d32017-07-23 16:08:26 -06002414 case glslang::EOpAtomicCounterAdd:
2415 case glslang::EOpAtomicCounterSubtract:
2416 case glslang::EOpAtomicCounterMin:
2417 case glslang::EOpAtomicCounterMax:
2418 case glslang::EOpAtomicCounterAnd:
2419 case glslang::EOpAtomicCounterOr:
2420 case glslang::EOpAtomicCounterXor:
2421 case glslang::EOpAtomicCounterExchange:
2422 case glslang::EOpAtomicCounterCompSwap:
2423 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2424 builder.addCapability(spv::CapabilityAtomicStorageOps);
2425 atomic = true;
2426 break;
2427
Chao Chen3c366992018-09-19 11:41:59 -07002428#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002429 case glslang::EOpIgnoreIntersectionNV:
2430 case glslang::EOpTerminateRayNV:
2431 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002432 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002433 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2434 noReturnValue = true;
2435 break;
2436#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002437 case glslang::EOpCooperativeMatrixLoad:
2438 case glslang::EOpCooperativeMatrixStore:
2439 noReturnValue = true;
2440 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002441 case glslang::EOpBeginInvocationInterlock:
2442 case glslang::EOpEndInvocationInterlock:
2443 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2444 noReturnValue = true;
2445 break;
Chao Chen3c366992018-09-19 11:41:59 -07002446
John Kessenich140f3df2015-06-26 16:58:36 -06002447 default:
2448 break;
2449 }
2450
2451 //
2452 // See if it maps to a regular operation.
2453 //
John Kessenich140f3df2015-06-26 16:58:36 -06002454 if (binOp != glslang::EOpNull) {
2455 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2456 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2457 assert(left && right);
2458
2459 builder.clearAccessChain();
2460 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002461 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002462
2463 builder.clearAccessChain();
2464 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002465 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002466
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002467 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002468 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002469 TranslateNoContractionDecoration(node->getType().getQualifier()),
2470 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002471 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002472 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002473 left->getType().getBasicType(), reduceComparison);
2474
2475 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002476 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002477 builder.clearAccessChain();
2478 builder.setAccessChainRValue(result);
2479
2480 return false;
2481 }
2482
John Kessenich426394d2015-07-23 10:22:48 -06002483 //
2484 // Create the list of operands.
2485 //
John Kessenich140f3df2015-06-26 16:58:36 -06002486 glslang::TIntermSequence& glslangOperands = node->getSequence();
2487 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002488 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002489 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002490 // special case l-value operands; there are just a few
2491 bool lvalue = false;
2492 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002493 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002494 case glslang::EOpModf:
2495 if (arg == 1)
2496 lvalue = true;
2497 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002498 case glslang::EOpInterpolateAtSample:
2499 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002500#ifdef AMD_EXTENSIONS
2501 case glslang::EOpInterpolateAtVertex:
2502#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002503 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002504 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002505
2506 // Does it need a swizzle inversion? If so, evaluation is inverted;
2507 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002508 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002509 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2510 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2511 }
Rex Xu7a26c172015-12-08 17:12:09 +08002512 break;
Rex Xud4782c12015-09-06 16:30:11 +08002513 case glslang::EOpAtomicAdd:
2514 case glslang::EOpAtomicMin:
2515 case glslang::EOpAtomicMax:
2516 case glslang::EOpAtomicAnd:
2517 case glslang::EOpAtomicOr:
2518 case glslang::EOpAtomicXor:
2519 case glslang::EOpAtomicExchange:
2520 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002521 case glslang::EOpAtomicLoad:
2522 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002523 case glslang::EOpAtomicCounterAdd:
2524 case glslang::EOpAtomicCounterSubtract:
2525 case glslang::EOpAtomicCounterMin:
2526 case glslang::EOpAtomicCounterMax:
2527 case glslang::EOpAtomicCounterAnd:
2528 case glslang::EOpAtomicCounterOr:
2529 case glslang::EOpAtomicCounterXor:
2530 case glslang::EOpAtomicCounterExchange:
2531 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002532 if (arg == 0)
2533 lvalue = true;
2534 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002535 case glslang::EOpAddCarry:
2536 case glslang::EOpSubBorrow:
2537 if (arg == 2)
2538 lvalue = true;
2539 break;
2540 case glslang::EOpUMulExtended:
2541 case glslang::EOpIMulExtended:
2542 if (arg >= 2)
2543 lvalue = true;
2544 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002545 case glslang::EOpCooperativeMatrixLoad:
2546 if (arg == 0 || arg == 1)
2547 lvalue = true;
2548 break;
2549 case glslang::EOpCooperativeMatrixStore:
2550 if (arg == 1)
2551 lvalue = true;
2552 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002553 default:
2554 break;
2555 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002556 builder.clearAccessChain();
2557 if (invertedType != spv::NoType && arg == 0)
2558 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2559 else
2560 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002561
2562 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2563 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2564
2565 if (arg == 1) {
2566 // fold "element" parameter into the access chain
2567 spv::Builder::AccessChain save = builder.getAccessChain();
2568 builder.clearAccessChain();
2569 glslangOperands[2]->traverse(this);
2570
2571 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2572
2573 builder.setAccessChain(save);
2574
2575 // Point to the first element of the array.
2576 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002577 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002578
2579 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2580 unsigned int alignment = builder.getAccessChain().alignment;
2581
2582 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2583 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2584 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2585 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2586 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2587 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2588 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2589 }
2590
2591 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2592
2593 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2594 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2595 }
2596
2597 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2598 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2599 }
2600 } else if (arg == 2) {
2601 continue;
2602 }
2603 }
2604
John Kessenich140f3df2015-06-26 16:58:36 -06002605 if (lvalue)
2606 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002607 else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002608 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002609 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002610 }
John Kessenich140f3df2015-06-26 16:58:36 -06002611 }
John Kessenich426394d2015-07-23 10:22:48 -06002612
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002613 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002614 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2615 std::vector<spv::IdImmediate> idImmOps;
2616
2617 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2618 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2619 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2620 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2621 // get the pointee type
2622 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2623 assert(builder.isCooperativeMatrixType(typeId));
2624 // do the op
2625 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2626 // store the result to the pointer (out param 'm')
2627 builder.createStore(result, operands[0]);
2628 result = 0;
2629 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2630 std::vector<spv::IdImmediate> idImmOps;
2631
2632 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2633 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2634 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2635 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2636 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2637
2638 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2639 result = 0;
2640 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002641 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002642 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002643 } else {
2644 // Pass through to generic operations.
2645 switch (glslangOperands.size()) {
2646 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002647 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002648 break;
2649 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002650 {
2651 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002652 TranslateNoContractionDecoration(node->getType().getQualifier()),
2653 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002654 result = createUnaryOperation(
2655 node->getOp(), decorations,
2656 resultType(), operands.front(),
2657 glslangOperands[0]->getAsTyped()->getBasicType());
2658 }
John Kessenich426394d2015-07-23 10:22:48 -06002659 break;
2660 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002661 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002662 break;
2663 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002664 if (invertedType)
2665 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002666 }
2667
2668 if (noReturnValue)
2669 return false;
2670
2671 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002672 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002673 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002674 } else {
2675 builder.clearAccessChain();
2676 builder.setAccessChainRValue(result);
2677 return false;
2678 }
2679}
2680
John Kessenich433e9ff2017-01-26 20:31:11 -07002681// This path handles both if-then-else and ?:
2682// The if-then-else has a node type of void, while
2683// ?: has either a void or a non-void node type
2684//
2685// Leaving the result, when not void:
2686// GLSL only has r-values as the result of a :?, but
2687// if we have an l-value, that can be more efficient if it will
2688// become the base of a complex r-value expression, because the
2689// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002690bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2691{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002692 // see if OpSelect can handle it
2693 const auto isOpSelectable = [&]() {
2694 if (node->getBasicType() == glslang::EbtVoid)
2695 return false;
2696 // OpSelect can do all other types starting with SPV 1.4
2697 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2698 // pre-1.4, only scalars and vectors can be handled
2699 if ((!node->getType().isScalar() && !node->getType().isVector()))
2700 return false;
2701 }
2702 return true;
2703 };
2704
John Kessenich4bee5312018-02-20 21:29:05 -07002705 // See if it simple and safe, or required, to execute both sides.
2706 // Crucially, side effects must be either semantically required or avoided,
2707 // and there are performance trade-offs.
2708 // Return true if required or a good idea (and safe) to execute both sides,
2709 // false otherwise.
2710 const auto bothSidesPolicy = [&]() -> bool {
2711 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002712 if (node->getTrueBlock() == nullptr ||
2713 node->getFalseBlock() == nullptr)
2714 return false;
2715
John Kessenich4bee5312018-02-20 21:29:05 -07002716 // required? (unless we write additional code to look for side effects
2717 // and make performance trade-offs if none are present)
2718 if (!node->getShortCircuit())
2719 return true;
2720
2721 // if not required to execute both, decide based on performance/practicality...
2722
John Kessenich0c1e71a2019-01-10 18:23:06 +07002723 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002724 return false;
2725
John Kessenich433e9ff2017-01-26 20:31:11 -07002726 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2727 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2728
2729 // return true if a single operand to ? : is okay for OpSelect
2730 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002731 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002732 };
2733
2734 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2735 operandOkay(node->getFalseBlock()->getAsTyped());
2736 };
2737
John Kessenich4bee5312018-02-20 21:29:05 -07002738 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2739 // emit the condition before doing anything with selection
2740 node->getCondition()->traverse(this);
2741 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2742
2743 // Find a way of executing both sides and selecting the right result.
2744 const auto executeBothSides = [&]() -> void {
2745 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002746 node->getTrueBlock()->traverse(this);
2747 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2748 node->getFalseBlock()->traverse(this);
2749 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2750
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002751 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002752
John Kessenich4bee5312018-02-20 21:29:05 -07002753 // done if void
2754 if (node->getBasicType() == glslang::EbtVoid)
2755 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002756
John Kessenich4bee5312018-02-20 21:29:05 -07002757 // emit code to select between trueValue and falseValue
2758
2759 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002760 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002761 // Emit OpSelect for this selection.
2762
2763 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002764 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2765 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002766 condition = builder.smearScalar(spv::NoPrecision, condition,
2767 builder.makeVectorType(builder.makeBoolType(),
2768 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002769 }
John Kessenich4bee5312018-02-20 21:29:05 -07002770
2771 // OpSelect
2772 result = builder.createTriOp(spv::OpSelect,
2773 convertGlslangToSpvType(node->getType()), condition,
2774 trueValue, falseValue);
2775
2776 builder.clearAccessChain();
2777 builder.setAccessChainRValue(result);
2778 } else {
2779 // We need control flow to select the result.
2780 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2781 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2782
2783 // Selection control:
2784 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2785
2786 // make an "if" based on the value created by the condition
2787 spv::Builder::If ifBuilder(condition, control, builder);
2788
2789 // emit the "then" statement
2790 builder.createStore(trueValue, result);
2791 ifBuilder.makeBeginElse();
2792 // emit the "else" statement
2793 builder.createStore(falseValue, result);
2794
2795 // finish off the control flow
2796 ifBuilder.makeEndIf();
2797
2798 builder.clearAccessChain();
2799 builder.setAccessChainLValue(result);
2800 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002801 };
2802
John Kessenich4bee5312018-02-20 21:29:05 -07002803 // Execute the one side needed, as per the condition
2804 const auto executeOneSide = [&]() {
2805 // Always emit control flow.
2806 if (node->getBasicType() != glslang::EbtVoid)
2807 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002808
John Kessenich4bee5312018-02-20 21:29:05 -07002809 // Selection control:
2810 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2811
2812 // make an "if" based on the value created by the condition
2813 spv::Builder::If ifBuilder(condition, control, builder);
2814
2815 // emit the "then" statement
2816 if (node->getTrueBlock() != nullptr) {
2817 node->getTrueBlock()->traverse(this);
2818 if (result != spv::NoResult)
2819 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2820 }
2821
2822 if (node->getFalseBlock() != nullptr) {
2823 ifBuilder.makeBeginElse();
2824 // emit the "else" statement
2825 node->getFalseBlock()->traverse(this);
2826 if (result != spv::NoResult)
2827 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2828 }
2829
2830 // finish off the control flow
2831 ifBuilder.makeEndIf();
2832
2833 if (result != spv::NoResult) {
2834 builder.clearAccessChain();
2835 builder.setAccessChainLValue(result);
2836 }
2837 };
2838
2839 // Try for OpSelect (or a requirement to execute both sides)
2840 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002841 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2842 if (node->getType().getQualifier().isSpecConstant())
2843 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002844 executeBothSides();
2845 } else
2846 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002847
2848 return false;
2849}
2850
2851bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2852{
2853 // emit and get the condition before doing anything with switch
2854 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002855 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002856
Rex Xu57e65922017-07-04 23:23:40 +08002857 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002858 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002859
John Kessenich140f3df2015-06-26 16:58:36 -06002860 // browse the children to sort out code segments
2861 int defaultSegment = -1;
2862 std::vector<TIntermNode*> codeSegments;
2863 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2864 std::vector<int> caseValues;
2865 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2866 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2867 TIntermNode* child = *c;
2868 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002869 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002870 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002871 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002872 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2873 } else
2874 codeSegments.push_back(child);
2875 }
2876
qining25262b32016-05-06 17:25:16 -04002877 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002878 // statements between the last case and the end of the switch statement
2879 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2880 (int)codeSegments.size() == defaultSegment)
2881 codeSegments.push_back(nullptr);
2882
2883 // make the switch statement
2884 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002885 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002886
2887 // emit all the code in the segments
2888 breakForLoop.push(false);
2889 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2890 builder.nextSwitchSegment(segmentBlocks, s);
2891 if (codeSegments[s])
2892 codeSegments[s]->traverse(this);
2893 else
2894 builder.addSwitchBreak();
2895 }
2896 breakForLoop.pop();
2897
2898 builder.endSwitch(segmentBlocks);
2899
2900 return false;
2901}
2902
2903void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2904{
2905 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002906 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002907
2908 builder.clearAccessChain();
2909 builder.setAccessChainRValue(constant);
2910}
2911
2912bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2913{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002914 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002915 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002916
2917 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07002918 std::vector<unsigned int> operands;
2919 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06002920
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002921 // Spec requires back edges to target header blocks, and every header block
2922 // must dominate its merge block. Make a header block first to ensure these
2923 // conditions are met. By definition, it will contain OpLoopMerge, followed
2924 // by a block-ending branch. But we don't want to put any other body/test
2925 // instructions in it, since the body/test may have arbitrary instructions,
2926 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002927 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002928 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07002929 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002930 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002931 spv::Block& test = builder.makeNewBlock();
2932 builder.createBranch(&test);
2933
2934 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002935 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002936 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002937 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2938
2939 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002940 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002941 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002942 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002943 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002944 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002945
2946 builder.setBuildPoint(&blocks.continue_target);
2947 if (node->getTerminal())
2948 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002949 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002950 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002951 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002952 builder.createBranch(&blocks.body);
2953
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002954 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002955 builder.setBuildPoint(&blocks.body);
2956 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002957 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002958 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002959 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002960
2961 builder.setBuildPoint(&blocks.continue_target);
2962 if (node->getTerminal())
2963 node->getTerminal()->traverse(this);
2964 if (node->getTest()) {
2965 node->getTest()->traverse(this);
2966 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002967 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002968 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002969 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002970 // TODO: unless there was a break/return/discard instruction
2971 // somewhere in the body, this is an infinite loop, so we should
2972 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002973 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002974 }
John Kessenich140f3df2015-06-26 16:58:36 -06002975 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002976 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002977 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002978 return false;
2979}
2980
2981bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2982{
2983 if (node->getExpression())
2984 node->getExpression()->traverse(this);
2985
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002986 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002987
John Kessenich140f3df2015-06-26 16:58:36 -06002988 switch (node->getFlowOp()) {
2989 case glslang::EOpKill:
2990 builder.makeDiscard();
2991 break;
2992 case glslang::EOpBreak:
2993 if (breakForLoop.top())
2994 builder.createLoopExit();
2995 else
2996 builder.addSwitchBreak();
2997 break;
2998 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002999 builder.createLoopContinue();
3000 break;
3001 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06003002 if (node->getExpression()) {
3003 const glslang::TType& glslangReturnType = node->getExpression()->getType();
3004 spv::Id returnId = accessChainLoad(glslangReturnType);
3005 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
3006 builder.clearAccessChain();
3007 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
3008 builder.setAccessChainLValue(copyId);
3009 multiTypeStore(glslangReturnType, returnId);
3010 returnId = builder.createLoad(copyId);
3011 }
3012 builder.makeReturn(false, returnId);
3013 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06003014 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06003015
3016 builder.clearAccessChain();
3017 break;
3018
3019 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003020 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003021 break;
3022 }
3023
3024 return false;
3025}
3026
3027spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
3028{
qining25262b32016-05-06 17:25:16 -04003029 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003030 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003031 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003032 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003033 spv::Id result = createSpvConstant(*node);
3034 if (result != spv::NoResult)
3035 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003036 }
3037
3038 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003039 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003040 spv::Id spvType = convertGlslangToSpvType(node->getType());
3041
Rex Xucabbb782017-03-24 13:41:14 +08003042 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
3043 node->getType().containsBasicType(glslang::EbtInt16) ||
3044 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08003045 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003046 switch (storageClass) {
3047 case spv::StorageClassInput:
3048 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07003049 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003050 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003051 break;
3052 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07003053 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003054 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06003055 break;
3056 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003057 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003058 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3059 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003060 else
3061 builder.addCapability(spv::CapabilityStorageUniform16);
3062 break;
3063 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003064 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003065 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3066 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3067 break;
3068 default:
3069 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003070 }
3071 }
Rex Xuf89ad982017-04-07 23:22:33 +08003072
John Kessenich312dcfb2018-07-03 13:19:51 -06003073 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3074 node->getType().containsBasicType(glslang::EbtUint8);
3075 if (contains8BitType) {
3076 if (storageClass == spv::StorageClassPushConstant) {
3077 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3078 builder.addCapability(spv::CapabilityStoragePushConstant8);
3079 } else if (storageClass == spv::StorageClassUniform) {
3080 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3081 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003082 } else if (storageClass == spv::StorageClassStorageBuffer) {
3083 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3084 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
John Kessenich312dcfb2018-07-03 13:19:51 -06003085 }
3086 }
3087
John Kessenich140f3df2015-06-26 16:58:36 -06003088 const char* name = node->getName().c_str();
3089 if (glslang::IsAnonymous(name))
3090 name = "";
3091
3092 return builder.createVariable(storageClass, spvType, name);
3093}
3094
3095// Return type Id of the sampled type.
3096spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3097{
3098 switch (sampler.type) {
3099 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003100#ifdef AMD_EXTENSIONS
3101 case glslang::EbtFloat16:
3102 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3103 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3104 return builder.makeFloatType(16);
3105#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003106 case glslang::EbtInt: return builder.makeIntType(32);
3107 case glslang::EbtUint: return builder.makeUintType(32);
3108 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003109 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003110 return builder.makeFloatType(32);
3111 }
3112}
3113
John Kessenich8c8505c2016-07-26 12:50:38 -06003114// If node is a swizzle operation, return the type that should be used if
3115// the swizzle base is first consumed by another operation, before the swizzle
3116// is applied.
3117spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3118{
John Kessenichecba76f2017-01-06 00:34:48 -07003119 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003120 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3121 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3122 else
3123 return spv::NoType;
3124}
3125
3126// When inverting a swizzle with a parent op, this function
3127// will apply the swizzle operation to a completed parent operation.
3128spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3129{
3130 std::vector<unsigned> swizzle;
3131 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3132 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3133}
3134
John Kessenich8c8505c2016-07-26 12:50:38 -06003135// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3136void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3137{
3138 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3139 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3140 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3141}
3142
John Kessenich3ac051e2015-12-20 11:29:16 -07003143// Convert from a glslang type to an SPV type, by calling into a
3144// recursive version of this function. This establishes the inherited
3145// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003146spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003147{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003148 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003149}
3150
3151// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003152// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003153// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003154spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003155 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3156 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003157{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003158 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003159
3160 switch (type.getBasicType()) {
3161 case glslang::EbtVoid:
3162 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003163 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003164 break;
3165 case glslang::EbtFloat:
3166 spvType = builder.makeFloatType(32);
3167 break;
3168 case glslang::EbtDouble:
3169 spvType = builder.makeFloatType(64);
3170 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003171 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003172 spvType = builder.makeFloatType(16);
3173 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003174 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003175 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3176 // a 32-bit int where non-0 means true.
3177 if (explicitLayout != glslang::ElpNone)
3178 spvType = builder.makeUintType(32);
3179 else
3180 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003181 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003182 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003183 spvType = builder.makeIntType(8);
3184 break;
3185 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003186 spvType = builder.makeUintType(8);
3187 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003188 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003189 spvType = builder.makeIntType(16);
3190 break;
3191 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003192 spvType = builder.makeUintType(16);
3193 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003194 case glslang::EbtInt:
3195 spvType = builder.makeIntType(32);
3196 break;
3197 case glslang::EbtUint:
3198 spvType = builder.makeUintType(32);
3199 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003200 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003201 spvType = builder.makeIntType(64);
3202 break;
3203 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003204 spvType = builder.makeUintType(64);
3205 break;
John Kessenich426394d2015-07-23 10:22:48 -06003206 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003207 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003208 spvType = builder.makeUintType(32);
3209 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003210#ifdef NV_EXTENSIONS
3211 case glslang::EbtAccStructNV:
3212 spvType = builder.makeAccelerationStructureNVType();
3213 break;
3214#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003215 case glslang::EbtSampler:
3216 {
3217 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003218 if (sampler.sampler) {
3219 // pure sampler
3220 spvType = builder.makeSamplerType();
3221 } else {
3222 // an image is present, make its type
3223 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3224 sampler.image ? 2 : 1, TranslateImageFormat(type));
3225 if (sampler.combined) {
3226 // already has both image and sampler, make the combined type
3227 spvType = builder.makeSampledImageType(spvType);
3228 }
John Kessenich55e7d112015-11-15 21:33:39 -07003229 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003230 }
John Kessenich140f3df2015-06-26 16:58:36 -06003231 break;
3232 case glslang::EbtStruct:
3233 case glslang::EbtBlock:
3234 {
3235 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003236 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003237
3238 // Try to share structs for different layouts, but not yet for other
3239 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003240 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003241 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003242 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003243 break;
3244
3245 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003246 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003247 memberRemapper[glslangMembers].resize(glslangMembers->size());
3248 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003249 }
3250 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003251 case glslang::EbtReference:
3252 {
3253 // Make the forward pointer, then recurse to convert the structure type, then
3254 // patch up the forward pointer with a real pointer type.
3255 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3256 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3257 forwardPointers[type.getReferentType()] = forwardId;
3258 }
3259 spvType = forwardPointers[type.getReferentType()];
3260 if (!forwardReferenceOnly) {
3261 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3262 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3263 forwardPointers[type.getReferentType()],
3264 referentType);
3265 }
3266 }
3267 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003268 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003269 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003270 break;
3271 }
3272
3273 if (type.isMatrix())
3274 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3275 else {
3276 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3277 if (type.getVectorSize() > 1)
3278 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3279 }
3280
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003281 if (type.isCoopMat()) {
3282 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3283 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3284 if (type.getBasicType() == glslang::EbtFloat16)
3285 builder.addCapability(spv::CapabilityFloat16);
3286
3287 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3288 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3289 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3290
3291 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3292 }
3293
John Kessenich140f3df2015-06-26 16:58:36 -06003294 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003295 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3296
John Kessenichc9a80832015-09-12 12:17:44 -06003297 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003298 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003299 // We need to decorate array strides for types needing explicit layout, except blocks.
3300 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003301 // Use a dummy glslang type for querying internal strides of
3302 // arrays of arrays, but using just a one-dimensional array.
3303 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003304 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3305 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003306
3307 // Will compute the higher-order strides here, rather than making a whole
3308 // pile of types and doing repetitive recursion on their contents.
3309 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3310 }
John Kessenichf8842e52016-01-04 19:22:56 -07003311
3312 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003313 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003314 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003315 if (stride > 0)
3316 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003317 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003318 }
3319 } else {
3320 // single-dimensional array, and don't yet have stride
3321
John Kessenichf8842e52016-01-04 19:22:56 -07003322 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003323 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3324 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003325 }
John Kessenich31ed4832015-09-09 17:51:38 -06003326
John Kessenichead86222018-03-28 18:01:20 -06003327 // Do the outer dimension, which might not be known for a runtime-sized array.
3328 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3329 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003330 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003331 else {
3332 if (!lastBufferBlockMember) {
3333 builder.addExtension("SPV_EXT_descriptor_indexing");
3334 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3335 }
John Kessenichead86222018-03-28 18:01:20 -06003336 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003337 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003338 if (stride > 0)
3339 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003340 }
3341
3342 return spvType;
3343}
3344
John Kessenich0e737842017-03-24 18:38:16 -06003345// TODO: this functionality should exist at a higher level, in creating the AST
3346//
3347// Identify interface members that don't have their required extension turned on.
3348//
3349bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3350{
Chao Chen3c366992018-09-19 11:41:59 -07003351#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003352 auto& extensions = glslangIntermediate->getRequestedExtensions();
3353
Rex Xubcf291a2017-03-29 23:01:36 +08003354 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3355 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3356 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003357 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3358 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3359 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003360
3361 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3362 if (member.getFieldName() == "gl_ViewportMask" &&
3363 extensions.find("GL_NV_viewport_array2") == extensions.end())
3364 return true;
3365 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3366 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3367 return true;
3368 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3369 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3370 return true;
3371 }
3372#endif
John Kessenich0e737842017-03-24 18:38:16 -06003373
3374 return false;
3375};
3376
John Kessenich6090df02016-06-30 21:18:02 -06003377// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3378// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3379// Mutually recursive with convertGlslangToSpvType().
3380spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3381 const glslang::TTypeList* glslangMembers,
3382 glslang::TLayoutPacking explicitLayout,
3383 const glslang::TQualifier& qualifier)
3384{
3385 // Create a vector of struct types for SPIR-V to consume
3386 std::vector<spv::Id> spvMembers;
3387 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 -06003388 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003389 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3390 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3391 if (glslangMember.hiddenMember()) {
3392 ++memberDelta;
3393 if (type.getBasicType() == glslang::EbtBlock)
3394 memberRemapper[glslangMembers][i] = -1;
3395 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003396 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003397 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003398 if (filterMember(glslangMember))
3399 continue;
3400 }
John Kessenich6090df02016-06-30 21:18:02 -06003401 // modify just this child's view of the qualifier
3402 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3403 InheritQualifiers(memberQualifier, qualifier);
3404
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003405 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003406 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003407 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003408
3409 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003410 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3411 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003412
3413 // Make forward pointers for any pointer members, and create a list of members to
3414 // convert to spirv types after creating the struct.
3415 if (glslangMember.getBasicType() == glslang::EbtReference) {
3416 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3417 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3418 }
3419 spvMembers.push_back(
3420 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3421 } else {
3422 spvMembers.push_back(
3423 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3424 }
John Kessenich6090df02016-06-30 21:18:02 -06003425 }
3426 }
3427
3428 // Make the SPIR-V type
3429 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003430 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003431 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3432
3433 // Decorate it
3434 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3435
John Kessenichd72f4882019-01-16 14:55:37 +07003436 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003437 auto it = deferredForwardPointers[i];
3438 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3439 }
3440
John Kessenich6090df02016-06-30 21:18:02 -06003441 return spvType;
3442}
3443
3444void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3445 const glslang::TTypeList* glslangMembers,
3446 glslang::TLayoutPacking explicitLayout,
3447 const glslang::TQualifier& qualifier,
3448 spv::Id spvType)
3449{
3450 // Name and decorate the non-hidden members
3451 int offset = -1;
3452 int locationOffset = 0; // for use within the members of this struct
3453 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3454 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3455 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003456 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003457 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003458 if (filterMember(glslangMember))
3459 continue;
3460 }
John Kessenich6090df02016-06-30 21:18:02 -06003461
3462 // modify just this child's view of the qualifier
3463 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3464 InheritQualifiers(memberQualifier, qualifier);
3465
3466 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003467 if (member < 0)
3468 continue;
3469
3470 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3471 builder.addMemberDecoration(spvType, member,
3472 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3473 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3474 // Add interpolation and auxiliary storage decorations only to
3475 // top-level members of Input and Output storage classes
3476 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3477 type.getQualifier().storage == glslang::EvqVaryingOut) {
3478 if (type.getBasicType() == glslang::EbtBlock ||
3479 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3480 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3481 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003482#ifdef NV_EXTENSIONS
3483 addMeshNVDecoration(spvType, member, memberQualifier);
3484#endif
John Kessenich6090df02016-06-30 21:18:02 -06003485 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003486 }
3487 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003488
John Kessenich5d610ee2018-03-07 18:05:55 -07003489 if (type.getBasicType() == glslang::EbtBlock &&
3490 qualifier.storage == glslang::EvqBuffer) {
3491 // Add memory decorations only to top-level members of shader storage block
3492 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003493 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003494 for (unsigned int i = 0; i < memory.size(); ++i)
3495 builder.addMemberDecoration(spvType, member, memory[i]);
3496 }
John Kessenich6090df02016-06-30 21:18:02 -06003497
John Kessenich5d610ee2018-03-07 18:05:55 -07003498 // Location assignment was already completed correctly by the front end,
3499 // just track whether a member needs to be decorated.
3500 // Ignore member locations if the container is an array, as that's
3501 // ill-specified and decisions have been made to not allow this.
3502 if (! type.isArray() && memberQualifier.hasLocation())
3503 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003504
John Kessenich5d610ee2018-03-07 18:05:55 -07003505 if (qualifier.hasLocation()) // track for upcoming inheritance
3506 locationOffset += glslangIntermediate->computeTypeLocationSize(
3507 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003508
John Kessenich5d610ee2018-03-07 18:05:55 -07003509 // component, XFB, others
3510 if (glslangMember.getQualifier().hasComponent())
3511 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3512 glslangMember.getQualifier().layoutComponent);
3513 if (glslangMember.getQualifier().hasXfbOffset())
3514 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3515 glslangMember.getQualifier().layoutXfbOffset);
3516 else if (explicitLayout != glslang::ElpNone) {
3517 // figure out what to do with offset, which is accumulating
3518 int nextOffset;
3519 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3520 if (offset >= 0)
3521 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3522 offset = nextOffset;
3523 }
John Kessenich6090df02016-06-30 21:18:02 -06003524
John Kessenich5d610ee2018-03-07 18:05:55 -07003525 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3526 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3527 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003528
John Kessenich5d610ee2018-03-07 18:05:55 -07003529 // built-in variable decorations
3530 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3531 if (builtIn != spv::BuiltInMax)
3532 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003533
John Kessenich5611c6d2018-04-05 11:25:02 -06003534 // nonuniform
3535 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3536
John Kessenichead86222018-03-28 18:01:20 -06003537 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3538 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3539 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3540 memberQualifier.semanticName);
3541 }
3542
chaoc771d89f2017-01-13 01:10:53 -08003543#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003544 if (builtIn == spv::BuiltInLayer) {
3545 // SPV_NV_viewport_array2 extension
3546 if (glslangMember.getQualifier().layoutViewportRelative){
3547 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3548 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3549 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003550 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003551 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3552 builder.addMemberDecoration(spvType, member,
3553 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3554 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3555 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3556 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003557 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003558 }
3559 if (glslangMember.getQualifier().layoutPassthrough) {
3560 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3561 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3562 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3563 }
chaoc771d89f2017-01-13 01:10:53 -08003564#endif
John Kessenich6090df02016-06-30 21:18:02 -06003565 }
3566
3567 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003568 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3569 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003570}
3571
John Kessenich6c292d32016-02-15 20:58:50 -07003572// Turn the expression forming the array size into an id.
3573// This is not quite trivial, because of specialization constants.
3574// Sometimes, a raw constant is turned into an Id, and sometimes
3575// a specialization constant expression is.
3576spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3577{
3578 // First, see if this is sized with a node, meaning a specialization constant:
3579 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3580 if (specNode != nullptr) {
3581 builder.clearAccessChain();
3582 specNode->traverse(this);
3583 return accessChainLoad(specNode->getAsTyped()->getType());
3584 }
qining25262b32016-05-06 17:25:16 -04003585
John Kessenich6c292d32016-02-15 20:58:50 -07003586 // Otherwise, need a compile-time (front end) size, get it:
3587 int size = arraySizes.getDimSize(dim);
3588 assert(size > 0);
3589 return builder.makeUintConstant(size);
3590}
3591
John Kessenich103bef92016-02-08 21:38:15 -07003592// Wrap the builder's accessChainLoad to:
3593// - localize handling of RelaxedPrecision
3594// - use the SPIR-V inferred type instead of another conversion of the glslang type
3595// (avoids unnecessary work and possible type punning for structures)
3596// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003597spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3598{
John Kessenich103bef92016-02-08 21:38:15 -07003599 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003600
3601 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3602 coherentFlags |= TranslateCoherent(type);
3603
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003604 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003605 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003606
John Kessenich5611c6d2018-04-05 11:25:02 -06003607 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003608 TranslateNonUniformDecoration(type.getQualifier()),
3609 nominalTypeId,
3610 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003611 TranslateMemoryScope(coherentFlags),
3612 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003613
3614 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003615 if (type.getBasicType() == glslang::EbtBool) {
3616 if (builder.isScalarType(nominalTypeId)) {
3617 // Conversion for bool
3618 spv::Id boolType = builder.makeBoolType();
3619 if (nominalTypeId != boolType)
3620 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3621 } else if (builder.isVectorType(nominalTypeId)) {
3622 // Conversion for bvec
3623 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3624 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3625 if (nominalTypeId != bvecType)
3626 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3627 }
3628 }
John Kessenich103bef92016-02-08 21:38:15 -07003629
3630 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003631}
3632
Rex Xu27253232016-02-23 17:51:09 +08003633// Wrap the builder's accessChainStore to:
3634// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003635//
3636// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003637void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3638{
3639 // Need to convert to abstract types when necessary
3640 if (type.getBasicType() == glslang::EbtBool) {
3641 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3642
3643 if (builder.isScalarType(nominalTypeId)) {
3644 // Conversion for bool
3645 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003646 if (nominalTypeId != boolType) {
3647 // keep these outside arguments, for determinant order-of-evaluation
3648 spv::Id one = builder.makeUintConstant(1);
3649 spv::Id zero = builder.makeUintConstant(0);
3650 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3651 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003652 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003653 } else if (builder.isVectorType(nominalTypeId)) {
3654 // Conversion for bvec
3655 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3656 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003657 if (nominalTypeId != bvecType) {
3658 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003659 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3660 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3661 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003662 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003663 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3664 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003665 }
3666 }
3667
Jeff Bolz36831c92018-09-05 10:11:41 -05003668 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3669 coherentFlags |= TranslateCoherent(type);
3670
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003671 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003672 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003673
Jeff Bolz36831c92018-09-05 10:11:41 -05003674 builder.accessChainStore(rvalue,
3675 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003676 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003677}
3678
John Kessenich4bf71552016-09-02 11:20:21 -06003679// For storing when types match at the glslang level, but not might match at the
3680// SPIR-V level.
3681//
3682// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003683// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003684// as in a member-decorated way.
3685//
3686// NOTE: This function can handle any store request; if it's not special it
3687// simplifies to a simple OpStore.
3688//
3689// Implicitly uses the existing builder.accessChain as the storage target.
3690void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3691{
John Kessenichb3e24e42016-09-11 12:33:43 -06003692 // we only do the complex path here if it's an aggregate
3693 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003694 accessChainStore(type, rValue);
3695 return;
3696 }
3697
John Kessenichb3e24e42016-09-11 12:33:43 -06003698 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003699 spv::Id rType = builder.getTypeId(rValue);
3700 spv::Id lValue = builder.accessChainGetLValue();
3701 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3702 if (lType == rType) {
3703 accessChainStore(type, rValue);
3704 return;
3705 }
3706
John Kessenichb3e24e42016-09-11 12:33:43 -06003707 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003708 // where the two types were the same type in GLSL. This requires member
3709 // by member copy, recursively.
3710
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003711 // SPIR-V 1.4 added an instruction to do help do this.
3712 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3713 // However, bool in uniform space is changed to int, so
3714 // OpCopyLogical does not work for that.
3715 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3716 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3717 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3718 if (lBool == rBool) {
3719 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3720 accessChainStore(type, logicalCopy);
3721 return;
3722 }
3723 }
3724
John Kessenichb3e24e42016-09-11 12:33:43 -06003725 // If an array, copy element by element.
3726 if (type.isArray()) {
3727 glslang::TType glslangElementType(type, 0);
3728 spv::Id elementRType = builder.getContainedTypeId(rType);
3729 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3730 // get the source member
3731 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003732
John Kessenichb3e24e42016-09-11 12:33:43 -06003733 // set up the target storage
3734 builder.clearAccessChain();
3735 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003736 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003737
John Kessenichb3e24e42016-09-11 12:33:43 -06003738 // store the member
3739 multiTypeStore(glslangElementType, elementRValue);
3740 }
3741 } else {
3742 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003743
John Kessenichb3e24e42016-09-11 12:33:43 -06003744 // loop over structure members
3745 const glslang::TTypeList& members = *type.getStruct();
3746 for (int m = 0; m < (int)members.size(); ++m) {
3747 const glslang::TType& glslangMemberType = *members[m].type;
3748
3749 // get the source member
3750 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3751 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3752
3753 // set up the target storage
3754 builder.clearAccessChain();
3755 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003756 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003757
3758 // store the member
3759 multiTypeStore(glslangMemberType, memberRValue);
3760 }
John Kessenich4bf71552016-09-02 11:20:21 -06003761 }
3762}
3763
John Kessenichf85e8062015-12-19 13:57:10 -07003764// Decide whether or not this type should be
3765// decorated with offsets and strides, and if so
3766// whether std140 or std430 rules should be applied.
3767glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003768{
John Kessenichf85e8062015-12-19 13:57:10 -07003769 // has to be a block
3770 if (type.getBasicType() != glslang::EbtBlock)
3771 return glslang::ElpNone;
3772
Chao Chen3c366992018-09-19 11:41:59 -07003773 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003774 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003775 type.getQualifier().storage != glslang::EvqBuffer &&
3776 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003777 return glslang::ElpNone;
3778
3779 // return the layout to use
3780 switch (type.getQualifier().layoutPacking) {
3781 case glslang::ElpStd140:
3782 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003783 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003784 return type.getQualifier().layoutPacking;
3785 default:
3786 return glslang::ElpNone;
3787 }
John Kessenich31ed4832015-09-09 17:51:38 -06003788}
3789
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003790// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003791int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003792{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003793 int size;
John Kessenich49987892015-12-29 17:11:44 -07003794 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003795 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003796
3797 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003798}
3799
John Kessenich49987892015-12-29 17:11:44 -07003800// 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 -07003801// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003802int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003803{
John Kessenich49987892015-12-29 17:11:44 -07003804 glslang::TType elementType;
3805 elementType.shallowCopy(matrixType);
3806 elementType.clearArraySizes();
3807
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003808 int size;
John Kessenich49987892015-12-29 17:11:44 -07003809 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003810 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003811
3812 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003813}
3814
John Kessenich5e4b1242015-08-06 22:53:06 -06003815// Given a member type of a struct, realign the current offset for it, and compute
3816// the next (not yet aligned) offset for the next member, which will get aligned
3817// on the next call.
3818// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3819// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3820// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003821void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003822 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003823{
3824 // this will get a positive value when deemed necessary
3825 nextOffset = -1;
3826
John Kessenich5e4b1242015-08-06 22:53:06 -06003827 // override anything in currentOffset with user-set offset
3828 if (memberType.getQualifier().hasOffset())
3829 currentOffset = memberType.getQualifier().layoutOffset;
3830
3831 // It could be that current linker usage in glslang updated all the layoutOffset,
3832 // in which case the following code does not matter. But, that's not quite right
3833 // once cross-compilation unit GLSL validation is done, as the original user
3834 // settings are needed in layoutOffset, and then the following will come into play.
3835
John Kessenichf85e8062015-12-19 13:57:10 -07003836 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003837 if (! memberType.getQualifier().hasOffset())
3838 currentOffset = -1;
3839
3840 return;
3841 }
3842
John Kessenichf85e8062015-12-19 13:57:10 -07003843 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003844 if (currentOffset < 0)
3845 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003846
John Kessenich5e4b1242015-08-06 22:53:06 -06003847 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3848 // but possibly not yet correctly aligned.
3849
3850 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003851 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003852 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003853
3854 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003855 // TODO: make this consistent in early phases of code:
3856 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3857 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3858 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003859 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003860 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003861 int dummySize;
3862 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3863 if (componentAlignment <= 4)
3864 memberAlignment = componentAlignment;
3865 }
3866
3867 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003868 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003869
3870 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003871 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003872 glslang::RoundToPow2(currentOffset, 16);
3873
John Kessenich5e4b1242015-08-06 22:53:06 -06003874 nextOffset = currentOffset + memberSize;
3875}
3876
David Netoa901ffe2016-06-08 14:11:40 +01003877void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003878{
David Netoa901ffe2016-06-08 14:11:40 +01003879 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3880 switch (glslangBuiltIn)
3881 {
3882 case glslang::EbvClipDistance:
3883 case glslang::EbvCullDistance:
3884 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003885#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003886 case glslang::EbvViewportMaskNV:
3887 case glslang::EbvSecondaryPositionNV:
3888 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003889 case glslang::EbvPositionPerViewNV:
3890 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003891 case glslang::EbvTaskCountNV:
3892 case glslang::EbvPrimitiveCountNV:
3893 case glslang::EbvPrimitiveIndicesNV:
3894 case glslang::EbvClipDistancePerViewNV:
3895 case glslang::EbvCullDistancePerViewNV:
3896 case glslang::EbvLayerPerViewNV:
3897 case glslang::EbvMeshViewCountNV:
3898 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003899#endif
David Netoa901ffe2016-06-08 14:11:40 +01003900 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3901 // Alternately, we could just call this for any glslang built-in, since the
3902 // capability already guards against duplicates.
3903 TranslateBuiltInDecoration(glslangBuiltIn, false);
3904 break;
3905 default:
3906 // Capabilities were already generated when the struct was declared.
3907 break;
3908 }
John Kessenichebb50532016-05-16 19:22:05 -06003909}
3910
John Kessenich6fccb3c2016-09-19 16:01:41 -06003911bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003912{
John Kessenicheee9d532016-09-19 18:09:30 -06003913 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003914}
3915
John Kessenichd41993d2017-09-10 15:21:05 -06003916// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003917// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3918// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003919bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003920{
John Kessenich6a14f782017-12-04 02:48:10 -07003921 assert(qualifier == glslang::EvqIn ||
3922 qualifier == glslang::EvqOut ||
3923 qualifier == glslang::EvqInOut ||
3924 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003925 return qualifier != glslang::EvqConstReadOnly;
3926}
3927
3928// Is parameter pass-by-original?
3929bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3930 bool implicitThisParam)
3931{
3932 if (implicitThisParam) // implicit this
3933 return true;
3934 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003935 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003936 return paramType.containsOpaque() || // sampler, etc.
3937 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3938}
3939
John Kessenich140f3df2015-06-26 16:58:36 -06003940// Make all the functions, skeletally, without actually visiting their bodies.
3941void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3942{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003943 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003944 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3945 if (paramPrecision != spv::NoPrecision)
3946 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003947 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003948 if (type.getBasicType() == glslang::EbtReference) {
3949 // Original and non-writable params pass the pointer directly and
3950 // use restrict/aliased, others are stored to a pointer in Function
3951 // memory and use RestrictPointer/AliasedPointer.
3952 if (originalParam(type.getQualifier().storage, type, false) ||
3953 !writableParam(type.getQualifier().storage)) {
3954 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
3955 } else {
3956 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
3957 }
3958 }
John Kessenichfad62972017-07-18 02:35:46 -06003959 };
3960
John Kessenich140f3df2015-06-26 16:58:36 -06003961 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3962 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003963 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003964 continue;
3965
3966 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003967 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003968 //
qining25262b32016-05-06 17:25:16 -04003969 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003970 // function. What it is an address of varies:
3971 //
John Kessenich4bf71552016-09-02 11:20:21 -06003972 // - "in" parameters not marked as "const" can be written to without modifying the calling
3973 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003974 //
3975 // - "const in" parameters can just be the r-value, as no writes need occur.
3976 //
John Kessenich4bf71552016-09-02 11:20:21 -06003977 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3978 // 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 -06003979
3980 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003981 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003982 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3983
John Kessenichfad62972017-07-18 02:35:46 -06003984 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3985 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003986
John Kessenichfad62972017-07-18 02:35:46 -06003987 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003988 for (int p = 0; p < (int)parameters.size(); ++p) {
3989 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3990 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003991 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003992 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003993 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003994 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3995 else
John Kessenich4bf71552016-09-02 11:20:21 -06003996 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003997 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003998 paramTypes.push_back(typeId);
3999 }
4000
4001 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07004002 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
4003 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06004004 glslFunction->getName().c_str(), paramTypes,
4005 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06004006 if (implicitThis)
4007 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06004008
4009 // Track function to emit/call later
4010 functionMap[glslFunction->getName().c_str()] = function;
4011
4012 // Set the parameter id's
4013 for (int p = 0; p < (int)parameters.size(); ++p) {
4014 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
4015 // give a name too
4016 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
4017 }
4018 }
4019}
4020
4021// Process all the initializers, while skipping the functions and link objects
4022void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4023{
4024 builder.setBuildPoint(shaderEntry->getLastBlock());
4025 for (int i = 0; i < (int)initializers.size(); ++i) {
4026 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4027 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4028
4029 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004030 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004031 initializer->traverse(this);
4032 }
4033 }
4034}
4035
4036// Process all the functions, while skipping initializers.
4037void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4038{
4039 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4040 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004041 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004042 node->traverse(this);
4043 }
4044}
4045
4046void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4047{
qining25262b32016-05-06 17:25:16 -04004048 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004049 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004050 currentFunction = functionMap[node->getName().c_str()];
4051 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004052 builder.setBuildPoint(functionBlock);
4053}
4054
Rex Xu04db3f52015-09-16 11:44:02 +08004055void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004056{
Rex Xufc618912015-09-09 16:42:49 +08004057 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004058
4059 glslang::TSampler sampler = {};
4060 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004061#ifdef AMD_EXTENSIONS
4062 bool f16ShadowCompare = false;
4063#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004064 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004065 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4066 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004067#ifdef AMD_EXTENSIONS
4068 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4069#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004070 }
4071
John Kessenich140f3df2015-06-26 16:58:36 -06004072 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4073 builder.clearAccessChain();
4074 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004075
4076 // Special case l-value operands
4077 bool lvalue = false;
4078 switch (node.getOp()) {
4079 case glslang::EOpImageAtomicAdd:
4080 case glslang::EOpImageAtomicMin:
4081 case glslang::EOpImageAtomicMax:
4082 case glslang::EOpImageAtomicAnd:
4083 case glslang::EOpImageAtomicOr:
4084 case glslang::EOpImageAtomicXor:
4085 case glslang::EOpImageAtomicExchange:
4086 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004087 case glslang::EOpImageAtomicLoad:
4088 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004089 if (i == 0)
4090 lvalue = true;
4091 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004092 case glslang::EOpSparseImageLoad:
4093 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4094 lvalue = true;
4095 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004096#ifdef AMD_EXTENSIONS
4097 case glslang::EOpSparseTexture:
4098 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4099 lvalue = true;
4100 break;
4101 case glslang::EOpSparseTextureClamp:
4102 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4103 lvalue = true;
4104 break;
4105 case glslang::EOpSparseTextureLod:
4106 case glslang::EOpSparseTextureOffset:
4107 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4108 lvalue = true;
4109 break;
4110#else
Rex Xu48edadf2015-12-31 16:11:41 +08004111 case glslang::EOpSparseTexture:
4112 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4113 lvalue = true;
4114 break;
4115 case glslang::EOpSparseTextureClamp:
4116 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4117 lvalue = true;
4118 break;
4119 case glslang::EOpSparseTextureLod:
4120 case glslang::EOpSparseTextureOffset:
4121 if (i == 3)
4122 lvalue = true;
4123 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004124#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004125 case glslang::EOpSparseTextureFetch:
4126 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4127 lvalue = true;
4128 break;
4129 case glslang::EOpSparseTextureFetchOffset:
4130 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4131 lvalue = true;
4132 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004133#ifdef AMD_EXTENSIONS
4134 case glslang::EOpSparseTextureLodOffset:
4135 case glslang::EOpSparseTextureGrad:
4136 case glslang::EOpSparseTextureOffsetClamp:
4137 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4138 lvalue = true;
4139 break;
4140 case glslang::EOpSparseTextureGradOffset:
4141 case glslang::EOpSparseTextureGradClamp:
4142 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4143 lvalue = true;
4144 break;
4145 case glslang::EOpSparseTextureGradOffsetClamp:
4146 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4147 lvalue = true;
4148 break;
4149#else
Rex Xu48edadf2015-12-31 16:11:41 +08004150 case glslang::EOpSparseTextureLodOffset:
4151 case glslang::EOpSparseTextureGrad:
4152 case glslang::EOpSparseTextureOffsetClamp:
4153 if (i == 4)
4154 lvalue = true;
4155 break;
4156 case glslang::EOpSparseTextureGradOffset:
4157 case glslang::EOpSparseTextureGradClamp:
4158 if (i == 5)
4159 lvalue = true;
4160 break;
4161 case glslang::EOpSparseTextureGradOffsetClamp:
4162 if (i == 6)
4163 lvalue = true;
4164 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004165#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004166 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004167 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4168 lvalue = true;
4169 break;
4170 case glslang::EOpSparseTextureGatherOffset:
4171 case glslang::EOpSparseTextureGatherOffsets:
4172 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4173 lvalue = true;
4174 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004175#ifdef AMD_EXTENSIONS
4176 case glslang::EOpSparseTextureGatherLod:
4177 if (i == 3)
4178 lvalue = true;
4179 break;
4180 case glslang::EOpSparseTextureGatherLodOffset:
4181 case glslang::EOpSparseTextureGatherLodOffsets:
4182 if (i == 4)
4183 lvalue = true;
4184 break;
Rex Xu129799a2017-07-05 17:23:28 +08004185 case glslang::EOpSparseImageLoadLod:
4186 if (i == 3)
4187 lvalue = true;
4188 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004189#endif
Chao Chen3a137962018-09-19 11:41:27 -07004190#ifdef NV_EXTENSIONS
4191 case glslang::EOpImageSampleFootprintNV:
4192 if (i == 4)
4193 lvalue = true;
4194 break;
4195 case glslang::EOpImageSampleFootprintClampNV:
4196 case glslang::EOpImageSampleFootprintLodNV:
4197 if (i == 5)
4198 lvalue = true;
4199 break;
4200 case glslang::EOpImageSampleFootprintGradNV:
4201 if (i == 6)
4202 lvalue = true;
4203 break;
4204 case glslang::EOpImageSampleFootprintGradClampNV:
4205 if (i == 7)
4206 lvalue = true;
4207 break;
4208#endif
Rex Xufc618912015-09-09 16:42:49 +08004209 default:
4210 break;
4211 }
4212
Rex Xu6b86d492015-09-16 17:48:22 +08004213 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08004214 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08004215 else
John Kessenich32cfd492016-02-02 12:37:46 -07004216 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004217 }
4218}
4219
John Kessenichfc51d282015-08-19 13:34:18 -06004220void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004221{
John Kessenichfc51d282015-08-19 13:34:18 -06004222 builder.clearAccessChain();
4223 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004224 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004225}
John Kessenich140f3df2015-06-26 16:58:36 -06004226
John Kessenichfc51d282015-08-19 13:34:18 -06004227spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4228{
John Kesseniche485c7a2017-05-31 18:50:53 -06004229 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004230 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004231
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004232 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004233
John Kessenichfc51d282015-08-19 13:34:18 -06004234 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004235
John Kessenichf43c7392019-03-31 10:51:57 -06004236 const glslang::TType &imageType = node->getAsAggregate()
4237 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4238 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004239 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004240#ifdef AMD_EXTENSIONS
4241 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004242 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4243 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004244#endif
4245
John Kessenichf43c7392019-03-31 10:51:57 -06004246 const auto signExtensionMask = [&]() {
4247 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4248 if (sampler.type == glslang::EbtUint)
4249 return spv::ImageOperandsZeroExtendMask;
4250 else if (sampler.type == glslang::EbtInt)
4251 return spv::ImageOperandsSignExtendMask;
4252 }
4253 return spv::ImageOperandsMaskNone;
4254 };
4255
John Kessenichfc51d282015-08-19 13:34:18 -06004256 std::vector<spv::Id> arguments;
4257 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08004258 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06004259 else
4260 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004261 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004262
4263 spv::Builder::TextureParameters params = { };
4264 params.sampler = arguments[0];
4265
Rex Xu04db3f52015-09-16 11:44:02 +08004266 glslang::TCrackedTextureOp cracked;
4267 node->crackTexture(sampler, cracked);
4268
amhagan05506bb2017-06-13 16:53:02 -04004269 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004270
John Kessenichfc51d282015-08-19 13:34:18 -06004271 // Check for queries
4272 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004273 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4274 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004275 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004276
John Kessenichfc51d282015-08-19 13:34:18 -06004277 switch (node->getOp()) {
4278 case glslang::EOpImageQuerySize:
4279 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004280 if (arguments.size() > 1) {
4281 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004282 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004283 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004284 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004285 case glslang::EOpImageQuerySamples:
4286 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004287 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004288 case glslang::EOpTextureQueryLod:
4289 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004290 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004291 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004292 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004293 case glslang::EOpSparseTexelsResident:
4294 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004295 default:
4296 assert(0);
4297 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004298 }
John Kessenich140f3df2015-06-26 16:58:36 -06004299 }
4300
LoopDawg4425f242018-02-18 11:40:01 -07004301 int components = node->getType().getVectorSize();
4302
4303 if (node->getOp() == glslang::EOpTextureFetch) {
4304 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4305 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4306 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4307 // here around e.g. which ones return scalars or other types.
4308 components = 4;
4309 }
4310
4311 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4312
4313 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4314
Rex Xufc618912015-09-09 16:42:49 +08004315 // Check for image functions other than queries
4316 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004317 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004318 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004319 spv::IdImmediate image = { true, *(opIt++) };
4320 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004321
4322 // Handle subpass operations
4323 // TODO: GLSL should change to have the "MS" only on the type rather than the
4324 // built-in function.
4325 if (cracked.subpass) {
4326 // add on the (0,0) coordinate
4327 spv::Id zero = builder.makeIntConstant(0);
4328 std::vector<spv::Id> comps;
4329 comps.push_back(zero);
4330 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004331 spv::IdImmediate coord = { true,
4332 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4333 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004334 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4335 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich6c292d32016-02-15 20:58:50 -07004336 if (sampler.ms) {
John Kessenichf43c7392019-03-31 10:51:57 -06004337 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4338 }
4339 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004340 operands.push_back(imageOperands);
John Kessenichf43c7392019-03-31 10:51:57 -06004341 if (sampler.ms) {
4342 spv::IdImmediate imageOperand = { true, *(opIt++) };
4343 operands.push_back(imageOperand);
4344 }
John Kessenich6c292d32016-02-15 20:58:50 -07004345 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004346 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4347 builder.setPrecision(result, precision);
4348 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004349 }
4350
John Kessenich149afc32018-08-14 13:31:43 -06004351 spv::IdImmediate coord = { true, *(opIt++) };
4352 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004353#ifdef AMD_EXTENSIONS
4354 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4355#else
John Kessenich56bab042015-09-16 10:54:31 -06004356 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004357#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004358 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004359 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004360 mask = mask | spv::ImageOperandsSampleMask;
4361 }
Rex Xu129799a2017-07-05 17:23:28 +08004362#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004363 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004364 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4365 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004366 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004367 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004368#endif
4369 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4370 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004371 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004372 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004373 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4374 operands.push_back(imageOperands);
4375 }
4376 if (mask & spv::ImageOperandsSampleMask) {
4377 spv::IdImmediate imageOperand = { true, *opIt++ };
4378 operands.push_back(imageOperand);
4379 }
4380#ifdef AMD_EXTENSIONS
4381 if (mask & spv::ImageOperandsLodMask) {
4382 spv::IdImmediate imageOperand = { true, *opIt++ };
4383 operands.push_back(imageOperand);
4384 }
4385#endif
4386 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004387 spv::IdImmediate imageOperand = { true,
4388 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004389 operands.push_back(imageOperand);
4390 }
4391
John Kessenich149afc32018-08-14 13:31:43 -06004392 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004393 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004394
John Kessenich149afc32018-08-14 13:31:43 -06004395 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004396 builder.setPrecision(result[0], precision);
4397
4398 // If needed, add a conversion constructor to the proper size.
4399 if (components != node->getType().getVectorSize())
4400 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4401
4402 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004403#ifdef AMD_EXTENSIONS
4404 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4405#else
John Kessenich56bab042015-09-16 10:54:31 -06004406 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004407#endif
Rex Xu129799a2017-07-05 17:23:28 +08004408
Jeff Bolz36831c92018-09-05 10:11:41 -05004409 // Push the texel value before the operands
4410#ifdef AMD_EXTENSIONS
4411 if (sampler.ms || cracked.lod) {
4412#else
4413 if (sampler.ms) {
4414#endif
John Kessenich149afc32018-08-14 13:31:43 -06004415 spv::IdImmediate texel = { true, *(opIt + 1) };
4416 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004417 } else {
4418 spv::IdImmediate texel = { true, *opIt };
4419 operands.push_back(texel);
4420 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004421
4422 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4423 if (sampler.ms) {
4424 mask = mask | spv::ImageOperandsSampleMask;
4425 }
4426#ifdef AMD_EXTENSIONS
4427 if (cracked.lod) {
4428 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4429 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4430 mask = mask | spv::ImageOperandsLodMask;
4431 }
4432#endif
4433 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4434 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004435 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004436 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004437 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4438 operands.push_back(imageOperands);
4439 }
4440 if (mask & spv::ImageOperandsSampleMask) {
4441 spv::IdImmediate imageOperand = { true, *opIt++ };
4442 operands.push_back(imageOperand);
4443 }
4444#ifdef AMD_EXTENSIONS
4445 if (mask & spv::ImageOperandsLodMask) {
4446 spv::IdImmediate imageOperand = { true, *opIt++ };
4447 operands.push_back(imageOperand);
4448 }
4449#endif
4450 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004451 spv::IdImmediate imageOperand = { true,
4452 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004453 operands.push_back(imageOperand);
4454 }
4455
John Kessenich56bab042015-09-16 10:54:31 -06004456 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004457 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004458 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004459 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004460#ifdef AMD_EXTENSIONS
John Kessenichf43c7392019-03-31 10:51:57 -06004461 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4462 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004463#else
Rex Xu5eafa472016-02-19 22:24:03 +08004464 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004465#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004466 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004467 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004468 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4469
Jeff Bolz36831c92018-09-05 10:11:41 -05004470 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004471 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004472 mask = mask | spv::ImageOperandsSampleMask;
4473 }
Rex Xu129799a2017-07-05 17:23:28 +08004474#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004475 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004476 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4477 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4478
Jeff Bolz36831c92018-09-05 10:11:41 -05004479 mask = mask | spv::ImageOperandsLodMask;
4480 }
4481#endif
4482 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4483 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004484 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004485 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004486 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004487 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004488 }
4489 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004490 spv::IdImmediate imageOperand = { true, *opIt++ };
4491 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004492 }
4493#ifdef AMD_EXTENSIONS
4494 if (mask & spv::ImageOperandsLodMask) {
4495 spv::IdImmediate imageOperand = { true, *opIt++ };
4496 operands.push_back(imageOperand);
4497 }
Rex Xu129799a2017-07-05 17:23:28 +08004498#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004499 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4500 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4501 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004502 }
4503
4504 // Create the return type that was a special structure
4505 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004506 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004507 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4508 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4509
4510 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4511
4512 // Decode the return type
4513 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4514 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004515 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004516 // Process image atomic operations
4517
4518 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4519 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004520 // For non-MS, the sample value should be 0
4521 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4522 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004523
Jeff Bolz36831c92018-09-05 10:11:41 -05004524 spv::Id resultTypeId;
4525 // imageAtomicStore has a void return type so base the pointer type on
4526 // the type of the value operand.
4527 if (node->getOp() == glslang::EOpImageAtomicStore) {
4528 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4529 } else {
4530 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4531 }
John Kessenich56bab042015-09-16 10:54:31 -06004532 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004533
4534 std::vector<spv::Id> operands;
4535 operands.push_back(pointer);
4536 for (; opIt != arguments.end(); ++opIt)
4537 operands.push_back(*opIt);
4538
John Kessenich8c8505c2016-07-26 12:50:38 -06004539 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004540 }
4541 }
4542
amhagan05506bb2017-06-13 16:53:02 -04004543#ifdef AMD_EXTENSIONS
4544 // Check for fragment mask functions other than queries
4545 if (cracked.fragMask) {
4546 assert(sampler.ms);
4547
4548 auto opIt = arguments.begin();
4549 std::vector<spv::Id> operands;
4550
4551 // Extract the image if necessary
4552 if (builder.isSampledImage(params.sampler))
4553 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4554
4555 operands.push_back(params.sampler);
4556 ++opIt;
4557
4558 if (sampler.isSubpass()) {
4559 // add on the (0,0) coordinate
4560 spv::Id zero = builder.makeIntConstant(0);
4561 std::vector<spv::Id> comps;
4562 comps.push_back(zero);
4563 comps.push_back(zero);
4564 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4565 }
4566
4567 for (; opIt != arguments.end(); ++opIt)
4568 operands.push_back(*opIt);
4569
4570 spv::Op fragMaskOp = spv::OpNop;
4571 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4572 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4573 else if (node->getOp() == glslang::EOpFragmentFetch)
4574 fragMaskOp = spv::OpFragmentFetchAMD;
4575
4576 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4577 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4578 return builder.createOp(fragMaskOp, resultType(), operands);
4579 }
4580#endif
4581
Rex Xufc618912015-09-09 16:42:49 +08004582 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004583 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004584#ifdef NV_EXTENSIONS
4585 bool imageFootprint = node->isImageFootprint();
4586#endif
4587
Rex Xu71519fe2015-11-11 15:35:47 +08004588 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4589
John Kessenichfc51d282015-08-19 13:34:18 -06004590 // check for bias argument
4591 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004592#ifdef AMD_EXTENSIONS
4593 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4594#else
Rex Xu71519fe2015-11-11 15:35:47 +08004595 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004596#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004597 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004598#ifdef AMD_EXTENSIONS
4599 if (cracked.gather)
4600 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004601
4602 if (f16ShadowCompare)
4603 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004604#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004605 if (cracked.offset)
4606 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004607#ifdef AMD_EXTENSIONS
4608 else if (cracked.offsets)
4609 ++nonBiasArgCount;
4610#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004611 if (cracked.grad)
4612 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004613 if (cracked.lodClamp)
4614 ++nonBiasArgCount;
4615 if (sparse)
4616 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004617#ifdef NV_EXTENSIONS
4618 if (imageFootprint)
4619 //Following three extra arguments
4620 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4621 nonBiasArgCount += 3;
4622#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004623 if ((int)arguments.size() > nonBiasArgCount)
4624 bias = true;
4625 }
4626
John Kessenicha5c33d62016-06-02 23:45:21 -06004627 // See if the sampler param should really be just the SPV image part
4628 if (cracked.fetch) {
4629 // a fetch needs to have the image extracted first
4630 if (builder.isSampledImage(params.sampler))
4631 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4632 }
4633
Rex Xu225e0fc2016-11-17 17:47:59 +08004634#ifdef AMD_EXTENSIONS
4635 if (cracked.gather) {
4636 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4637 if (bias || cracked.lod ||
4638 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4639 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004640 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004641 }
4642 }
4643#endif
4644
John Kessenichfc51d282015-08-19 13:34:18 -06004645 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004646
John Kessenichfc51d282015-08-19 13:34:18 -06004647 params.coords = arguments[1];
4648 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004649 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004650
4651 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004652#ifdef AMD_EXTENSIONS
4653 if (cubeCompare || f16ShadowCompare) {
4654#else
Rex Xu48edadf2015-12-31 16:11:41 +08004655 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004656#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004657 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004658 ++extraArgs;
4659 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004660 params.Dref = arguments[2];
4661 ++extraArgs;
4662 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004663 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004664 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004665 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004666 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004667 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004668 dRefComp = builder.getNumComponents(params.coords) - 1;
4669 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004670 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4671 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004672
4673 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004674 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004675 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004676 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004677 } else if (glslangIntermediate->getStage() != EShLangFragment
4678#ifdef NV_EXTENSIONS
4679 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4680 && !(glslangIntermediate->getStage() == EShLangCompute &&
4681 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4682#endif
4683 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004684 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4685 noImplicitLod = true;
4686 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004687
4688 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004689 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004690 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004691 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004692 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004693
4694 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004695 if (cracked.grad) {
4696 params.gradX = arguments[2 + extraArgs];
4697 params.gradY = arguments[3 + extraArgs];
4698 extraArgs += 2;
4699 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004700
4701 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004702 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004703 params.offset = arguments[2 + extraArgs];
4704 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004705 } else if (cracked.offsets) {
4706 params.offsets = arguments[2 + extraArgs];
4707 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004708 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004709
4710 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004711 if (cracked.lodClamp) {
4712 params.lodClamp = arguments[2 + extraArgs];
4713 ++extraArgs;
4714 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004715 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004716 if (sparse) {
4717 params.texelOut = arguments[2 + extraArgs];
4718 ++extraArgs;
4719 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004720
John Kessenich76d4dfc2016-06-16 12:43:23 -06004721 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004722 if (cracked.gather && ! sampler.shadow) {
4723 // default component is 0, if missing, otherwise an argument
4724 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004725 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004726 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004727 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004728 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004729 }
Chao Chen3a137962018-09-19 11:41:27 -07004730#ifdef NV_EXTENSIONS
4731 spv::Id resultStruct = spv::NoResult;
4732 if (imageFootprint) {
4733 //Following three extra arguments
4734 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4735 params.granularity = arguments[2 + extraArgs];
4736 params.coarse = arguments[3 + extraArgs];
4737 resultStruct = arguments[4 + extraArgs];
4738 extraArgs += 3;
4739 }
4740#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004741 // bias
4742 if (bias) {
4743 params.bias = arguments[2 + extraArgs];
4744 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004745 }
John Kessenichfc51d282015-08-19 13:34:18 -06004746
Chao Chen3a137962018-09-19 11:41:27 -07004747#ifdef NV_EXTENSIONS
4748 if (imageFootprint) {
4749 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4750 builder.addCapability(spv::CapabilityImageFootprintNV);
4751
4752
4753 //resultStructType(OpenGL type) contains 5 elements:
4754 //struct gl_TextureFootprint2DNV {
4755 // uvec2 anchor;
4756 // uvec2 offset;
4757 // uvec2 mask;
4758 // uint lod;
4759 // uint granularity;
4760 //};
4761 //or
4762 //struct gl_TextureFootprint3DNV {
4763 // uvec3 anchor;
4764 // uvec3 offset;
4765 // uvec2 mask;
4766 // uint lod;
4767 // uint granularity;
4768 //};
4769 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4770 assert(builder.isStructType(resultStructType));
4771
4772 //resType (SPIR-V type) contains 6 elements:
4773 //Member 0 must be a Boolean type scalar(LOD),
4774 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4775 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4776 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4777 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4778 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4779 std::vector<spv::Id> members;
4780 members.push_back(resultType());
4781 for (int i = 0; i < 5; i++) {
4782 members.push_back(builder.getContainedTypeId(resultStructType, i));
4783 }
4784 spv::Id resType = builder.makeStructType(members, "ResType");
4785
4786 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004787 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4788 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004789
4790 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4791 for (int i = 0; i < 5; i++) {
4792 builder.clearAccessChain();
4793 builder.setAccessChainLValue(resultStruct);
4794
4795 //Accessing to a struct we created, no coherent flag is set
4796 spv::Builder::AccessChain::CoherentFlags flags;
4797 flags.clear();
4798
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004799 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004800 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4801 }
4802 return builder.createCompositeExtract(res, resultType(), 0);
4803 }
4804#endif
4805
John Kessenich65336482016-06-16 14:06:26 -06004806 // projective component (might not to move)
4807 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4808 // are divided by the last component of P."
4809 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4810 // unused components will appear after all used components."
4811 if (cracked.proj) {
4812 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4813 int projTargetComp;
4814 switch (sampler.dim) {
4815 case glslang::Esd1D: projTargetComp = 1; break;
4816 case glslang::Esd2D: projTargetComp = 2; break;
4817 case glslang::EsdRect: projTargetComp = 2; break;
4818 default: projTargetComp = projSourceComp; break;
4819 }
4820 // copy the projective coordinate if we have to
4821 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004822 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004823 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4824 projSourceComp);
4825 params.coords = builder.createCompositeInsert(projComp, params.coords,
4826 builder.getTypeId(params.coords), projTargetComp);
4827 }
4828 }
4829
Jeff Bolz36831c92018-09-05 10:11:41 -05004830 // nonprivate
4831 if (imageType.getQualifier().nonprivate) {
4832 params.nonprivate = true;
4833 }
4834
4835 // volatile
4836 if (imageType.getQualifier().volatil) {
4837 params.volatil = true;
4838 }
4839
St0fFa1184dd2018-04-09 21:08:14 +02004840 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004841 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4842 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004843 );
LoopDawg4425f242018-02-18 11:40:01 -07004844
4845 if (components != node->getType().getVectorSize())
4846 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4847
4848 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004849}
4850
4851spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4852{
4853 // Grab the function's pointer from the previously created function
4854 spv::Function* function = functionMap[node->getName().c_str()];
4855 if (! function)
4856 return 0;
4857
4858 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4859 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4860
4861 // See comments in makeFunctions() for details about the semantics for parameter passing.
4862 //
4863 // These imply we need a four step process:
4864 // 1. Evaluate the arguments
4865 // 2. Allocate and make copies of in, out, and inout arguments
4866 // 3. Make the call
4867 // 4. Copy back the results
4868
John Kessenichd3ed90b2018-05-04 11:43:03 -06004869 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004870 std::vector<spv::Builder::AccessChain> lValues;
4871 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004872 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004873 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004874 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004875 // build l-value
4876 builder.clearAccessChain();
4877 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004878 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004879 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004880 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004881 // save l-value
4882 lValues.push_back(builder.getAccessChain());
4883 } else {
4884 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004885 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004886 }
4887 }
4888
4889 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4890 // copy the original into that space.
4891 //
4892 // Also, build up the list of actual arguments to pass in for the call
4893 int lValueCount = 0;
4894 int rValueCount = 0;
4895 std::vector<spv::Id> spvArgs;
4896 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4897 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004898 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004899 builder.setAccessChain(lValues[lValueCount]);
4900 arg = builder.accessChainGetLValue();
4901 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004902 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004903 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004904 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004905 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4906 // need to copy the input into output space
4907 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004908 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004909 builder.clearAccessChain();
4910 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004911 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004912 }
4913 ++lValueCount;
4914 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004915 // process r-value, which involves a copy for a type mismatch
4916 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4917 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4918 builder.clearAccessChain();
4919 builder.setAccessChainLValue(argCopy);
4920 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4921 arg = builder.createLoad(argCopy);
4922 } else
4923 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004924 ++rValueCount;
4925 }
4926 spvArgs.push_back(arg);
4927 }
4928
4929 // 3. Make the call.
4930 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004931 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004932
4933 // 4. Copy back out an "out" arguments.
4934 lValueCount = 0;
4935 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004936 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004937 ++lValueCount;
4938 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004939 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4940 spv::Id copy = builder.createLoad(spvArgs[a]);
4941 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004942 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004943 }
4944 ++lValueCount;
4945 }
4946 }
4947
4948 return result;
4949}
4950
4951// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004952spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004953 spv::Id typeId, spv::Id left, spv::Id right,
4954 glslang::TBasicType typeProxy, bool reduceComparison)
4955{
John Kessenich66011cb2018-03-06 16:12:04 -07004956 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4957 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004958 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004959
4960 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004961 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004962 bool comparison = false;
4963
4964 switch (op) {
4965 case glslang::EOpAdd:
4966 case glslang::EOpAddAssign:
4967 if (isFloat)
4968 binOp = spv::OpFAdd;
4969 else
4970 binOp = spv::OpIAdd;
4971 break;
4972 case glslang::EOpSub:
4973 case glslang::EOpSubAssign:
4974 if (isFloat)
4975 binOp = spv::OpFSub;
4976 else
4977 binOp = spv::OpISub;
4978 break;
4979 case glslang::EOpMul:
4980 case glslang::EOpMulAssign:
4981 if (isFloat)
4982 binOp = spv::OpFMul;
4983 else
4984 binOp = spv::OpIMul;
4985 break;
4986 case glslang::EOpVectorTimesScalar:
4987 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004988 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004989 if (builder.isVector(right))
4990 std::swap(left, right);
4991 assert(builder.isScalar(right));
4992 needMatchingVectors = false;
4993 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01004994 } else if (isFloat)
4995 binOp = spv::OpFMul;
4996 else
John Kessenichec43d0a2015-07-04 17:17:31 -06004997 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004998 break;
4999 case glslang::EOpVectorTimesMatrix:
5000 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005001 binOp = spv::OpVectorTimesMatrix;
5002 break;
5003 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06005004 binOp = spv::OpMatrixTimesVector;
5005 break;
5006 case glslang::EOpMatrixTimesScalar:
5007 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005008 binOp = spv::OpMatrixTimesScalar;
5009 break;
5010 case glslang::EOpMatrixTimesMatrix:
5011 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06005012 binOp = spv::OpMatrixTimesMatrix;
5013 break;
5014 case glslang::EOpOuterProduct:
5015 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06005016 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005017 break;
5018
5019 case glslang::EOpDiv:
5020 case glslang::EOpDivAssign:
5021 if (isFloat)
5022 binOp = spv::OpFDiv;
5023 else if (isUnsigned)
5024 binOp = spv::OpUDiv;
5025 else
5026 binOp = spv::OpSDiv;
5027 break;
5028 case glslang::EOpMod:
5029 case glslang::EOpModAssign:
5030 if (isFloat)
5031 binOp = spv::OpFMod;
5032 else if (isUnsigned)
5033 binOp = spv::OpUMod;
5034 else
5035 binOp = spv::OpSMod;
5036 break;
5037 case glslang::EOpRightShift:
5038 case glslang::EOpRightShiftAssign:
5039 if (isUnsigned)
5040 binOp = spv::OpShiftRightLogical;
5041 else
5042 binOp = spv::OpShiftRightArithmetic;
5043 break;
5044 case glslang::EOpLeftShift:
5045 case glslang::EOpLeftShiftAssign:
5046 binOp = spv::OpShiftLeftLogical;
5047 break;
5048 case glslang::EOpAnd:
5049 case glslang::EOpAndAssign:
5050 binOp = spv::OpBitwiseAnd;
5051 break;
5052 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005053 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005054 binOp = spv::OpLogicalAnd;
5055 break;
5056 case glslang::EOpInclusiveOr:
5057 case glslang::EOpInclusiveOrAssign:
5058 binOp = spv::OpBitwiseOr;
5059 break;
5060 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005061 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005062 binOp = spv::OpLogicalOr;
5063 break;
5064 case glslang::EOpExclusiveOr:
5065 case glslang::EOpExclusiveOrAssign:
5066 binOp = spv::OpBitwiseXor;
5067 break;
5068 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005069 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005070 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005071 break;
5072
5073 case glslang::EOpLessThan:
5074 case glslang::EOpGreaterThan:
5075 case glslang::EOpLessThanEqual:
5076 case glslang::EOpGreaterThanEqual:
5077 case glslang::EOpEqual:
5078 case glslang::EOpNotEqual:
5079 case glslang::EOpVectorEqual:
5080 case glslang::EOpVectorNotEqual:
5081 comparison = true;
5082 break;
5083 default:
5084 break;
5085 }
5086
John Kessenich7c1aa102015-10-15 13:29:11 -06005087 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005088 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005089 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005090 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5091 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005092 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005093
5094 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005095 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005096 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005097
qining25262b32016-05-06 17:25:16 -04005098 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005099 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005100 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005101 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005102 }
5103
5104 if (! comparison)
5105 return 0;
5106
John Kessenich7c1aa102015-10-15 13:29:11 -06005107 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005108
John Kessenich4583b612016-08-07 19:14:22 -06005109 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005110 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5111 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06005112 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005113 return result;
5114 }
John Kessenich140f3df2015-06-26 16:58:36 -06005115
5116 switch (op) {
5117 case glslang::EOpLessThan:
5118 if (isFloat)
5119 binOp = spv::OpFOrdLessThan;
5120 else if (isUnsigned)
5121 binOp = spv::OpULessThan;
5122 else
5123 binOp = spv::OpSLessThan;
5124 break;
5125 case glslang::EOpGreaterThan:
5126 if (isFloat)
5127 binOp = spv::OpFOrdGreaterThan;
5128 else if (isUnsigned)
5129 binOp = spv::OpUGreaterThan;
5130 else
5131 binOp = spv::OpSGreaterThan;
5132 break;
5133 case glslang::EOpLessThanEqual:
5134 if (isFloat)
5135 binOp = spv::OpFOrdLessThanEqual;
5136 else if (isUnsigned)
5137 binOp = spv::OpULessThanEqual;
5138 else
5139 binOp = spv::OpSLessThanEqual;
5140 break;
5141 case glslang::EOpGreaterThanEqual:
5142 if (isFloat)
5143 binOp = spv::OpFOrdGreaterThanEqual;
5144 else if (isUnsigned)
5145 binOp = spv::OpUGreaterThanEqual;
5146 else
5147 binOp = spv::OpSGreaterThanEqual;
5148 break;
5149 case glslang::EOpEqual:
5150 case glslang::EOpVectorEqual:
5151 if (isFloat)
5152 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005153 else if (isBool)
5154 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005155 else
5156 binOp = spv::OpIEqual;
5157 break;
5158 case glslang::EOpNotEqual:
5159 case glslang::EOpVectorNotEqual:
5160 if (isFloat)
5161 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005162 else if (isBool)
5163 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005164 else
5165 binOp = spv::OpINotEqual;
5166 break;
5167 default:
5168 break;
5169 }
5170
qining25262b32016-05-06 17:25:16 -04005171 if (binOp != spv::OpNop) {
5172 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005173 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005174 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005175 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005176 }
John Kessenich140f3df2015-06-26 16:58:36 -06005177
5178 return 0;
5179}
5180
John Kessenich04bb8a02015-12-12 12:28:14 -07005181//
5182// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5183// These can be any of:
5184//
5185// matrix * scalar
5186// scalar * matrix
5187// matrix * matrix linear algebraic
5188// matrix * vector
5189// vector * matrix
5190// matrix * matrix componentwise
5191// matrix op matrix op in {+, -, /}
5192// matrix op scalar op in {+, -, /}
5193// scalar op matrix op in {+, -, /}
5194//
John Kessenichead86222018-03-28 18:01:20 -06005195spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5196 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005197{
5198 bool firstClass = true;
5199
5200 // First, handle first-class matrix operations (* and matrix/scalar)
5201 switch (op) {
5202 case spv::OpFDiv:
5203 if (builder.isMatrix(left) && builder.isScalar(right)) {
5204 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005205 spv::Id resultType = builder.getTypeId(right);
5206 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005207 op = spv::OpMatrixTimesScalar;
5208 } else
5209 firstClass = false;
5210 break;
5211 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005212 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005213 std::swap(left, right);
5214 assert(builder.isScalar(right));
5215 break;
5216 case spv::OpVectorTimesMatrix:
5217 assert(builder.isVector(left));
5218 assert(builder.isMatrix(right));
5219 break;
5220 case spv::OpMatrixTimesVector:
5221 assert(builder.isMatrix(left));
5222 assert(builder.isVector(right));
5223 break;
5224 case spv::OpMatrixTimesMatrix:
5225 assert(builder.isMatrix(left));
5226 assert(builder.isMatrix(right));
5227 break;
5228 default:
5229 firstClass = false;
5230 break;
5231 }
5232
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005233 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5234 firstClass = true;
5235
qining25262b32016-05-06 17:25:16 -04005236 if (firstClass) {
5237 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005238 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005239 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005240 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005241 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005242
LoopDawg592860c2016-06-09 08:57:35 -06005243 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005244 // The result type of all of them is the same type as the (a) matrix operand.
5245 // The algorithm is to:
5246 // - break the matrix(es) into vectors
5247 // - smear any scalar to a vector
5248 // - do vector operations
5249 // - make a matrix out the vector results
5250 switch (op) {
5251 case spv::OpFAdd:
5252 case spv::OpFSub:
5253 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005254 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005255 case spv::OpFMul:
5256 {
5257 // one time set up...
5258 bool leftMat = builder.isMatrix(left);
5259 bool rightMat = builder.isMatrix(right);
5260 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5261 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5262 spv::Id scalarType = builder.getScalarTypeId(typeId);
5263 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5264 std::vector<spv::Id> results;
5265 spv::Id smearVec = spv::NoResult;
5266 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005267 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005268 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005269 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005270
5271 // do each vector op
5272 for (unsigned int c = 0; c < numCols; ++c) {
5273 std::vector<unsigned int> indexes;
5274 indexes.push_back(c);
5275 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5276 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005277 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005278 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005279 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005280 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005281 }
5282
5283 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005284 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005285 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005286 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005287 }
5288 default:
5289 assert(0);
5290 return spv::NoResult;
5291 }
5292}
5293
John Kessenichead86222018-03-28 18:01:20 -06005294spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
5295 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005296{
5297 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005298 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005299 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005300 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5301 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005302
5303 switch (op) {
5304 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005305 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005306 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005307 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005308 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005309 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005310 unaryOp = spv::OpSNegate;
5311 break;
5312
5313 case glslang::EOpLogicalNot:
5314 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005315 unaryOp = spv::OpLogicalNot;
5316 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005317 case glslang::EOpBitwiseNot:
5318 unaryOp = spv::OpNot;
5319 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005320
John Kessenich140f3df2015-06-26 16:58:36 -06005321 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005322 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005323 break;
5324 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005325 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005326 break;
5327 case glslang::EOpTranspose:
5328 unaryOp = spv::OpTranspose;
5329 break;
5330
5331 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005332 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005333 break;
5334 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005335 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005336 break;
5337 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005338 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005339 break;
5340 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005341 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005342 break;
5343 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005344 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005345 break;
5346 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005347 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005348 break;
5349 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005350 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005351 break;
5352 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005353 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005354 break;
5355
5356 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005357 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005358 break;
5359 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005360 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005361 break;
5362 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005363 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005364 break;
5365 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005366 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005367 break;
5368 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005369 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005370 break;
5371 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005372 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005373 break;
5374
5375 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005376 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005377 break;
5378 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005379 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005380 break;
5381
5382 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005383 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005384 break;
5385 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005386 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005387 break;
5388 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005389 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005390 break;
5391 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005392 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005393 break;
5394 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005395 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005396 break;
5397 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005398 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005399 break;
5400
5401 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005402 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005403 break;
5404 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005405 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005406 break;
5407 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005408 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005409 break;
5410 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005411 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005412 break;
5413 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005414 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005415 break;
5416 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005417 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005418 break;
5419
5420 case glslang::EOpIsNan:
5421 unaryOp = spv::OpIsNan;
5422 break;
5423 case glslang::EOpIsInf:
5424 unaryOp = spv::OpIsInf;
5425 break;
LoopDawg592860c2016-06-09 08:57:35 -06005426 case glslang::EOpIsFinite:
5427 unaryOp = spv::OpIsFinite;
5428 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005429
Rex Xucbc426e2015-12-15 16:03:10 +08005430 case glslang::EOpFloatBitsToInt:
5431 case glslang::EOpFloatBitsToUint:
5432 case glslang::EOpIntBitsToFloat:
5433 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005434 case glslang::EOpDoubleBitsToInt64:
5435 case glslang::EOpDoubleBitsToUint64:
5436 case glslang::EOpInt64BitsToDouble:
5437 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005438 case glslang::EOpFloat16BitsToInt16:
5439 case glslang::EOpFloat16BitsToUint16:
5440 case glslang::EOpInt16BitsToFloat16:
5441 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005442 unaryOp = spv::OpBitcast;
5443 break;
5444
John Kessenich140f3df2015-06-26 16:58:36 -06005445 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005446 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005447 break;
5448 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005449 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005450 break;
5451 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005452 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005453 break;
5454 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005455 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005456 break;
5457 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005458 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005459 break;
5460 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005461 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005462 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005463 case glslang::EOpPackSnorm4x8:
5464 libCall = spv::GLSLstd450PackSnorm4x8;
5465 break;
5466 case glslang::EOpUnpackSnorm4x8:
5467 libCall = spv::GLSLstd450UnpackSnorm4x8;
5468 break;
5469 case glslang::EOpPackUnorm4x8:
5470 libCall = spv::GLSLstd450PackUnorm4x8;
5471 break;
5472 case glslang::EOpUnpackUnorm4x8:
5473 libCall = spv::GLSLstd450UnpackUnorm4x8;
5474 break;
5475 case glslang::EOpPackDouble2x32:
5476 libCall = spv::GLSLstd450PackDouble2x32;
5477 break;
5478 case glslang::EOpUnpackDouble2x32:
5479 libCall = spv::GLSLstd450UnpackDouble2x32;
5480 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005481
Rex Xu8ff43de2016-04-22 16:51:45 +08005482 case glslang::EOpPackInt2x32:
5483 case glslang::EOpUnpackInt2x32:
5484 case glslang::EOpPackUint2x32:
5485 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005486 case glslang::EOpPack16:
5487 case glslang::EOpPack32:
5488 case glslang::EOpPack64:
5489 case glslang::EOpUnpack32:
5490 case glslang::EOpUnpack16:
5491 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005492 case glslang::EOpPackInt2x16:
5493 case glslang::EOpUnpackInt2x16:
5494 case glslang::EOpPackUint2x16:
5495 case glslang::EOpUnpackUint2x16:
5496 case glslang::EOpPackInt4x16:
5497 case glslang::EOpUnpackInt4x16:
5498 case glslang::EOpPackUint4x16:
5499 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005500 case glslang::EOpPackFloat2x16:
5501 case glslang::EOpUnpackFloat2x16:
5502 unaryOp = spv::OpBitcast;
5503 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005504
John Kessenich140f3df2015-06-26 16:58:36 -06005505 case glslang::EOpDPdx:
5506 unaryOp = spv::OpDPdx;
5507 break;
5508 case glslang::EOpDPdy:
5509 unaryOp = spv::OpDPdy;
5510 break;
5511 case glslang::EOpFwidth:
5512 unaryOp = spv::OpFwidth;
5513 break;
5514 case glslang::EOpDPdxFine:
5515 unaryOp = spv::OpDPdxFine;
5516 break;
5517 case glslang::EOpDPdyFine:
5518 unaryOp = spv::OpDPdyFine;
5519 break;
5520 case glslang::EOpFwidthFine:
5521 unaryOp = spv::OpFwidthFine;
5522 break;
5523 case glslang::EOpDPdxCoarse:
5524 unaryOp = spv::OpDPdxCoarse;
5525 break;
5526 case glslang::EOpDPdyCoarse:
5527 unaryOp = spv::OpDPdyCoarse;
5528 break;
5529 case glslang::EOpFwidthCoarse:
5530 unaryOp = spv::OpFwidthCoarse;
5531 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005532 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005533#ifdef AMD_EXTENSIONS
5534 if (typeProxy == glslang::EbtFloat16)
5535 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5536#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005537 libCall = spv::GLSLstd450InterpolateAtCentroid;
5538 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005539 case glslang::EOpAny:
5540 unaryOp = spv::OpAny;
5541 break;
5542 case glslang::EOpAll:
5543 unaryOp = spv::OpAll;
5544 break;
5545
5546 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005547 if (isFloat)
5548 libCall = spv::GLSLstd450FAbs;
5549 else
5550 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005551 break;
5552 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005553 if (isFloat)
5554 libCall = spv::GLSLstd450FSign;
5555 else
5556 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005557 break;
5558
John Kessenichfc51d282015-08-19 13:34:18 -06005559 case glslang::EOpAtomicCounterIncrement:
5560 case glslang::EOpAtomicCounterDecrement:
5561 case glslang::EOpAtomicCounter:
5562 {
5563 // Handle all of the atomics in one place, in createAtomicOperation()
5564 std::vector<spv::Id> operands;
5565 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005566 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005567 }
5568
John Kessenichfc51d282015-08-19 13:34:18 -06005569 case glslang::EOpBitFieldReverse:
5570 unaryOp = spv::OpBitReverse;
5571 break;
5572 case glslang::EOpBitCount:
5573 unaryOp = spv::OpBitCount;
5574 break;
5575 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005576 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005577 break;
5578 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005579 if (isUnsigned)
5580 libCall = spv::GLSLstd450FindUMsb;
5581 else
5582 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005583 break;
5584
Rex Xu574ab042016-04-14 16:53:07 +08005585 case glslang::EOpBallot:
5586 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005587 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005588 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005589 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005590#ifdef AMD_EXTENSIONS
5591 case glslang::EOpMinInvocations:
5592 case glslang::EOpMaxInvocations:
5593 case glslang::EOpAddInvocations:
5594 case glslang::EOpMinInvocationsNonUniform:
5595 case glslang::EOpMaxInvocationsNonUniform:
5596 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005597 case glslang::EOpMinInvocationsInclusiveScan:
5598 case glslang::EOpMaxInvocationsInclusiveScan:
5599 case glslang::EOpAddInvocationsInclusiveScan:
5600 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5601 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5602 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5603 case glslang::EOpMinInvocationsExclusiveScan:
5604 case glslang::EOpMaxInvocationsExclusiveScan:
5605 case glslang::EOpAddInvocationsExclusiveScan:
5606 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5607 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5608 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005609#endif
Rex Xu51596642016-09-21 18:56:12 +08005610 {
5611 std::vector<spv::Id> operands;
5612 operands.push_back(operand);
5613 return createInvocationsOperation(op, typeId, operands, typeProxy);
5614 }
John Kessenich66011cb2018-03-06 16:12:04 -07005615 case glslang::EOpSubgroupAll:
5616 case glslang::EOpSubgroupAny:
5617 case glslang::EOpSubgroupAllEqual:
5618 case glslang::EOpSubgroupBroadcastFirst:
5619 case glslang::EOpSubgroupBallot:
5620 case glslang::EOpSubgroupInverseBallot:
5621 case glslang::EOpSubgroupBallotBitCount:
5622 case glslang::EOpSubgroupBallotInclusiveBitCount:
5623 case glslang::EOpSubgroupBallotExclusiveBitCount:
5624 case glslang::EOpSubgroupBallotFindLSB:
5625 case glslang::EOpSubgroupBallotFindMSB:
5626 case glslang::EOpSubgroupAdd:
5627 case glslang::EOpSubgroupMul:
5628 case glslang::EOpSubgroupMin:
5629 case glslang::EOpSubgroupMax:
5630 case glslang::EOpSubgroupAnd:
5631 case glslang::EOpSubgroupOr:
5632 case glslang::EOpSubgroupXor:
5633 case glslang::EOpSubgroupInclusiveAdd:
5634 case glslang::EOpSubgroupInclusiveMul:
5635 case glslang::EOpSubgroupInclusiveMin:
5636 case glslang::EOpSubgroupInclusiveMax:
5637 case glslang::EOpSubgroupInclusiveAnd:
5638 case glslang::EOpSubgroupInclusiveOr:
5639 case glslang::EOpSubgroupInclusiveXor:
5640 case glslang::EOpSubgroupExclusiveAdd:
5641 case glslang::EOpSubgroupExclusiveMul:
5642 case glslang::EOpSubgroupExclusiveMin:
5643 case glslang::EOpSubgroupExclusiveMax:
5644 case glslang::EOpSubgroupExclusiveAnd:
5645 case glslang::EOpSubgroupExclusiveOr:
5646 case glslang::EOpSubgroupExclusiveXor:
5647 case glslang::EOpSubgroupQuadSwapHorizontal:
5648 case glslang::EOpSubgroupQuadSwapVertical:
5649 case glslang::EOpSubgroupQuadSwapDiagonal: {
5650 std::vector<spv::Id> operands;
5651 operands.push_back(operand);
5652 return createSubgroupOperation(op, typeId, operands, typeProxy);
5653 }
Rex Xu9d93a232016-05-05 12:30:44 +08005654#ifdef AMD_EXTENSIONS
5655 case glslang::EOpMbcnt:
5656 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5657 libCall = spv::MbcntAMD;
5658 break;
5659
5660 case glslang::EOpCubeFaceIndex:
5661 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5662 libCall = spv::CubeFaceIndexAMD;
5663 break;
5664
5665 case glslang::EOpCubeFaceCoord:
5666 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5667 libCall = spv::CubeFaceCoordAMD;
5668 break;
5669#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005670#ifdef NV_EXTENSIONS
5671 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005672 unaryOp = spv::OpGroupNonUniformPartitionNV;
5673 break;
5674#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005675 case glslang::EOpConstructReference:
5676 unaryOp = spv::OpBitcast;
5677 break;
Jeff Bolz88220d52019-05-08 10:24:46 -05005678
5679 case glslang::EOpCopyObject:
5680 unaryOp = spv::OpCopyObject;
5681 break;
5682
John Kessenich140f3df2015-06-26 16:58:36 -06005683 default:
5684 return 0;
5685 }
5686
5687 spv::Id id;
5688 if (libCall >= 0) {
5689 std::vector<spv::Id> args;
5690 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005691 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005692 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005693 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005694 }
John Kessenich140f3df2015-06-26 16:58:36 -06005695
John Kessenichead86222018-03-28 18:01:20 -06005696 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005697 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005698 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005699}
5700
John Kessenich7a53f762016-01-20 11:19:27 -07005701// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005702spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5703 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005704{
5705 // Handle unary operations vector by vector.
5706 // The result type is the same type as the original type.
5707 // The algorithm is to:
5708 // - break the matrix into vectors
5709 // - apply the operation to each vector
5710 // - make a matrix out the vector results
5711
5712 // get the types sorted out
5713 int numCols = builder.getNumColumns(operand);
5714 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005715 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5716 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005717 std::vector<spv::Id> results;
5718
5719 // do each vector op
5720 for (int c = 0; c < numCols; ++c) {
5721 std::vector<unsigned int> indexes;
5722 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005723 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5724 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005725 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005726 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005727 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005728 }
5729
5730 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005731 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005732 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005733 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005734}
5735
John Kessenichad7645f2018-06-04 19:11:25 -06005736// For converting integers where both the bitwidth and the signedness could
5737// change, but only do the width change here. The caller is still responsible
5738// for the signedness conversion.
5739spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005740{
John Kessenichad7645f2018-06-04 19:11:25 -06005741 // Get the result type width, based on the type to convert to.
5742 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005743 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005744 case glslang::EOpConvInt16ToUint8:
5745 case glslang::EOpConvIntToUint8:
5746 case glslang::EOpConvInt64ToUint8:
5747 case glslang::EOpConvUint16ToInt8:
5748 case glslang::EOpConvUintToInt8:
5749 case glslang::EOpConvUint64ToInt8:
5750 width = 8;
5751 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005752 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005753 case glslang::EOpConvIntToUint16:
5754 case glslang::EOpConvInt64ToUint16:
5755 case glslang::EOpConvUint8ToInt16:
5756 case glslang::EOpConvUintToInt16:
5757 case glslang::EOpConvUint64ToInt16:
5758 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005759 break;
5760 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005761 case glslang::EOpConvInt16ToUint:
5762 case glslang::EOpConvInt64ToUint:
5763 case glslang::EOpConvUint8ToInt:
5764 case glslang::EOpConvUint16ToInt:
5765 case glslang::EOpConvUint64ToInt:
5766 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005767 break;
5768 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005769 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005770 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005771 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005772 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005773 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005774 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005775 break;
5776
5777 default:
5778 assert(false && "Default missing");
5779 break;
5780 }
5781
John Kessenichad7645f2018-06-04 19:11:25 -06005782 // Get the conversion operation and result type,
5783 // based on the target width, but the source type.
5784 spv::Id type = spv::NoType;
5785 spv::Op convOp = spv::OpNop;
5786 switch(op) {
5787 case glslang::EOpConvInt8ToUint16:
5788 case glslang::EOpConvInt8ToUint:
5789 case glslang::EOpConvInt8ToUint64:
5790 case glslang::EOpConvInt16ToUint8:
5791 case glslang::EOpConvInt16ToUint:
5792 case glslang::EOpConvInt16ToUint64:
5793 case glslang::EOpConvIntToUint8:
5794 case glslang::EOpConvIntToUint16:
5795 case glslang::EOpConvIntToUint64:
5796 case glslang::EOpConvInt64ToUint8:
5797 case glslang::EOpConvInt64ToUint16:
5798 case glslang::EOpConvInt64ToUint:
5799 convOp = spv::OpSConvert;
5800 type = builder.makeIntType(width);
5801 break;
5802 default:
5803 convOp = spv::OpUConvert;
5804 type = builder.makeUintType(width);
5805 break;
5806 }
5807
John Kessenich66011cb2018-03-06 16:12:04 -07005808 if (vectorSize > 0)
5809 type = builder.makeVectorType(type, vectorSize);
5810
John Kessenichad7645f2018-06-04 19:11:25 -06005811 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005812}
5813
John Kessenichead86222018-03-28 18:01:20 -06005814spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5815 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005816{
5817 spv::Op convOp = spv::OpNop;
5818 spv::Id zero = 0;
5819 spv::Id one = 0;
5820
5821 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5822
5823 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005824 case glslang::EOpConvInt8ToBool:
5825 case glslang::EOpConvUint8ToBool:
5826 zero = builder.makeUint8Constant(0);
5827 zero = makeSmearedConstant(zero, vectorSize);
5828 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005829 case glslang::EOpConvInt16ToBool:
5830 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005831 zero = builder.makeUint16Constant(0);
5832 zero = makeSmearedConstant(zero, vectorSize);
5833 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5834 case glslang::EOpConvIntToBool:
5835 case glslang::EOpConvUintToBool:
5836 zero = builder.makeUintConstant(0);
5837 zero = makeSmearedConstant(zero, vectorSize);
5838 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5839 case glslang::EOpConvInt64ToBool:
5840 case glslang::EOpConvUint64ToBool:
5841 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005842 zero = makeSmearedConstant(zero, vectorSize);
5843 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5844
5845 case glslang::EOpConvFloatToBool:
5846 zero = builder.makeFloatConstant(0.0F);
5847 zero = makeSmearedConstant(zero, vectorSize);
5848 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5849
5850 case glslang::EOpConvDoubleToBool:
5851 zero = builder.makeDoubleConstant(0.0);
5852 zero = makeSmearedConstant(zero, vectorSize);
5853 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5854
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005855 case glslang::EOpConvFloat16ToBool:
5856 zero = builder.makeFloat16Constant(0.0F);
5857 zero = makeSmearedConstant(zero, vectorSize);
5858 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005859
John Kessenich140f3df2015-06-26 16:58:36 -06005860 case glslang::EOpConvBoolToFloat:
5861 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005862 zero = builder.makeFloatConstant(0.0F);
5863 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005864 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005865
John Kessenich140f3df2015-06-26 16:58:36 -06005866 case glslang::EOpConvBoolToDouble:
5867 convOp = spv::OpSelect;
5868 zero = builder.makeDoubleConstant(0.0);
5869 one = builder.makeDoubleConstant(1.0);
5870 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005871
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005872 case glslang::EOpConvBoolToFloat16:
5873 convOp = spv::OpSelect;
5874 zero = builder.makeFloat16Constant(0.0F);
5875 one = builder.makeFloat16Constant(1.0F);
5876 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005877
5878 case glslang::EOpConvBoolToInt8:
5879 zero = builder.makeInt8Constant(0);
5880 one = builder.makeInt8Constant(1);
5881 convOp = spv::OpSelect;
5882 break;
5883
5884 case glslang::EOpConvBoolToUint8:
5885 zero = builder.makeUint8Constant(0);
5886 one = builder.makeUint8Constant(1);
5887 convOp = spv::OpSelect;
5888 break;
5889
5890 case glslang::EOpConvBoolToInt16:
5891 zero = builder.makeInt16Constant(0);
5892 one = builder.makeInt16Constant(1);
5893 convOp = spv::OpSelect;
5894 break;
5895
5896 case glslang::EOpConvBoolToUint16:
5897 zero = builder.makeUint16Constant(0);
5898 one = builder.makeUint16Constant(1);
5899 convOp = spv::OpSelect;
5900 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005901
John Kessenich140f3df2015-06-26 16:58:36 -06005902 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005903 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005904 if (op == glslang::EOpConvBoolToInt64)
5905 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005906 else
5907 zero = builder.makeIntConstant(0);
5908
5909 if (op == glslang::EOpConvBoolToInt64)
5910 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005911 else
5912 one = builder.makeIntConstant(1);
5913
John Kessenich140f3df2015-06-26 16:58:36 -06005914 convOp = spv::OpSelect;
5915 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005916
John Kessenich140f3df2015-06-26 16:58:36 -06005917 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005918 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005919 if (op == glslang::EOpConvBoolToUint64)
5920 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005921 else
5922 zero = builder.makeUintConstant(0);
5923
5924 if (op == glslang::EOpConvBoolToUint64)
5925 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005926 else
5927 one = builder.makeUintConstant(1);
5928
John Kessenich140f3df2015-06-26 16:58:36 -06005929 convOp = spv::OpSelect;
5930 break;
5931
John Kessenich66011cb2018-03-06 16:12:04 -07005932 case glslang::EOpConvInt8ToFloat16:
5933 case glslang::EOpConvInt8ToFloat:
5934 case glslang::EOpConvInt8ToDouble:
5935 case glslang::EOpConvInt16ToFloat16:
5936 case glslang::EOpConvInt16ToFloat:
5937 case glslang::EOpConvInt16ToDouble:
5938 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005939 case glslang::EOpConvIntToFloat:
5940 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005941 case glslang::EOpConvInt64ToFloat:
5942 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005943 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005944 convOp = spv::OpConvertSToF;
5945 break;
5946
John Kessenich66011cb2018-03-06 16:12:04 -07005947 case glslang::EOpConvUint8ToFloat16:
5948 case glslang::EOpConvUint8ToFloat:
5949 case glslang::EOpConvUint8ToDouble:
5950 case glslang::EOpConvUint16ToFloat16:
5951 case glslang::EOpConvUint16ToFloat:
5952 case glslang::EOpConvUint16ToDouble:
5953 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005954 case glslang::EOpConvUintToFloat:
5955 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005956 case glslang::EOpConvUint64ToFloat:
5957 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005958 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005959 convOp = spv::OpConvertUToF;
5960 break;
5961
5962 case glslang::EOpConvDoubleToFloat:
5963 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005964 case glslang::EOpConvDoubleToFloat16:
5965 case glslang::EOpConvFloat16ToDouble:
5966 case glslang::EOpConvFloatToFloat16:
5967 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005968 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005969 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005970 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005971 break;
5972
John Kessenich66011cb2018-03-06 16:12:04 -07005973 case glslang::EOpConvFloat16ToInt8:
5974 case glslang::EOpConvFloatToInt8:
5975 case glslang::EOpConvDoubleToInt8:
5976 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005977 case glslang::EOpConvFloatToInt16:
5978 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005979 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005980 case glslang::EOpConvFloatToInt:
5981 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005982 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005983 case glslang::EOpConvFloatToInt64:
5984 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005985 convOp = spv::OpConvertFToS;
5986 break;
5987
John Kessenich66011cb2018-03-06 16:12:04 -07005988 case glslang::EOpConvUint8ToInt8:
5989 case glslang::EOpConvInt8ToUint8:
5990 case glslang::EOpConvUint16ToInt16:
5991 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005992 case glslang::EOpConvUintToInt:
5993 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005994 case glslang::EOpConvUint64ToInt64:
5995 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005996 if (builder.isInSpecConstCodeGenMode()) {
5997 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005998 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5999 zero = builder.makeUint8Constant(0);
6000 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08006001 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006002 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
6003 zero = builder.makeUint64Constant(0);
6004 } else {
Rex Xucabbb782017-03-24 13:41:14 +08006005 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006006 }
qining189b2032016-04-12 23:16:20 -04006007 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04006008 // Use OpIAdd, instead of OpBitcast to do the conversion when
6009 // generating for OpSpecConstantOp instruction.
6010 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6011 }
6012 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06006013 convOp = spv::OpBitcast;
6014 break;
6015
John Kessenich66011cb2018-03-06 16:12:04 -07006016 case glslang::EOpConvFloat16ToUint8:
6017 case glslang::EOpConvFloatToUint8:
6018 case glslang::EOpConvDoubleToUint8:
6019 case glslang::EOpConvFloat16ToUint16:
6020 case glslang::EOpConvFloatToUint16:
6021 case glslang::EOpConvDoubleToUint16:
6022 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006023 case glslang::EOpConvFloatToUint:
6024 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006025 case glslang::EOpConvFloatToUint64:
6026 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006027 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006028 convOp = spv::OpConvertFToU;
6029 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006030
John Kessenich66011cb2018-03-06 16:12:04 -07006031 case glslang::EOpConvInt8ToInt16:
6032 case glslang::EOpConvInt8ToInt:
6033 case glslang::EOpConvInt8ToInt64:
6034 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006035 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006036 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006037 case glslang::EOpConvIntToInt8:
6038 case glslang::EOpConvIntToInt16:
6039 case glslang::EOpConvIntToInt64:
6040 case glslang::EOpConvInt64ToInt8:
6041 case glslang::EOpConvInt64ToInt16:
6042 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006043 convOp = spv::OpSConvert;
6044 break;
6045
John Kessenich66011cb2018-03-06 16:12:04 -07006046 case glslang::EOpConvUint8ToUint16:
6047 case glslang::EOpConvUint8ToUint:
6048 case glslang::EOpConvUint8ToUint64:
6049 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006050 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006051 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006052 case glslang::EOpConvUintToUint8:
6053 case glslang::EOpConvUintToUint16:
6054 case glslang::EOpConvUintToUint64:
6055 case glslang::EOpConvUint64ToUint8:
6056 case glslang::EOpConvUint64ToUint16:
6057 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006058 convOp = spv::OpUConvert;
6059 break;
6060
John Kessenich66011cb2018-03-06 16:12:04 -07006061 case glslang::EOpConvInt8ToUint16:
6062 case glslang::EOpConvInt8ToUint:
6063 case glslang::EOpConvInt8ToUint64:
6064 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006065 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006066 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006067 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006068 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006069 case glslang::EOpConvIntToUint64:
6070 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006071 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006072 case glslang::EOpConvInt64ToUint:
6073 case glslang::EOpConvUint8ToInt16:
6074 case glslang::EOpConvUint8ToInt:
6075 case glslang::EOpConvUint8ToInt64:
6076 case glslang::EOpConvUint16ToInt8:
6077 case glslang::EOpConvUint16ToInt:
6078 case glslang::EOpConvUint16ToInt64:
6079 case glslang::EOpConvUintToInt8:
6080 case glslang::EOpConvUintToInt16:
6081 case glslang::EOpConvUintToInt64:
6082 case glslang::EOpConvUint64ToInt8:
6083 case glslang::EOpConvUint64ToInt16:
6084 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006085 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006086 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006087
6088 if (builder.isInSpecConstCodeGenMode()) {
6089 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006090 switch(op) {
6091 case glslang::EOpConvInt16ToUint8:
6092 case glslang::EOpConvIntToUint8:
6093 case glslang::EOpConvInt64ToUint8:
6094 case glslang::EOpConvUint16ToInt8:
6095 case glslang::EOpConvUintToInt8:
6096 case glslang::EOpConvUint64ToInt8:
6097 zero = builder.makeUint8Constant(0);
6098 break;
6099 case glslang::EOpConvInt8ToUint16:
6100 case glslang::EOpConvIntToUint16:
6101 case glslang::EOpConvInt64ToUint16:
6102 case glslang::EOpConvUint8ToInt16:
6103 case glslang::EOpConvUintToInt16:
6104 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006105 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006106 break;
6107 case glslang::EOpConvInt8ToUint:
6108 case glslang::EOpConvInt16ToUint:
6109 case glslang::EOpConvInt64ToUint:
6110 case glslang::EOpConvUint8ToInt:
6111 case glslang::EOpConvUint16ToInt:
6112 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006113 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006114 break;
6115 case glslang::EOpConvInt8ToUint64:
6116 case glslang::EOpConvInt16ToUint64:
6117 case glslang::EOpConvIntToUint64:
6118 case glslang::EOpConvUint8ToInt64:
6119 case glslang::EOpConvUint16ToInt64:
6120 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006121 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006122 break;
6123 default:
6124 assert(false && "Default missing");
6125 break;
6126 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006127 zero = makeSmearedConstant(zero, vectorSize);
6128 // Use OpIAdd, instead of OpBitcast to do the conversion when
6129 // generating for OpSpecConstantOp instruction.
6130 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6131 }
6132 // For normal run-time conversion instruction, use OpBitcast.
6133 convOp = spv::OpBitcast;
6134 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006135 case glslang::EOpConvUint64ToPtr:
6136 convOp = spv::OpConvertUToPtr;
6137 break;
6138 case glslang::EOpConvPtrToUint64:
6139 convOp = spv::OpConvertPtrToU;
6140 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006141 default:
6142 break;
6143 }
6144
6145 spv::Id result = 0;
6146 if (convOp == spv::OpNop)
6147 return result;
6148
6149 if (convOp == spv::OpSelect) {
6150 zero = makeSmearedConstant(zero, vectorSize);
6151 one = makeSmearedConstant(one, vectorSize);
6152 result = builder.createTriOp(convOp, destType, operand, one, zero);
6153 } else
6154 result = builder.createUnaryOp(convOp, destType, operand);
6155
John Kessenichead86222018-03-28 18:01:20 -06006156 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006157 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006158 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006159}
6160
6161spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6162{
6163 if (vectorSize == 0)
6164 return constant;
6165
6166 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6167 std::vector<spv::Id> components;
6168 for (int c = 0; c < vectorSize; ++c)
6169 components.push_back(constant);
6170 return builder.makeCompositeConstant(vectorTypeId, components);
6171}
6172
John Kessenich426394d2015-07-23 10:22:48 -06006173// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07006174spv::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 -06006175{
6176 spv::Op opCode = spv::OpNop;
6177
6178 switch (op) {
6179 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006180 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006181 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006182 opCode = spv::OpAtomicIAdd;
6183 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006184 case glslang::EOpAtomicCounterSubtract:
6185 opCode = spv::OpAtomicISub;
6186 break;
John Kessenich426394d2015-07-23 10:22:48 -06006187 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006188 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006189 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006190 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006191 break;
6192 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006193 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006194 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006195 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006196 break;
6197 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006198 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006199 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006200 opCode = spv::OpAtomicAnd;
6201 break;
6202 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006203 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006204 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006205 opCode = spv::OpAtomicOr;
6206 break;
6207 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006208 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006209 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006210 opCode = spv::OpAtomicXor;
6211 break;
6212 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006213 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006214 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006215 opCode = spv::OpAtomicExchange;
6216 break;
6217 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006218 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006219 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006220 opCode = spv::OpAtomicCompareExchange;
6221 break;
6222 case glslang::EOpAtomicCounterIncrement:
6223 opCode = spv::OpAtomicIIncrement;
6224 break;
6225 case glslang::EOpAtomicCounterDecrement:
6226 opCode = spv::OpAtomicIDecrement;
6227 break;
6228 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006229 case glslang::EOpImageAtomicLoad:
6230 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006231 opCode = spv::OpAtomicLoad;
6232 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006233 case glslang::EOpAtomicStore:
6234 case glslang::EOpImageAtomicStore:
6235 opCode = spv::OpAtomicStore;
6236 break;
John Kessenich426394d2015-07-23 10:22:48 -06006237 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006238 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006239 break;
6240 }
6241
Rex Xue8fe8b02017-09-26 15:42:56 +08006242 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6243 builder.addCapability(spv::CapabilityInt64Atomics);
6244
John Kessenich426394d2015-07-23 10:22:48 -06006245 // Sort out the operands
6246 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006247 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006248 // - compare-exchange swaps the value and comparator
6249 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006250 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006251 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6252 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6253 spv::Id scopeId;
6254 if (glslangIntermediate->usingVulkanMemoryModel()) {
6255 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6256 } else {
6257 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6258 }
6259 // semantics default to relaxed
6260 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
6261 spv::Id semanticsId2 = semanticsId;
6262
6263 pointerId = operands[0];
6264 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6265 // no additional operands
6266 } else if (opCode == spv::OpAtomicCompareExchange) {
6267 compareId = operands[1];
6268 valueId = operands[2];
6269 if (operands.size() > 3) {
6270 scopeId = operands[3];
6271 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6272 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6273 }
6274 } else if (opCode == spv::OpAtomicLoad) {
6275 if (operands.size() > 1) {
6276 scopeId = operands[1];
6277 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6278 }
6279 } else {
6280 // atomic store or RMW
6281 valueId = operands[1];
6282 if (operands.size() > 2) {
6283 scopeId = operands[2];
6284 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6285 }
Rex Xu04db3f52015-09-16 11:44:02 +08006286 }
John Kessenich426394d2015-07-23 10:22:48 -06006287
Jeff Bolz36831c92018-09-05 10:11:41 -05006288 // Check for capabilities
6289 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
6290 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6291 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6292 }
John Kessenich426394d2015-07-23 10:22:48 -06006293
Jeff Bolz36831c92018-09-05 10:11:41 -05006294 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6295 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6296 }
John Kessenich48d6e792017-10-06 21:21:48 -06006297
Jeff Bolz36831c92018-09-05 10:11:41 -05006298 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6299 spvAtomicOperands.push_back(pointerId);
6300 spvAtomicOperands.push_back(scopeId);
6301 spvAtomicOperands.push_back(semanticsId);
6302 if (opCode == spv::OpAtomicCompareExchange) {
6303 spvAtomicOperands.push_back(semanticsId2);
6304 spvAtomicOperands.push_back(valueId);
6305 spvAtomicOperands.push_back(compareId);
6306 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6307 spvAtomicOperands.push_back(valueId);
6308 }
John Kessenich48d6e792017-10-06 21:21:48 -06006309
Jeff Bolz36831c92018-09-05 10:11:41 -05006310 if (opCode == spv::OpAtomicStore) {
6311 builder.createNoResultOp(opCode, spvAtomicOperands);
6312 return 0;
6313 } else {
6314 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6315
6316 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6317 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6318 if (op == glslang::EOpAtomicCounterDecrement)
6319 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6320
6321 return resultId;
6322 }
John Kessenich426394d2015-07-23 10:22:48 -06006323}
6324
John Kessenich91cef522016-05-05 16:45:40 -06006325// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006326spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006327{
Corentin Walleze7061422018-08-08 15:20:15 +02006328#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006329 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6330 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006331#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006332
Rex Xu51596642016-09-21 18:56:12 +08006333 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006334 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006335 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6336
chaocf200da82016-12-20 12:44:35 -08006337 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6338 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006339 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6340 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006341 } else if (op == glslang::EOpAnyInvocation ||
6342 op == glslang::EOpAllInvocations ||
6343 op == glslang::EOpAllInvocationsEqual) {
6344 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6345 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006346 } else {
6347 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006348#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006349 if (op == glslang::EOpMinInvocationsNonUniform ||
6350 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006351 op == glslang::EOpAddInvocationsNonUniform ||
6352 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6353 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6354 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6355 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6356 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6357 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006358 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006359#endif
Rex Xu51596642016-09-21 18:56:12 +08006360
Rex Xu9d93a232016-05-05 12:30:44 +08006361#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006362 switch (op) {
6363 case glslang::EOpMinInvocations:
6364 case glslang::EOpMaxInvocations:
6365 case glslang::EOpAddInvocations:
6366 case glslang::EOpMinInvocationsNonUniform:
6367 case glslang::EOpMaxInvocationsNonUniform:
6368 case glslang::EOpAddInvocationsNonUniform:
6369 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006370 break;
6371 case glslang::EOpMinInvocationsInclusiveScan:
6372 case glslang::EOpMaxInvocationsInclusiveScan:
6373 case glslang::EOpAddInvocationsInclusiveScan:
6374 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6375 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6376 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6377 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006378 break;
6379 case glslang::EOpMinInvocationsExclusiveScan:
6380 case glslang::EOpMaxInvocationsExclusiveScan:
6381 case glslang::EOpAddInvocationsExclusiveScan:
6382 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6383 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6384 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6385 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006386 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006387 default:
6388 break;
Rex Xu430ef402016-10-14 17:22:23 +08006389 }
John Kessenich149afc32018-08-14 13:31:43 -06006390 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6391 spvGroupOperands.push_back(scope);
6392 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006393 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006394 spvGroupOperands.push_back(groupOp);
6395 }
Rex Xu9d93a232016-05-05 12:30:44 +08006396#endif
Rex Xu51596642016-09-21 18:56:12 +08006397 }
6398
John Kessenich149afc32018-08-14 13:31:43 -06006399 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6400 spv::IdImmediate op = { true, *opIt };
6401 spvGroupOperands.push_back(op);
6402 }
John Kessenich91cef522016-05-05 16:45:40 -06006403
6404 switch (op) {
6405 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006406 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006407 break;
John Kessenich91cef522016-05-05 16:45:40 -06006408 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006409 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006410 break;
John Kessenich91cef522016-05-05 16:45:40 -06006411 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006412 opCode = spv::OpSubgroupAllEqualKHR;
6413 break;
Rex Xu51596642016-09-21 18:56:12 +08006414 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006415 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006416 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006417 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006418 break;
6419 case glslang::EOpReadFirstInvocation:
6420 opCode = spv::OpSubgroupFirstInvocationKHR;
6421 break;
6422 case glslang::EOpBallot:
6423 {
6424 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6425 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6426 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6427 //
6428 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6429 //
6430 spv::Id uintType = builder.makeUintType(32);
6431 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6432 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6433
6434 std::vector<spv::Id> components;
6435 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6436 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6437
6438 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6439 return builder.createUnaryOp(spv::OpBitcast, typeId,
6440 builder.createCompositeConstruct(uvec2Type, components));
6441 }
6442
Rex Xu9d93a232016-05-05 12:30:44 +08006443#ifdef AMD_EXTENSIONS
6444 case glslang::EOpMinInvocations:
6445 case glslang::EOpMaxInvocations:
6446 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006447 case glslang::EOpMinInvocationsInclusiveScan:
6448 case glslang::EOpMaxInvocationsInclusiveScan:
6449 case glslang::EOpAddInvocationsInclusiveScan:
6450 case glslang::EOpMinInvocationsExclusiveScan:
6451 case glslang::EOpMaxInvocationsExclusiveScan:
6452 case glslang::EOpAddInvocationsExclusiveScan:
6453 if (op == glslang::EOpMinInvocations ||
6454 op == glslang::EOpMinInvocationsInclusiveScan ||
6455 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006456 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006457 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006458 else {
6459 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006460 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006461 else
Rex Xu51596642016-09-21 18:56:12 +08006462 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006463 }
Rex Xu430ef402016-10-14 17:22:23 +08006464 } else if (op == glslang::EOpMaxInvocations ||
6465 op == glslang::EOpMaxInvocationsInclusiveScan ||
6466 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006467 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006468 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006469 else {
6470 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006471 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006472 else
Rex Xu51596642016-09-21 18:56:12 +08006473 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006474 }
6475 } else {
6476 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006477 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006478 else
Rex Xu51596642016-09-21 18:56:12 +08006479 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006480 }
6481
Rex Xu2bbbe062016-08-23 15:41:05 +08006482 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006483 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006484
6485 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006486 case glslang::EOpMinInvocationsNonUniform:
6487 case glslang::EOpMaxInvocationsNonUniform:
6488 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006489 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6490 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6491 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6492 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6493 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6494 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6495 if (op == glslang::EOpMinInvocationsNonUniform ||
6496 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6497 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006498 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006499 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006500 else {
6501 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006502 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006503 else
Rex Xu51596642016-09-21 18:56:12 +08006504 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006505 }
6506 }
Rex Xu430ef402016-10-14 17:22:23 +08006507 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6508 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6509 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006510 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006511 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006512 else {
6513 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006514 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006515 else
Rex Xu51596642016-09-21 18:56:12 +08006516 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006517 }
6518 }
6519 else {
6520 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006521 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006522 else
Rex Xu51596642016-09-21 18:56:12 +08006523 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006524 }
6525
Rex Xu2bbbe062016-08-23 15:41:05 +08006526 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006527 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006528
6529 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006530#endif
John Kessenich91cef522016-05-05 16:45:40 -06006531 default:
6532 logger->missingFunctionality("invocation operation");
6533 return spv::NoResult;
6534 }
Rex Xu51596642016-09-21 18:56:12 +08006535
6536 assert(opCode != spv::OpNop);
6537 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006538}
6539
Rex Xu2bbbe062016-08-23 15:41:05 +08006540// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006541spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6542 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006543{
Rex Xub7072052016-09-26 15:53:40 +08006544#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006545 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6546 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006547 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006548 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006549 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6550 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6551 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006552#else
6553 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6554 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006555 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6556 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006557#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006558
6559 // Handle group invocation operations scalar by scalar.
6560 // The result type is the same type as the original type.
6561 // The algorithm is to:
6562 // - break the vector into scalars
6563 // - apply the operation to each scalar
6564 // - make a vector out the scalar results
6565
6566 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006567 int numComponents = builder.getNumComponents(operands[0]);
6568 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006569 std::vector<spv::Id> results;
6570
6571 // do each scalar op
6572 for (int comp = 0; comp < numComponents; ++comp) {
6573 std::vector<unsigned int> indexes;
6574 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006575 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6576 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006577 if (op == spv::OpSubgroupReadInvocationKHR) {
6578 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006579 spv::IdImmediate operand = { true, operands[1] };
6580 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006581 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006582 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6583 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006584 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006585 spv::IdImmediate operand = { true, operands[1] };
6586 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006587 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006588 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6589 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006590 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006591 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006592 spvGroupOperands.push_back(scalar);
6593 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006594
Rex Xub7072052016-09-26 15:53:40 +08006595 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006596 }
6597
6598 // put the pieces together
6599 return builder.createCompositeConstruct(typeId, results);
6600}
Rex Xu2bbbe062016-08-23 15:41:05 +08006601
John Kessenich66011cb2018-03-06 16:12:04 -07006602// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006603spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6604 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006605{
6606 // Add the required capabilities.
6607 switch (op) {
6608 case glslang::EOpSubgroupElect:
6609 builder.addCapability(spv::CapabilityGroupNonUniform);
6610 break;
6611 case glslang::EOpSubgroupAll:
6612 case glslang::EOpSubgroupAny:
6613 case glslang::EOpSubgroupAllEqual:
6614 builder.addCapability(spv::CapabilityGroupNonUniform);
6615 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6616 break;
6617 case glslang::EOpSubgroupBroadcast:
6618 case glslang::EOpSubgroupBroadcastFirst:
6619 case glslang::EOpSubgroupBallot:
6620 case glslang::EOpSubgroupInverseBallot:
6621 case glslang::EOpSubgroupBallotBitExtract:
6622 case glslang::EOpSubgroupBallotBitCount:
6623 case glslang::EOpSubgroupBallotInclusiveBitCount:
6624 case glslang::EOpSubgroupBallotExclusiveBitCount:
6625 case glslang::EOpSubgroupBallotFindLSB:
6626 case glslang::EOpSubgroupBallotFindMSB:
6627 builder.addCapability(spv::CapabilityGroupNonUniform);
6628 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6629 break;
6630 case glslang::EOpSubgroupShuffle:
6631 case glslang::EOpSubgroupShuffleXor:
6632 builder.addCapability(spv::CapabilityGroupNonUniform);
6633 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6634 break;
6635 case glslang::EOpSubgroupShuffleUp:
6636 case glslang::EOpSubgroupShuffleDown:
6637 builder.addCapability(spv::CapabilityGroupNonUniform);
6638 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6639 break;
6640 case glslang::EOpSubgroupAdd:
6641 case glslang::EOpSubgroupMul:
6642 case glslang::EOpSubgroupMin:
6643 case glslang::EOpSubgroupMax:
6644 case glslang::EOpSubgroupAnd:
6645 case glslang::EOpSubgroupOr:
6646 case glslang::EOpSubgroupXor:
6647 case glslang::EOpSubgroupInclusiveAdd:
6648 case glslang::EOpSubgroupInclusiveMul:
6649 case glslang::EOpSubgroupInclusiveMin:
6650 case glslang::EOpSubgroupInclusiveMax:
6651 case glslang::EOpSubgroupInclusiveAnd:
6652 case glslang::EOpSubgroupInclusiveOr:
6653 case glslang::EOpSubgroupInclusiveXor:
6654 case glslang::EOpSubgroupExclusiveAdd:
6655 case glslang::EOpSubgroupExclusiveMul:
6656 case glslang::EOpSubgroupExclusiveMin:
6657 case glslang::EOpSubgroupExclusiveMax:
6658 case glslang::EOpSubgroupExclusiveAnd:
6659 case glslang::EOpSubgroupExclusiveOr:
6660 case glslang::EOpSubgroupExclusiveXor:
6661 builder.addCapability(spv::CapabilityGroupNonUniform);
6662 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6663 break;
6664 case glslang::EOpSubgroupClusteredAdd:
6665 case glslang::EOpSubgroupClusteredMul:
6666 case glslang::EOpSubgroupClusteredMin:
6667 case glslang::EOpSubgroupClusteredMax:
6668 case glslang::EOpSubgroupClusteredAnd:
6669 case glslang::EOpSubgroupClusteredOr:
6670 case glslang::EOpSubgroupClusteredXor:
6671 builder.addCapability(spv::CapabilityGroupNonUniform);
6672 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6673 break;
6674 case glslang::EOpSubgroupQuadBroadcast:
6675 case glslang::EOpSubgroupQuadSwapHorizontal:
6676 case glslang::EOpSubgroupQuadSwapVertical:
6677 case glslang::EOpSubgroupQuadSwapDiagonal:
6678 builder.addCapability(spv::CapabilityGroupNonUniform);
6679 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6680 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006681#ifdef NV_EXTENSIONS
6682 case glslang::EOpSubgroupPartitionedAdd:
6683 case glslang::EOpSubgroupPartitionedMul:
6684 case glslang::EOpSubgroupPartitionedMin:
6685 case glslang::EOpSubgroupPartitionedMax:
6686 case glslang::EOpSubgroupPartitionedAnd:
6687 case glslang::EOpSubgroupPartitionedOr:
6688 case glslang::EOpSubgroupPartitionedXor:
6689 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6690 case glslang::EOpSubgroupPartitionedInclusiveMul:
6691 case glslang::EOpSubgroupPartitionedInclusiveMin:
6692 case glslang::EOpSubgroupPartitionedInclusiveMax:
6693 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6694 case glslang::EOpSubgroupPartitionedInclusiveOr:
6695 case glslang::EOpSubgroupPartitionedInclusiveXor:
6696 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6697 case glslang::EOpSubgroupPartitionedExclusiveMul:
6698 case glslang::EOpSubgroupPartitionedExclusiveMin:
6699 case glslang::EOpSubgroupPartitionedExclusiveMax:
6700 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6701 case glslang::EOpSubgroupPartitionedExclusiveOr:
6702 case glslang::EOpSubgroupPartitionedExclusiveXor:
6703 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6704 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6705 break;
6706#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006707 default: assert(0 && "Unhandled subgroup operation!");
6708 }
6709
6710 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6711 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6712 const bool isBool = typeProxy == glslang::EbtBool;
6713
6714 spv::Op opCode = spv::OpNop;
6715
6716 // Figure out which opcode to use.
6717 switch (op) {
6718 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6719 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6720 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6721 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6722 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6723 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6724 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6725 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6726 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6727 case glslang::EOpSubgroupBallotBitCount:
6728 case glslang::EOpSubgroupBallotInclusiveBitCount:
6729 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6730 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6731 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6732 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6733 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6734 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6735 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6736 case glslang::EOpSubgroupAdd:
6737 case glslang::EOpSubgroupInclusiveAdd:
6738 case glslang::EOpSubgroupExclusiveAdd:
6739 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006740#ifdef NV_EXTENSIONS
6741 case glslang::EOpSubgroupPartitionedAdd:
6742 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6743 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6744#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006745 if (isFloat) {
6746 opCode = spv::OpGroupNonUniformFAdd;
6747 } else {
6748 opCode = spv::OpGroupNonUniformIAdd;
6749 }
6750 break;
6751 case glslang::EOpSubgroupMul:
6752 case glslang::EOpSubgroupInclusiveMul:
6753 case glslang::EOpSubgroupExclusiveMul:
6754 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006755#ifdef NV_EXTENSIONS
6756 case glslang::EOpSubgroupPartitionedMul:
6757 case glslang::EOpSubgroupPartitionedInclusiveMul:
6758 case glslang::EOpSubgroupPartitionedExclusiveMul:
6759#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006760 if (isFloat) {
6761 opCode = spv::OpGroupNonUniformFMul;
6762 } else {
6763 opCode = spv::OpGroupNonUniformIMul;
6764 }
6765 break;
6766 case glslang::EOpSubgroupMin:
6767 case glslang::EOpSubgroupInclusiveMin:
6768 case glslang::EOpSubgroupExclusiveMin:
6769 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006770#ifdef NV_EXTENSIONS
6771 case glslang::EOpSubgroupPartitionedMin:
6772 case glslang::EOpSubgroupPartitionedInclusiveMin:
6773 case glslang::EOpSubgroupPartitionedExclusiveMin:
6774#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006775 if (isFloat) {
6776 opCode = spv::OpGroupNonUniformFMin;
6777 } else if (isUnsigned) {
6778 opCode = spv::OpGroupNonUniformUMin;
6779 } else {
6780 opCode = spv::OpGroupNonUniformSMin;
6781 }
6782 break;
6783 case glslang::EOpSubgroupMax:
6784 case glslang::EOpSubgroupInclusiveMax:
6785 case glslang::EOpSubgroupExclusiveMax:
6786 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006787#ifdef NV_EXTENSIONS
6788 case glslang::EOpSubgroupPartitionedMax:
6789 case glslang::EOpSubgroupPartitionedInclusiveMax:
6790 case glslang::EOpSubgroupPartitionedExclusiveMax:
6791#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006792 if (isFloat) {
6793 opCode = spv::OpGroupNonUniformFMax;
6794 } else if (isUnsigned) {
6795 opCode = spv::OpGroupNonUniformUMax;
6796 } else {
6797 opCode = spv::OpGroupNonUniformSMax;
6798 }
6799 break;
6800 case glslang::EOpSubgroupAnd:
6801 case glslang::EOpSubgroupInclusiveAnd:
6802 case glslang::EOpSubgroupExclusiveAnd:
6803 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006804#ifdef NV_EXTENSIONS
6805 case glslang::EOpSubgroupPartitionedAnd:
6806 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6807 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6808#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006809 if (isBool) {
6810 opCode = spv::OpGroupNonUniformLogicalAnd;
6811 } else {
6812 opCode = spv::OpGroupNonUniformBitwiseAnd;
6813 }
6814 break;
6815 case glslang::EOpSubgroupOr:
6816 case glslang::EOpSubgroupInclusiveOr:
6817 case glslang::EOpSubgroupExclusiveOr:
6818 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006819#ifdef NV_EXTENSIONS
6820 case glslang::EOpSubgroupPartitionedOr:
6821 case glslang::EOpSubgroupPartitionedInclusiveOr:
6822 case glslang::EOpSubgroupPartitionedExclusiveOr:
6823#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006824 if (isBool) {
6825 opCode = spv::OpGroupNonUniformLogicalOr;
6826 } else {
6827 opCode = spv::OpGroupNonUniformBitwiseOr;
6828 }
6829 break;
6830 case glslang::EOpSubgroupXor:
6831 case glslang::EOpSubgroupInclusiveXor:
6832 case glslang::EOpSubgroupExclusiveXor:
6833 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006834#ifdef NV_EXTENSIONS
6835 case glslang::EOpSubgroupPartitionedXor:
6836 case glslang::EOpSubgroupPartitionedInclusiveXor:
6837 case glslang::EOpSubgroupPartitionedExclusiveXor:
6838#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006839 if (isBool) {
6840 opCode = spv::OpGroupNonUniformLogicalXor;
6841 } else {
6842 opCode = spv::OpGroupNonUniformBitwiseXor;
6843 }
6844 break;
6845 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6846 case glslang::EOpSubgroupQuadSwapHorizontal:
6847 case glslang::EOpSubgroupQuadSwapVertical:
6848 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6849 default: assert(0 && "Unhandled subgroup operation!");
6850 }
6851
John Kessenich149afc32018-08-14 13:31:43 -06006852 // get the right Group Operation
6853 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006854 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006855 default:
6856 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006857 case glslang::EOpSubgroupBallotBitCount:
6858 case glslang::EOpSubgroupAdd:
6859 case glslang::EOpSubgroupMul:
6860 case glslang::EOpSubgroupMin:
6861 case glslang::EOpSubgroupMax:
6862 case glslang::EOpSubgroupAnd:
6863 case glslang::EOpSubgroupOr:
6864 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006865 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006866 break;
6867 case glslang::EOpSubgroupBallotInclusiveBitCount:
6868 case glslang::EOpSubgroupInclusiveAdd:
6869 case glslang::EOpSubgroupInclusiveMul:
6870 case glslang::EOpSubgroupInclusiveMin:
6871 case glslang::EOpSubgroupInclusiveMax:
6872 case glslang::EOpSubgroupInclusiveAnd:
6873 case glslang::EOpSubgroupInclusiveOr:
6874 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006875 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006876 break;
6877 case glslang::EOpSubgroupBallotExclusiveBitCount:
6878 case glslang::EOpSubgroupExclusiveAdd:
6879 case glslang::EOpSubgroupExclusiveMul:
6880 case glslang::EOpSubgroupExclusiveMin:
6881 case glslang::EOpSubgroupExclusiveMax:
6882 case glslang::EOpSubgroupExclusiveAnd:
6883 case glslang::EOpSubgroupExclusiveOr:
6884 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006885 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006886 break;
6887 case glslang::EOpSubgroupClusteredAdd:
6888 case glslang::EOpSubgroupClusteredMul:
6889 case glslang::EOpSubgroupClusteredMin:
6890 case glslang::EOpSubgroupClusteredMax:
6891 case glslang::EOpSubgroupClusteredAnd:
6892 case glslang::EOpSubgroupClusteredOr:
6893 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006894 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006895 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006896#ifdef NV_EXTENSIONS
6897 case glslang::EOpSubgroupPartitionedAdd:
6898 case glslang::EOpSubgroupPartitionedMul:
6899 case glslang::EOpSubgroupPartitionedMin:
6900 case glslang::EOpSubgroupPartitionedMax:
6901 case glslang::EOpSubgroupPartitionedAnd:
6902 case glslang::EOpSubgroupPartitionedOr:
6903 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006904 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006905 break;
6906 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6907 case glslang::EOpSubgroupPartitionedInclusiveMul:
6908 case glslang::EOpSubgroupPartitionedInclusiveMin:
6909 case glslang::EOpSubgroupPartitionedInclusiveMax:
6910 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6911 case glslang::EOpSubgroupPartitionedInclusiveOr:
6912 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006913 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006914 break;
6915 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6916 case glslang::EOpSubgroupPartitionedExclusiveMul:
6917 case glslang::EOpSubgroupPartitionedExclusiveMin:
6918 case glslang::EOpSubgroupPartitionedExclusiveMax:
6919 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6920 case glslang::EOpSubgroupPartitionedExclusiveOr:
6921 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006922 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006923 break;
6924#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006925 }
6926
John Kessenich149afc32018-08-14 13:31:43 -06006927 // build the instruction
6928 std::vector<spv::IdImmediate> spvGroupOperands;
6929
6930 // Every operation begins with the Execution Scope operand.
6931 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6932 spvGroupOperands.push_back(executionScope);
6933
6934 // Next, for all operations that use a Group Operation, push that as an operand.
6935 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006936 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006937 spvGroupOperands.push_back(groupOperand);
6938 }
6939
John Kessenich66011cb2018-03-06 16:12:04 -07006940 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006941 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6942 spv::IdImmediate operand = { true, *opIt };
6943 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006944 }
6945
6946 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006947 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006948 switch (op) {
6949 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006950 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6951 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6952 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6953 }
6954 if (directionId != spv::NoResult) {
6955 spv::IdImmediate direction = { true, directionId };
6956 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006957 }
6958
6959 return builder.createOp(opCode, typeId, spvGroupOperands);
6960}
6961
John Kessenich5e4b1242015-08-06 22:53:06 -06006962spv::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 -06006963{
John Kessenich66011cb2018-03-06 16:12:04 -07006964 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6965 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006966
John Kessenich140f3df2015-06-26 16:58:36 -06006967 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006968 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006969 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006970 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006971 spv::Id typeId0 = 0;
6972 if (consumedOperands > 0)
6973 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006974 spv::Id typeId1 = 0;
6975 if (consumedOperands > 1)
6976 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006977 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006978
6979 switch (op) {
6980 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006981 if (isFloat)
6982 libCall = spv::GLSLstd450FMin;
6983 else if (isUnsigned)
6984 libCall = spv::GLSLstd450UMin;
6985 else
6986 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006987 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006988 break;
6989 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006990 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006991 break;
6992 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006993 if (isFloat)
6994 libCall = spv::GLSLstd450FMax;
6995 else if (isUnsigned)
6996 libCall = spv::GLSLstd450UMax;
6997 else
6998 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006999 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007000 break;
7001 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06007002 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06007003 break;
7004 case glslang::EOpDot:
7005 opCode = spv::OpDot;
7006 break;
7007 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06007008 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06007009 break;
7010
7011 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06007012 if (isFloat)
7013 libCall = spv::GLSLstd450FClamp;
7014 else if (isUnsigned)
7015 libCall = spv::GLSLstd450UClamp;
7016 else
7017 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007018 builder.promoteScalar(precision, operands.front(), operands[1]);
7019 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007020 break;
7021 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007022 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7023 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007024 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007025 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007026 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007027 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007028 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007029 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007030 break;
7031 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007032 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007033 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007034 break;
7035 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007036 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007037 builder.promoteScalar(precision, operands[0], operands[2]);
7038 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007039 break;
7040
7041 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007042 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007043 break;
7044 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007045 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007046 break;
7047 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007048 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007049 break;
7050 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007051 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007052 break;
7053 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007054 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007055 break;
Rex Xu7a26c172015-12-08 17:12:09 +08007056 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007057#ifdef AMD_EXTENSIONS
7058 if (typeProxy == glslang::EbtFloat16)
7059 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7060#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007061 libCall = spv::GLSLstd450InterpolateAtSample;
7062 break;
7063 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007064#ifdef AMD_EXTENSIONS
7065 if (typeProxy == glslang::EbtFloat16)
7066 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7067#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007068 libCall = spv::GLSLstd450InterpolateAtOffset;
7069 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007070 case glslang::EOpAddCarry:
7071 opCode = spv::OpIAddCarry;
7072 typeId = builder.makeStructResultType(typeId0, typeId0);
7073 consumedOperands = 2;
7074 break;
7075 case glslang::EOpSubBorrow:
7076 opCode = spv::OpISubBorrow;
7077 typeId = builder.makeStructResultType(typeId0, typeId0);
7078 consumedOperands = 2;
7079 break;
7080 case glslang::EOpUMulExtended:
7081 opCode = spv::OpUMulExtended;
7082 typeId = builder.makeStructResultType(typeId0, typeId0);
7083 consumedOperands = 2;
7084 break;
7085 case glslang::EOpIMulExtended:
7086 opCode = spv::OpSMulExtended;
7087 typeId = builder.makeStructResultType(typeId0, typeId0);
7088 consumedOperands = 2;
7089 break;
7090 case glslang::EOpBitfieldExtract:
7091 if (isUnsigned)
7092 opCode = spv::OpBitFieldUExtract;
7093 else
7094 opCode = spv::OpBitFieldSExtract;
7095 break;
7096 case glslang::EOpBitfieldInsert:
7097 opCode = spv::OpBitFieldInsert;
7098 break;
7099
7100 case glslang::EOpFma:
7101 libCall = spv::GLSLstd450Fma;
7102 break;
7103 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007104 {
7105 libCall = spv::GLSLstd450FrexpStruct;
7106 assert(builder.isPointerType(typeId1));
7107 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007108 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007109#ifdef AMD_EXTENSIONS
7110 if (width == 16)
7111 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7112 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
7113#endif
Rex Xu470026f2017-03-29 17:12:40 +08007114 if (builder.getNumComponents(operands[0]) == 1)
7115 frexpIntType = builder.makeIntegerType(width, true);
7116 else
7117 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7118 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7119 consumedOperands = 1;
7120 }
John Kessenich55e7d112015-11-15 21:33:39 -07007121 break;
7122 case glslang::EOpLdexp:
7123 libCall = spv::GLSLstd450Ldexp;
7124 break;
7125
Rex Xu574ab042016-04-14 16:53:07 +08007126 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007127 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007128
John Kessenich66011cb2018-03-06 16:12:04 -07007129 case glslang::EOpSubgroupBroadcast:
7130 case glslang::EOpSubgroupBallotBitExtract:
7131 case glslang::EOpSubgroupShuffle:
7132 case glslang::EOpSubgroupShuffleXor:
7133 case glslang::EOpSubgroupShuffleUp:
7134 case glslang::EOpSubgroupShuffleDown:
7135 case glslang::EOpSubgroupClusteredAdd:
7136 case glslang::EOpSubgroupClusteredMul:
7137 case glslang::EOpSubgroupClusteredMin:
7138 case glslang::EOpSubgroupClusteredMax:
7139 case glslang::EOpSubgroupClusteredAnd:
7140 case glslang::EOpSubgroupClusteredOr:
7141 case glslang::EOpSubgroupClusteredXor:
7142 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007143#ifdef NV_EXTENSIONS
7144 case glslang::EOpSubgroupPartitionedAdd:
7145 case glslang::EOpSubgroupPartitionedMul:
7146 case glslang::EOpSubgroupPartitionedMin:
7147 case glslang::EOpSubgroupPartitionedMax:
7148 case glslang::EOpSubgroupPartitionedAnd:
7149 case glslang::EOpSubgroupPartitionedOr:
7150 case glslang::EOpSubgroupPartitionedXor:
7151 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7152 case glslang::EOpSubgroupPartitionedInclusiveMul:
7153 case glslang::EOpSubgroupPartitionedInclusiveMin:
7154 case glslang::EOpSubgroupPartitionedInclusiveMax:
7155 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7156 case glslang::EOpSubgroupPartitionedInclusiveOr:
7157 case glslang::EOpSubgroupPartitionedInclusiveXor:
7158 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7159 case glslang::EOpSubgroupPartitionedExclusiveMul:
7160 case glslang::EOpSubgroupPartitionedExclusiveMin:
7161 case glslang::EOpSubgroupPartitionedExclusiveMax:
7162 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7163 case glslang::EOpSubgroupPartitionedExclusiveOr:
7164 case glslang::EOpSubgroupPartitionedExclusiveXor:
7165#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007166 return createSubgroupOperation(op, typeId, operands, typeProxy);
7167
Rex Xu9d93a232016-05-05 12:30:44 +08007168#ifdef AMD_EXTENSIONS
7169 case glslang::EOpSwizzleInvocations:
7170 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7171 libCall = spv::SwizzleInvocationsAMD;
7172 break;
7173 case glslang::EOpSwizzleInvocationsMasked:
7174 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7175 libCall = spv::SwizzleInvocationsMaskedAMD;
7176 break;
7177 case glslang::EOpWriteInvocation:
7178 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7179 libCall = spv::WriteInvocationAMD;
7180 break;
7181
7182 case glslang::EOpMin3:
7183 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7184 if (isFloat)
7185 libCall = spv::FMin3AMD;
7186 else {
7187 if (isUnsigned)
7188 libCall = spv::UMin3AMD;
7189 else
7190 libCall = spv::SMin3AMD;
7191 }
7192 break;
7193 case glslang::EOpMax3:
7194 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7195 if (isFloat)
7196 libCall = spv::FMax3AMD;
7197 else {
7198 if (isUnsigned)
7199 libCall = spv::UMax3AMD;
7200 else
7201 libCall = spv::SMax3AMD;
7202 }
7203 break;
7204 case glslang::EOpMid3:
7205 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7206 if (isFloat)
7207 libCall = spv::FMid3AMD;
7208 else {
7209 if (isUnsigned)
7210 libCall = spv::UMid3AMD;
7211 else
7212 libCall = spv::SMid3AMD;
7213 }
7214 break;
7215
7216 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007217 if (typeProxy == glslang::EbtFloat16)
7218 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007219 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7220 libCall = spv::InterpolateAtVertexAMD;
7221 break;
7222#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007223 case glslang::EOpBarrier:
7224 {
7225 // This is for the extended controlBarrier function, with four operands.
7226 // The unextended barrier() goes through createNoArgOperation.
7227 assert(operands.size() == 4);
7228 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7229 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7230 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7231 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7232 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7233 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7234 }
7235 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7236 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7237 }
7238 return 0;
7239 }
7240 break;
7241 case glslang::EOpMemoryBarrier:
7242 {
7243 // This is for the extended memoryBarrier function, with three operands.
7244 // The unextended memoryBarrier() goes through createNoArgOperation.
7245 assert(operands.size() == 3);
7246 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7247 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7248 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7249 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7250 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7251 }
7252 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7253 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7254 }
7255 return 0;
7256 }
7257 break;
Chao Chen3c366992018-09-19 11:41:59 -07007258
7259#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007260 case glslang::EOpReportIntersectionNV:
7261 {
7262 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007263 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007264 }
7265 break;
7266 case glslang::EOpTraceNV:
7267 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007268 builder.createNoResultOp(spv::OpTraceNV, operands);
7269 return 0;
7270 }
7271 break;
7272 case glslang::EOpExecuteCallableNV:
7273 {
7274 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007275 return 0;
7276 }
7277 break;
Chao Chen3c366992018-09-19 11:41:59 -07007278 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7279 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7280 return 0;
7281#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007282 case glslang::EOpCooperativeMatrixMulAdd:
7283 opCode = spv::OpCooperativeMatrixMulAddNV;
7284 break;
7285
John Kessenich140f3df2015-06-26 16:58:36 -06007286 default:
7287 return 0;
7288 }
7289
7290 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007291 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007292 // Use an extended instruction from the standard library.
7293 // Construct the call arguments, without modifying the original operands vector.
7294 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7295 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007296 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007297 } else if (opCode == spv::OpDot && !isFloat) {
7298 // int dot(int, int)
7299 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7300 const int componentCount = builder.getNumComponents(operands[0]);
7301 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7302 builder.setPrecision(mulOp, precision);
7303 id = builder.createCompositeExtract(mulOp, typeId, 0);
7304 for (int i = 1; i < componentCount; ++i) {
7305 builder.setPrecision(id, precision);
7306 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7307 }
John Kessenich2359bd02015-12-06 19:29:11 -07007308 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007309 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007310 case 0:
7311 // should all be handled by visitAggregate and createNoArgOperation
7312 assert(0);
7313 return 0;
7314 case 1:
7315 // should all be handled by createUnaryOperation
7316 assert(0);
7317 return 0;
7318 case 2:
7319 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7320 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007321 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007322 // anything 3 or over doesn't have l-value operands, so all should be consumed
7323 assert(consumedOperands == operands.size());
7324 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007325 break;
7326 }
7327 }
7328
John Kessenich55e7d112015-11-15 21:33:39 -07007329 // Decode the return types that were structures
7330 switch (op) {
7331 case glslang::EOpAddCarry:
7332 case glslang::EOpSubBorrow:
7333 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7334 id = builder.createCompositeExtract(id, typeId0, 0);
7335 break;
7336 case glslang::EOpUMulExtended:
7337 case glslang::EOpIMulExtended:
7338 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7339 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7340 break;
7341 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007342 {
7343 assert(operands.size() == 2);
7344 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7345 // "exp" is floating-point type (from HLSL intrinsic)
7346 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7347 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7348 builder.createStore(member1, operands[1]);
7349 } else
7350 // "exp" is integer type (from GLSL built-in function)
7351 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7352 id = builder.createCompositeExtract(id, typeId0, 0);
7353 }
John Kessenich55e7d112015-11-15 21:33:39 -07007354 break;
7355 default:
7356 break;
7357 }
7358
John Kessenich32cfd492016-02-02 12:37:46 -07007359 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007360}
7361
Rex Xu9d93a232016-05-05 12:30:44 +08007362// Intrinsics with no arguments (or no return value, and no precision).
7363spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007364{
Jeff Bolz36831c92018-09-05 10:11:41 -05007365 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7366 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007367
7368 switch (op) {
7369 case glslang::EOpEmitVertex:
7370 builder.createNoResultOp(spv::OpEmitVertex);
7371 return 0;
7372 case glslang::EOpEndPrimitive:
7373 builder.createNoResultOp(spv::OpEndPrimitive);
7374 return 0;
7375 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007376 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007377 if (glslangIntermediate->usingVulkanMemoryModel()) {
7378 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7379 spv::MemorySemanticsOutputMemoryKHRMask |
7380 spv::MemorySemanticsAcquireReleaseMask);
7381 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7382 } else {
7383 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7384 }
John Kessenich82979362017-12-11 04:02:24 -07007385 } else {
7386 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7387 spv::MemorySemanticsWorkgroupMemoryMask |
7388 spv::MemorySemanticsAcquireReleaseMask);
7389 }
John Kessenich140f3df2015-06-26 16:58:36 -06007390 return 0;
7391 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007392 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7393 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007394 return 0;
7395 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007396 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7397 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007398 return 0;
7399 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007400 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7401 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007402 return 0;
7403 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007404 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7405 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007406 return 0;
7407 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007408 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7409 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007410 return 0;
7411 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007412 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7413 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007414 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007415 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007416 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007417 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007418 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007419 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007420 case glslang::EOpDeviceMemoryBarrier:
7421 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7422 spv::MemorySemanticsImageMemoryMask |
7423 spv::MemorySemanticsAcquireReleaseMask);
7424 return 0;
7425 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7426 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7427 spv::MemorySemanticsImageMemoryMask |
7428 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007429 return 0;
7430 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007431 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7432 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007433 return 0;
7434 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007435 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7436 spv::MemorySemanticsWorkgroupMemoryMask |
7437 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007438 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007439 case glslang::EOpSubgroupBarrier:
7440 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7441 spv::MemorySemanticsAcquireReleaseMask);
7442 return spv::NoResult;
7443 case glslang::EOpSubgroupMemoryBarrier:
7444 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7445 spv::MemorySemanticsAcquireReleaseMask);
7446 return spv::NoResult;
7447 case glslang::EOpSubgroupMemoryBarrierBuffer:
7448 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7449 spv::MemorySemanticsAcquireReleaseMask);
7450 return spv::NoResult;
7451 case glslang::EOpSubgroupMemoryBarrierImage:
7452 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7453 spv::MemorySemanticsAcquireReleaseMask);
7454 return spv::NoResult;
7455 case glslang::EOpSubgroupMemoryBarrierShared:
7456 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7457 spv::MemorySemanticsAcquireReleaseMask);
7458 return spv::NoResult;
7459 case glslang::EOpSubgroupElect: {
7460 std::vector<spv::Id> operands;
7461 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7462 }
Rex Xu9d93a232016-05-05 12:30:44 +08007463#ifdef AMD_EXTENSIONS
7464 case glslang::EOpTime:
7465 {
7466 std::vector<spv::Id> args; // Dummy arguments
7467 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7468 return builder.setPrecision(id, precision);
7469 }
7470#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007471#ifdef NV_EXTENSIONS
7472 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007473 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007474 return 0;
7475 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007476 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007477 return 0;
7478#endif
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007479
7480 case glslang::EOpBeginInvocationInterlock:
7481 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7482 return 0;
7483 case glslang::EOpEndInvocationInterlock:
7484 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7485 return 0;
7486
John Kessenich140f3df2015-06-26 16:58:36 -06007487 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007488 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007489 return 0;
7490 }
7491}
7492
7493spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7494{
John Kessenich2f273362015-07-18 22:34:27 -06007495 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007496 spv::Id id;
7497 if (symbolValues.end() != iter) {
7498 id = iter->second;
7499 return id;
7500 }
7501
7502 // it was not found, create it
7503 id = createSpvVariable(symbol);
7504 symbolValues[symbol->getId()] = id;
7505
Rex Xuc884b4a2016-06-29 15:03:44 +08007506 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007507 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7508 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7509 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007510#ifdef NV_EXTENSIONS
7511 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7512#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007513 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007514 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007515 if (symbol->getQualifier().hasIndex())
7516 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7517 if (symbol->getQualifier().hasComponent())
7518 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007519 // atomic counters use this:
7520 if (symbol->getQualifier().hasOffset())
7521 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007522 }
7523
scygan2c864272016-05-18 18:09:17 +02007524 if (symbol->getQualifier().hasLocation())
7525 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007526 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007527 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007528 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007529 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007530 }
John Kessenich140f3df2015-06-26 16:58:36 -06007531 if (symbol->getQualifier().hasSet())
7532 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007533 else if (IsDescriptorResource(symbol->getType())) {
7534 // default to 0
7535 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7536 }
John Kessenich140f3df2015-06-26 16:58:36 -06007537 if (symbol->getQualifier().hasBinding())
7538 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007539 else if (IsDescriptorResource(symbol->getType())) {
7540 // default to 0
7541 builder.addDecoration(id, spv::DecorationBinding, 0);
7542 }
John Kessenich6c292d32016-02-15 20:58:50 -07007543 if (symbol->getQualifier().hasAttachment())
7544 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007545 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007546 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007547 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007548 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007549 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7550 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7551 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7552 }
7553 if (symbol->getQualifier().hasXfbOffset())
7554 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007555 }
7556
Rex Xu1da878f2016-02-21 20:59:01 +08007557 if (symbol->getType().isImage()) {
7558 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007559 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007560 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007561 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007562 }
7563
John Kessenich140f3df2015-06-26 16:58:36 -06007564 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007565 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007566 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007567 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007568
John Kessenich5611c6d2018-04-05 11:25:02 -06007569 // nonuniform
7570 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7571
John Kessenichecba76f2017-01-06 00:34:48 -07007572#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007573 if (builtIn == spv::BuiltInSampleMask) {
7574 spv::Decoration decoration;
7575 // GL_NV_sample_mask_override_coverage extension
7576 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007577 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007578 else
7579 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007580 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007581 if (decoration != spv::DecorationMax) {
7582 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7583 }
7584 }
chaoc771d89f2017-01-13 01:10:53 -08007585 else if (builtIn == spv::BuiltInLayer) {
7586 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007587 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007588 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007589 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7590 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7591 }
John Kessenichb41bff62017-08-11 13:07:17 -06007592 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007593 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7594 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007595 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7596 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7597 }
7598 }
7599
chaoc6e5acae2016-12-20 13:28:52 -08007600 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007601 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007602 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007603 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7604 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007605 if (symbol->getQualifier().pervertexNV) {
7606 builder.addDecoration(id, spv::DecorationPerVertexNV);
7607 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7608 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7609 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007610#endif
7611
John Kessenich5d610ee2018-03-07 18:05:55 -07007612 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7613 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7614 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7615 symbol->getType().getQualifier().semanticName);
7616 }
7617
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007618 if (symbol->getBasicType() == glslang::EbtReference) {
7619 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7620 }
7621
John Kessenich140f3df2015-06-26 16:58:36 -06007622 return id;
7623}
7624
Chao Chen3c366992018-09-19 11:41:59 -07007625#ifdef NV_EXTENSIONS
7626// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7627void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7628{
7629 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007630 if (qualifier.perPrimitiveNV) {
7631 // Need to add capability/extension for fragment shader.
7632 // Mesh shader already adds this by default.
7633 if (glslangIntermediate->getStage() == EShLangFragment) {
7634 builder.addCapability(spv::CapabilityMeshShadingNV);
7635 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7636 }
Chao Chen3c366992018-09-19 11:41:59 -07007637 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007638 }
Chao Chen3c366992018-09-19 11:41:59 -07007639 if (qualifier.perViewNV)
7640 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7641 if (qualifier.perTaskNV)
7642 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7643 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007644 if (qualifier.perPrimitiveNV) {
7645 // Need to add capability/extension for fragment shader.
7646 // Mesh shader already adds this by default.
7647 if (glslangIntermediate->getStage() == EShLangFragment) {
7648 builder.addCapability(spv::CapabilityMeshShadingNV);
7649 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7650 }
Chao Chen3c366992018-09-19 11:41:59 -07007651 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007652 }
Chao Chen3c366992018-09-19 11:41:59 -07007653 if (qualifier.perViewNV)
7654 builder.addDecoration(id, spv::DecorationPerViewNV);
7655 if (qualifier.perTaskNV)
7656 builder.addDecoration(id, spv::DecorationPerTaskNV);
7657 }
7658}
7659#endif
7660
John Kessenich55e7d112015-11-15 21:33:39 -07007661// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007662// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007663//
7664// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7665//
7666// Recursively walk the nodes. The nodes form a tree whose leaves are
7667// regular constants, which themselves are trees that createSpvConstant()
7668// recursively walks. So, this function walks the "top" of the tree:
7669// - emit specialization constant-building instructions for specConstant
7670// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007671spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007672{
John Kessenich7cc0e282016-03-20 00:46:02 -06007673 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007674
qining4f4bb812016-04-03 23:55:17 -04007675 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007676 if (! node.getQualifier().specConstant) {
7677 // hand off to the non-spec-constant path
7678 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7679 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007680 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007681 nextConst, false);
7682 }
7683
7684 // We now know we have a specialization constant to build
7685
John Kessenichd94c0032016-05-30 19:29:40 -06007686 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007687 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7688 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7689 std::vector<spv::Id> dimConstId;
7690 for (int dim = 0; dim < 3; ++dim) {
7691 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7692 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007693 if (specConst) {
7694 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7695 glslangIntermediate->getLocalSizeSpecId(dim));
7696 }
qining4f4bb812016-04-03 23:55:17 -04007697 }
7698 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7699 }
7700
7701 // An AST node labelled as specialization constant should be a symbol node.
7702 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7703 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007704 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007705 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007706 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7707 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7708 // will set the builder into spec constant op instruction generating mode.
7709 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007710 result = accessChainLoad(sub_tree->getType());
7711 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007712 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007713 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007714 } else {
7715 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007716 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007717 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007718 builder.addName(result, sn->getName().c_str());
7719 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007720 }
qining4f4bb812016-04-03 23:55:17 -04007721
7722 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7723 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007724 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007725 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007726}
7727
John Kessenich140f3df2015-06-26 16:58:36 -06007728// Use 'consts' as the flattened glslang source of scalar constants to recursively
7729// build the aggregate SPIR-V constant.
7730//
7731// If there are not enough elements present in 'consts', 0 will be substituted;
7732// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7733//
qining08408382016-03-21 09:51:37 -04007734spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007735{
7736 // vector of constants for SPIR-V
7737 std::vector<spv::Id> spvConsts;
7738
7739 // Type is used for struct and array constants
7740 spv::Id typeId = convertGlslangToSpvType(glslangType);
7741
7742 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007743 glslang::TType elementType(glslangType, 0);
7744 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007745 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007746 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007747 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007748 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007749 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007750 } else if (glslangType.isCoopMat()) {
7751 glslang::TType componentType(glslangType.getBasicType());
7752 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007753 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007754 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7755 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007756 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007757 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007758 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7759 bool zero = nextConst >= consts.size();
7760 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007761 case glslang::EbtInt8:
7762 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7763 break;
7764 case glslang::EbtUint8:
7765 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7766 break;
7767 case glslang::EbtInt16:
7768 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7769 break;
7770 case glslang::EbtUint16:
7771 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7772 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007773 case glslang::EbtInt:
7774 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7775 break;
7776 case glslang::EbtUint:
7777 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7778 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007779 case glslang::EbtInt64:
7780 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7781 break;
7782 case glslang::EbtUint64:
7783 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7784 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007785 case glslang::EbtFloat:
7786 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7787 break;
7788 case glslang::EbtDouble:
7789 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7790 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007791 case glslang::EbtFloat16:
7792 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7793 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007794 case glslang::EbtBool:
7795 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7796 break;
7797 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007798 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007799 break;
7800 }
7801 ++nextConst;
7802 }
7803 } else {
7804 // we have a non-aggregate (scalar) constant
7805 bool zero = nextConst >= consts.size();
7806 spv::Id scalar = 0;
7807 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007808 case glslang::EbtInt8:
7809 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7810 break;
7811 case glslang::EbtUint8:
7812 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7813 break;
7814 case glslang::EbtInt16:
7815 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7816 break;
7817 case glslang::EbtUint16:
7818 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7819 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007820 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007821 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007822 break;
7823 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007824 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007825 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007826 case glslang::EbtInt64:
7827 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7828 break;
7829 case glslang::EbtUint64:
7830 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7831 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007832 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007833 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007834 break;
7835 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007836 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007837 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007838 case glslang::EbtFloat16:
7839 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7840 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007841 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007842 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007843 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007844 case glslang::EbtReference:
7845 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7846 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7847 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007848 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007849 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007850 break;
7851 }
7852 ++nextConst;
7853 return scalar;
7854 }
7855
7856 return builder.makeCompositeConstant(typeId, spvConsts);
7857}
7858
John Kessenich7c1aa102015-10-15 13:29:11 -06007859// Return true if the node is a constant or symbol whose reading has no
7860// non-trivial observable cost or effect.
7861bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7862{
7863 // don't know what this is
7864 if (node == nullptr)
7865 return false;
7866
7867 // a constant is safe
7868 if (node->getAsConstantUnion() != nullptr)
7869 return true;
7870
7871 // not a symbol means non-trivial
7872 if (node->getAsSymbolNode() == nullptr)
7873 return false;
7874
7875 // a symbol, depends on what's being read
7876 switch (node->getType().getQualifier().storage) {
7877 case glslang::EvqTemporary:
7878 case glslang::EvqGlobal:
7879 case glslang::EvqIn:
7880 case glslang::EvqInOut:
7881 case glslang::EvqConst:
7882 case glslang::EvqConstReadOnly:
7883 case glslang::EvqUniform:
7884 return true;
7885 default:
7886 return false;
7887 }
qining25262b32016-05-06 17:25:16 -04007888}
John Kessenich7c1aa102015-10-15 13:29:11 -06007889
7890// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007891// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007892// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007893// Return true if trivial.
7894bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7895{
7896 if (node == nullptr)
7897 return false;
7898
John Kessenich84cc15f2017-05-24 16:44:47 -06007899 // count non scalars as trivial, as well as anything coming from HLSL
7900 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007901 return true;
7902
John Kessenich7c1aa102015-10-15 13:29:11 -06007903 // symbols and constants are trivial
7904 if (isTrivialLeaf(node))
7905 return true;
7906
7907 // otherwise, it needs to be a simple operation or one or two leaf nodes
7908
7909 // not a simple operation
7910 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7911 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7912 if (binaryNode == nullptr && unaryNode == nullptr)
7913 return false;
7914
7915 // not on leaf nodes
7916 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7917 return false;
7918
7919 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7920 return false;
7921 }
7922
7923 switch (node->getAsOperator()->getOp()) {
7924 case glslang::EOpLogicalNot:
7925 case glslang::EOpConvIntToBool:
7926 case glslang::EOpConvUintToBool:
7927 case glslang::EOpConvFloatToBool:
7928 case glslang::EOpConvDoubleToBool:
7929 case glslang::EOpEqual:
7930 case glslang::EOpNotEqual:
7931 case glslang::EOpLessThan:
7932 case glslang::EOpGreaterThan:
7933 case glslang::EOpLessThanEqual:
7934 case glslang::EOpGreaterThanEqual:
7935 case glslang::EOpIndexDirect:
7936 case glslang::EOpIndexDirectStruct:
7937 case glslang::EOpLogicalXor:
7938 case glslang::EOpAny:
7939 case glslang::EOpAll:
7940 return true;
7941 default:
7942 return false;
7943 }
7944}
7945
7946// Emit short-circuiting code, where 'right' is never evaluated unless
7947// the left side is true (for &&) or false (for ||).
7948spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7949{
7950 spv::Id boolTypeId = builder.makeBoolType();
7951
7952 // emit left operand
7953 builder.clearAccessChain();
7954 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007955 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007956
7957 // Operands to accumulate OpPhi operands
7958 std::vector<spv::Id> phiOperands;
7959 // accumulate left operand's phi information
7960 phiOperands.push_back(leftId);
7961 phiOperands.push_back(builder.getBuildPoint()->getId());
7962
7963 // Make the two kinds of operation symmetric with a "!"
7964 // || => emit "if (! left) result = right"
7965 // && => emit "if ( left) result = right"
7966 //
7967 // TODO: this runtime "not" for || could be avoided by adding functionality
7968 // to 'builder' to have an "else" without an "then"
7969 if (op == glslang::EOpLogicalOr)
7970 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7971
7972 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007973 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007974
7975 // emit right operand as the "then" part of the "if"
7976 builder.clearAccessChain();
7977 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007978 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007979
7980 // accumulate left operand's phi information
7981 phiOperands.push_back(rightId);
7982 phiOperands.push_back(builder.getBuildPoint()->getId());
7983
7984 // finish the "if"
7985 ifBuilder.makeEndIf();
7986
7987 // phi together the two results
7988 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7989}
7990
Frank Henigman541f7bb2018-01-16 00:18:26 -05007991#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007992// Return type Id of the imported set of extended instructions corresponds to the name.
7993// Import this set if it has not been imported yet.
7994spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7995{
7996 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7997 return extBuiltinMap[name];
7998 else {
Rex Xu51596642016-09-21 18:56:12 +08007999 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08008000 spv::Id extBuiltins = builder.import(name);
8001 extBuiltinMap[name] = extBuiltins;
8002 return extBuiltins;
8003 }
8004}
Frank Henigman541f7bb2018-01-16 00:18:26 -05008005#endif
Rex Xu9d93a232016-05-05 12:30:44 +08008006
John Kessenich140f3df2015-06-26 16:58:36 -06008007}; // end anonymous namespace
8008
8009namespace glslang {
8010
John Kessenich68d78fd2015-07-12 19:28:10 -06008011void GetSpirvVersion(std::string& version)
8012{
John Kessenich9e55f632015-07-15 10:03:39 -06008013 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06008014 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07008015 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06008016 version = buf;
8017}
8018
John Kessenicha372a3e2017-11-02 22:32:14 -06008019// For low-order part of the generator's magic number. Bump up
8020// when there is a change in the style (e.g., if SSA form changes,
8021// or a different instruction sequence to do something gets used).
8022int GetSpirvGeneratorVersion()
8023{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008024 // return 1; // start
8025 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008026 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008027 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008028 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008029 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8030 // versions 4 and 6 each generate OpArrayLength as it has long been done
8031 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008032}
8033
John Kessenich140f3df2015-06-26 16:58:36 -06008034// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008035void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008036{
8037 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008038 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008039 if (out.fail())
8040 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008041 for (int i = 0; i < (int)spirv.size(); ++i) {
8042 unsigned int word = spirv[i];
8043 out.write((const char*)&word, 4);
8044 }
8045 out.close();
8046}
8047
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008048// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008049void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008050{
8051 std::ofstream out;
8052 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008053 if (out.fail())
8054 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008055 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008056 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008057 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008058 if (varName != nullptr) {
8059 out << "\t #pragma once" << std::endl;
8060 out << "const uint32_t " << varName << "[] = {" << std::endl;
8061 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008062 const int WORDS_PER_LINE = 8;
8063 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8064 out << "\t";
8065 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8066 const unsigned int word = spirv[i + j];
8067 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8068 if (i + j + 1 < (int)spirv.size()) {
8069 out << ",";
8070 }
8071 }
8072 out << std::endl;
8073 }
Flavio15017db2017-02-15 14:29:33 -08008074 if (varName != nullptr) {
8075 out << "};";
8076 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008077 out.close();
8078}
8079
John Kessenich140f3df2015-06-26 16:58:36 -06008080//
8081// Set up the glslang traversal
8082//
John Kessenich4e11b612018-08-30 16:56:59 -06008083void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008084{
Lei Zhang17535f72016-05-04 15:55:59 -04008085 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008086 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008087}
8088
John Kessenich4e11b612018-08-30 16:56:59 -06008089void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008090 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008091{
John Kessenich140f3df2015-06-26 16:58:36 -06008092 TIntermNode* root = intermediate.getTreeRoot();
8093
8094 if (root == 0)
8095 return;
8096
John Kessenich4e11b612018-08-30 16:56:59 -06008097 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008098 if (options == nullptr)
8099 options = &defaultOptions;
8100
John Kessenich4e11b612018-08-30 16:56:59 -06008101 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008102
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008103 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008104 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008105 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008106 it.dumpSpv(spirv);
8107
GregFfb03a552018-03-29 11:49:14 -06008108#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008109 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8110 // eg. forward and remove memory writes of opaque types.
Jeff Bolzfd556e32019-06-07 14:42:08 -05008111 bool prelegalization = intermediate.getSource() == EShSourceHlsl;
8112 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer) {
John Kesseniche7df8e02018-08-22 17:12:46 -06008113 SpirvToolsLegalize(intermediate, spirv, logger, options);
Jeff Bolzfd556e32019-06-07 14:42:08 -05008114 prelegalization = false;
8115 }
John Kessenich717c80a2018-08-23 15:17:10 -06008116
John Kessenich4e11b612018-08-30 16:56:59 -06008117 if (options->validate)
Jeff Bolzfd556e32019-06-07 14:42:08 -05008118 SpirvToolsValidate(intermediate, spirv, logger, prelegalization);
John Kessenich4e11b612018-08-30 16:56:59 -06008119
John Kessenich717c80a2018-08-23 15:17:10 -06008120 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008121 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008122
GregFcd1f1692017-09-21 18:40:22 -06008123#endif
8124
John Kessenich4e11b612018-08-30 16:56:59 -06008125 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008126}
8127
8128}; // end namespace glslang