blob: f5cbb8877b4e23eb523353dddc0f37c47d2ac50e [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
John Kessenichb23d2322018-12-14 10:47:35 -07003// Copyright (C) 2015-2018 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080051#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080052 #include "GLSL.ext.NV.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
qining4c912612016-04-01 10:35:16 -040071namespace {
72class SpecConstantOpModeGuard {
73public:
74 SpecConstantOpModeGuard(spv::Builder* builder)
75 : builder_(builder) {
76 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040077 }
78 ~SpecConstantOpModeGuard() {
79 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
80 : builder_->setToNormalCodeGenMode();
81 }
qining40887662016-04-03 22:20:42 -040082 void turnOnSpecConstantOpMode() {
83 builder_->setToSpecConstCodeGenMode();
84 }
qining4c912612016-04-01 10:35:16 -040085
86private:
87 spv::Builder* builder_;
88 bool previous_flag_;
89};
John Kessenichead86222018-03-28 18:01:20 -060090
91struct OpDecorations {
92 spv::Decoration precision;
93 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -060094 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -060095};
96
97} // namespace
qining4c912612016-04-01 10:35:16 -040098
John Kessenich140f3df2015-06-26 16:58:36 -060099//
100// The main holder of information for translating glslang to SPIR-V.
101//
102// Derives from the AST walking base class.
103//
104class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
105public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700106 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
107 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700108 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600109
110 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
111 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
112 void visitConstantUnion(glslang::TIntermConstantUnion*);
113 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
114 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
115 void visitSymbol(glslang::TIntermSymbol* symbol);
116 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
117 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
118 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
119
John Kessenichfca82622016-11-26 13:23:20 -0700120 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700121 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600122
123protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700124 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
125 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
126
Rex Xu17ff3432016-10-14 17:41:45 +0800127 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800128 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600129 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500130 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
131 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
132 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
133 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100134 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700135 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700136 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
137 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700138 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600139 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600140 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich140f3df2015-06-26 16:58:36 -0600141 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
142 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600143 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
144 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
145 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600146 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600147 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600148 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600149 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600150 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
151 glslang::TLayoutPacking, const glslang::TQualifier&);
152 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
153 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700154 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700155 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800156 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600157 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700158 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700159 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
160 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700161 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
162 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100163 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600164
John Kessenich6fccb3c2016-09-19 16:01:41 -0600165 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600166 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600167 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600168 void makeFunctions(const glslang::TIntermSequence&);
169 void makeGlobalInitializers(const glslang::TIntermSequence&);
170 void visitFunctions(const glslang::TIntermSequence&);
171 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800172 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600173 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
174 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600175 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
176
John Kessenichead86222018-03-28 18:01:20 -0600177 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
178 glslang::TBasicType typeProxy, bool reduceComparison = true);
179 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
180 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
181 glslang::TBasicType typeProxy);
182 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
183 glslang::TBasicType typeProxy);
184 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
185 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600186 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600187 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800188 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800189 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800190 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700191 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600192 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800193 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600194 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700195#ifdef NV_EXTENSIONS
196 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
197#endif
qining08408382016-03-21 09:51:37 -0400198 spv::Id createSpvConstant(const glslang::TIntermTyped&);
199 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600200 bool isTrivialLeaf(const glslang::TIntermTyped* node);
201 bool isTrivial(const glslang::TIntermTyped* node);
202 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500203#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800204 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500205#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700206 void addPre13Extension(const char* ext)
207 {
208 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
209 builder.addExtension(ext);
210 }
John Kessenich140f3df2015-06-26 16:58:36 -0600211
John Kessenich121853f2017-05-31 17:11:16 -0600212 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600213 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600214 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700215 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600216 int sequenceDepth;
217
Lei Zhang17535f72016-05-04 15:55:59 -0400218 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400219
John Kessenich140f3df2015-06-26 16:58:36 -0600220 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
221 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700222 bool inEntryPoint;
223 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700224 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700225 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600226 const glslang::TIntermediate* glslangIntermediate;
227 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800228 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600229
John Kessenich2f273362015-07-18 22:34:27 -0600230 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600231 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600232 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700233 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700234 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
235 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600236 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700237 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600238 // Map pointee types for EbtReference to their forward pointers
239 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich140f3df2015-06-26 16:58:36 -0600240};
241
242//
243// Helper functions for translating glslang representations to SPIR-V enumerants.
244//
245
246// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700247spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600248{
John Kessenich66e2faf2016-03-12 18:34:36 -0700249 switch (source) {
250 case glslang::EShSourceGlsl:
251 switch (profile) {
252 case ENoProfile:
253 case ECoreProfile:
254 case ECompatibilityProfile:
255 return spv::SourceLanguageGLSL;
256 case EEsProfile:
257 return spv::SourceLanguageESSL;
258 default:
259 return spv::SourceLanguageUnknown;
260 }
261 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600262 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600263 default:
264 return spv::SourceLanguageUnknown;
265 }
266}
267
268// Translate glslang language (stage) to SPIR-V execution model.
269spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
270{
271 switch (stage) {
272 case EShLangVertex: return spv::ExecutionModelVertex;
273 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
274 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
275 case EShLangGeometry: return spv::ExecutionModelGeometry;
276 case EShLangFragment: return spv::ExecutionModelFragment;
277 case EShLangCompute: return spv::ExecutionModelGLCompute;
Chao Chen3c366992018-09-19 11:41:59 -0700278#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -0700279 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
280 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
281 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
282 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
283 case EShLangMissNV: return spv::ExecutionModelMissNV;
284 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700285 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
286 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
287#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600288 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700289 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600290 return spv::ExecutionModelFragment;
291 }
292}
293
John Kessenich140f3df2015-06-26 16:58:36 -0600294// Translate glslang sampler type to SPIR-V dimensionality.
295spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
296{
297 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700298 case glslang::Esd1D: return spv::Dim1D;
299 case glslang::Esd2D: return spv::Dim2D;
300 case glslang::Esd3D: return spv::Dim3D;
301 case glslang::EsdCube: return spv::DimCube;
302 case glslang::EsdRect: return spv::DimRect;
303 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700304 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600305 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700306 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600307 return spv::Dim2D;
308 }
309}
310
John Kessenichf6640762016-08-01 19:44:00 -0600311// Translate glslang precision to SPIR-V precision decorations.
312spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600313{
John Kessenichf6640762016-08-01 19:44:00 -0600314 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700315 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600316 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600317 default:
318 return spv::NoPrecision;
319 }
320}
321
John Kessenichf6640762016-08-01 19:44:00 -0600322// Translate glslang type to SPIR-V precision decorations.
323spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
324{
325 return TranslatePrecisionDecoration(type.getQualifier().precision);
326}
327
John Kessenich140f3df2015-06-26 16:58:36 -0600328// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600329spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600330{
331 if (type.getBasicType() == glslang::EbtBlock) {
332 switch (type.getQualifier().storage) {
333 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600334 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600335 case glslang::EvqVaryingIn: return spv::DecorationBlock;
336 case glslang::EvqVaryingOut: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700337#ifdef NV_EXTENSIONS
338 case glslang::EvqPayloadNV: return spv::DecorationBlock;
339 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
340 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700341 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
342 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700343#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600344 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700345 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600346 break;
347 }
348 }
349
John Kessenich4016e382016-07-15 11:53:56 -0600350 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600351}
352
Rex Xu1da878f2016-02-21 20:59:01 +0800353// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500354void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800355{
Jeff Bolz36831c92018-09-05 10:11:41 -0500356 if (!useVulkanMemoryModel) {
357 if (qualifier.coherent)
358 memory.push_back(spv::DecorationCoherent);
359 if (qualifier.volatil) {
360 memory.push_back(spv::DecorationVolatile);
361 memory.push_back(spv::DecorationCoherent);
362 }
John Kessenich14b85d32018-06-04 15:36:03 -0600363 }
Rex Xu1da878f2016-02-21 20:59:01 +0800364 if (qualifier.restrict)
365 memory.push_back(spv::DecorationRestrict);
366 if (qualifier.readonly)
367 memory.push_back(spv::DecorationNonWritable);
368 if (qualifier.writeonly)
369 memory.push_back(spv::DecorationNonReadable);
370}
371
John Kessenich140f3df2015-06-26 16:58:36 -0600372// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700373spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600374{
375 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700376 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600377 case glslang::ElmRowMajor:
378 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700379 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600380 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700381 default:
382 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600383 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600384 }
385 } else {
386 switch (type.getBasicType()) {
387 default:
John Kessenich4016e382016-07-15 11:53:56 -0600388 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600389 break;
390 case glslang::EbtBlock:
391 switch (type.getQualifier().storage) {
392 case glslang::EvqUniform:
393 case glslang::EvqBuffer:
394 switch (type.getQualifier().layoutPacking) {
395 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600396 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
397 default:
John Kessenich4016e382016-07-15 11:53:56 -0600398 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600399 }
400 case glslang::EvqVaryingIn:
401 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700402 if (type.getQualifier().isTaskMemory()) {
403 switch (type.getQualifier().layoutPacking) {
404 case glslang::ElpShared: return spv::DecorationGLSLShared;
405 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
406 default: break;
407 }
408 } else {
409 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
410 }
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
Chao Chenb50c02e2018-09-19 11:42:24 -0700412#ifdef NV_EXTENSIONS
413 case glslang::EvqPayloadNV:
414 case glslang::EvqPayloadInNV:
415 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700416 case glslang::EvqCallableDataNV:
417 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700418 return spv::DecorationMax;
419#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600420 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700421 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600422 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600423 }
424 }
425 }
426}
427
428// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600429// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700430// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800431spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600432{
Rex Xubbceed72016-05-21 09:40:44 +0800433 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700434 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600435 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800436 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700437 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700438 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600439 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800440#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800441 else if (qualifier.explicitInterp) {
442 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800443 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800444 }
Rex Xu9d93a232016-05-05 12:30:44 +0800445#endif
Rex Xubbceed72016-05-21 09:40:44 +0800446 else
John Kessenich4016e382016-07-15 11:53:56 -0600447 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800448}
449
450// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600451// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800452// should be applied.
453spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
454{
455 if (qualifier.patch)
456 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700457 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600458 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700459 else if (qualifier.sample) {
460 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600461 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700462 } else
John Kessenich4016e382016-07-15 11:53:56 -0600463 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600464}
465
John Kessenich92187592016-02-01 13:45:25 -0700466// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700467spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600468{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700469 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600470 return spv::DecorationInvariant;
471 else
John Kessenich4016e382016-07-15 11:53:56 -0600472 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600473}
474
qining9220dbb2016-05-04 17:34:38 -0400475// If glslang type is noContraction, return SPIR-V NoContraction decoration.
476spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
477{
478 if (qualifier.noContraction)
479 return spv::DecorationNoContraction;
480 else
John Kessenich4016e382016-07-15 11:53:56 -0600481 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400482}
483
John Kessenich5611c6d2018-04-05 11:25:02 -0600484// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
485spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
486{
487 if (qualifier.isNonUniform()) {
488 builder.addExtension("SPV_EXT_descriptor_indexing");
489 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
490 return spv::DecorationNonUniformEXT;
491 } else
492 return spv::DecorationMax;
493}
494
Jeff Bolz36831c92018-09-05 10:11:41 -0500495spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
496{
497 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
498 return spv::MemoryAccessMaskNone;
499 }
500 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
501 if (coherentFlags.volatil ||
502 coherentFlags.coherent ||
503 coherentFlags.devicecoherent ||
504 coherentFlags.queuefamilycoherent ||
505 coherentFlags.workgroupcoherent ||
506 coherentFlags.subgroupcoherent) {
507 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
508 spv::MemoryAccessMakePointerVisibleKHRMask;
509 }
510 if (coherentFlags.nonprivate) {
511 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
512 }
513 if (coherentFlags.volatil) {
514 mask = mask | spv::MemoryAccessVolatileMask;
515 }
516 if (mask != spv::MemoryAccessMaskNone) {
517 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
518 }
519 return mask;
520}
521
522spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
523{
524 if (!glslangIntermediate->usingVulkanMemoryModel()) {
525 return spv::ImageOperandsMaskNone;
526 }
527 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
528 if (coherentFlags.volatil ||
529 coherentFlags.coherent ||
530 coherentFlags.devicecoherent ||
531 coherentFlags.queuefamilycoherent ||
532 coherentFlags.workgroupcoherent ||
533 coherentFlags.subgroupcoherent) {
534 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
535 spv::ImageOperandsMakeTexelVisibleKHRMask;
536 }
537 if (coherentFlags.nonprivate) {
538 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
539 }
540 if (coherentFlags.volatil) {
541 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
542 }
543 if (mask != spv::ImageOperandsMaskNone) {
544 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
545 }
546 return mask;
547}
548
549spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
550{
551 spv::Builder::AccessChain::CoherentFlags flags;
552 flags.coherent = type.getQualifier().coherent;
553 flags.devicecoherent = type.getQualifier().devicecoherent;
554 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
555 // shared variables are implicitly workgroupcoherent in GLSL.
556 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
557 type.getQualifier().storage == glslang::EvqShared;
558 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600559 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500560 // *coherent variables are implicitly nonprivate in GLSL
561 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500562 flags.subgroupcoherent ||
563 flags.workgroupcoherent ||
564 flags.queuefamilycoherent ||
565 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600566 flags.coherent ||
567 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500568 flags.isImage = type.getBasicType() == glslang::EbtSampler;
569 return flags;
570}
571
572spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
573{
574 spv::Scope scope;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600575 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500576 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
577 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
578 } else if (coherentFlags.devicecoherent) {
579 scope = spv::ScopeDevice;
580 } else if (coherentFlags.queuefamilycoherent) {
581 scope = spv::ScopeQueueFamilyKHR;
582 } else if (coherentFlags.workgroupcoherent) {
583 scope = spv::ScopeWorkgroup;
584 } else if (coherentFlags.subgroupcoherent) {
585 scope = spv::ScopeSubgroup;
586 } else {
587 scope = spv::ScopeMax;
588 }
589 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
590 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
591 }
592 return scope;
593}
594
David Netoa901ffe2016-06-08 14:11:40 +0100595// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
596// associated capabilities when required. For some built-in variables, a capability
597// is generated only when using the variable in an executable instruction, but not when
598// just declaring a struct member variable with it. This is true for PointSize,
599// ClipDistance, and CullDistance.
600spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600601{
602 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700603 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600604 // Defer adding the capability until the built-in is actually used.
605 if (! memberDeclaration) {
606 switch (glslangIntermediate->getStage()) {
607 case EShLangGeometry:
608 builder.addCapability(spv::CapabilityGeometryPointSize);
609 break;
610 case EShLangTessControl:
611 case EShLangTessEvaluation:
612 builder.addCapability(spv::CapabilityTessellationPointSize);
613 break;
614 default:
615 break;
616 }
John Kessenich92187592016-02-01 13:45:25 -0700617 }
618 return spv::BuiltInPointSize;
619
John Kessenichebb50532016-05-16 19:22:05 -0600620 // These *Distance capabilities logically belong here, but if the member is declared and
621 // then never used, consumers of SPIR-V prefer the capability not be declared.
622 // They are now generated when used, rather than here when declared.
623 // Potentially, the specification should be more clear what the minimum
624 // use needed is to trigger the capability.
625 //
John Kessenich92187592016-02-01 13:45:25 -0700626 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100627 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800628 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700629 return spv::BuiltInClipDistance;
630
631 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100632 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800633 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700634 return spv::BuiltInCullDistance;
635
636 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600637 builder.addCapability(spv::CapabilityMultiViewport);
638 if (glslangIntermediate->getStage() == EShLangVertex ||
639 glslangIntermediate->getStage() == EShLangTessControl ||
640 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800641
John Kessenichba6a3c22017-09-13 13:22:50 -0600642 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
643 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800644 }
John Kessenich92187592016-02-01 13:45:25 -0700645 return spv::BuiltInViewportIndex;
646
John Kessenich5e801132016-02-15 11:09:46 -0700647 case glslang::EbvSampleId:
648 builder.addCapability(spv::CapabilitySampleRateShading);
649 return spv::BuiltInSampleId;
650
651 case glslang::EbvSamplePosition:
652 builder.addCapability(spv::CapabilitySampleRateShading);
653 return spv::BuiltInSamplePosition;
654
655 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700656 return spv::BuiltInSampleMask;
657
John Kessenich78a45572016-07-08 14:05:15 -0600658 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700659#ifdef NV_EXTENSIONS
660 if (glslangIntermediate->getStage() == EShLangMeshNV) {
661 return spv::BuiltInLayer;
662 }
663#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600664 builder.addCapability(spv::CapabilityGeometry);
665 if (glslangIntermediate->getStage() == EShLangVertex ||
666 glslangIntermediate->getStage() == EShLangTessControl ||
667 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800668
John Kessenichba6a3c22017-09-13 13:22:50 -0600669 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
670 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800671 }
John Kessenich78a45572016-07-08 14:05:15 -0600672 return spv::BuiltInLayer;
673
John Kessenich140f3df2015-06-26 16:58:36 -0600674 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600675 case glslang::EbvVertexId: return spv::BuiltInVertexId;
676 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700677 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
678 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800679
John Kessenichda581a22015-10-14 14:10:30 -0600680 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700681 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800682 builder.addCapability(spv::CapabilityDrawParameters);
683 return spv::BuiltInBaseVertex;
684
John Kessenichda581a22015-10-14 14:10:30 -0600685 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700686 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800687 builder.addCapability(spv::CapabilityDrawParameters);
688 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200689
John Kessenichda581a22015-10-14 14:10:30 -0600690 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700691 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800692 builder.addCapability(spv::CapabilityDrawParameters);
693 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200694
695 case glslang::EbvPrimitiveId:
696 if (glslangIntermediate->getStage() == EShLangFragment)
697 builder.addCapability(spv::CapabilityGeometry);
698 return spv::BuiltInPrimitiveId;
699
Rex Xu37cdcee2017-06-29 17:46:34 +0800700 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800701 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
702 builder.addCapability(spv::CapabilityStencilExportEXT);
703 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800704
John Kessenich140f3df2015-06-26 16:58:36 -0600705 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600706 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
707 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
708 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
709 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
710 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
711 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
712 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600713 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
714 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
715 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
716 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
717 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
718 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
719 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
720 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800721
Rex Xu574ab042016-04-14 16:53:07 +0800722 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800723 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800724 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
725 return spv::BuiltInSubgroupSize;
726
Rex Xu574ab042016-04-14 16:53:07 +0800727 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800728 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800729 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
730 return spv::BuiltInSubgroupLocalInvocationId;
731
Rex Xu574ab042016-04-14 16:53:07 +0800732 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800733 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
734 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
735 return spv::BuiltInSubgroupEqMaskKHR;
736
Rex Xu574ab042016-04-14 16:53:07 +0800737 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800738 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
739 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
740 return spv::BuiltInSubgroupGeMaskKHR;
741
Rex Xu574ab042016-04-14 16:53:07 +0800742 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800743 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
744 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
745 return spv::BuiltInSubgroupGtMaskKHR;
746
Rex Xu574ab042016-04-14 16:53:07 +0800747 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800748 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
749 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
750 return spv::BuiltInSubgroupLeMaskKHR;
751
Rex Xu574ab042016-04-14 16:53:07 +0800752 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800753 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
754 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
755 return spv::BuiltInSubgroupLtMaskKHR;
756
John Kessenich66011cb2018-03-06 16:12:04 -0700757 case glslang::EbvNumSubgroups:
758 builder.addCapability(spv::CapabilityGroupNonUniform);
759 return spv::BuiltInNumSubgroups;
760
761 case glslang::EbvSubgroupID:
762 builder.addCapability(spv::CapabilityGroupNonUniform);
763 return spv::BuiltInSubgroupId;
764
765 case glslang::EbvSubgroupSize2:
766 builder.addCapability(spv::CapabilityGroupNonUniform);
767 return spv::BuiltInSubgroupSize;
768
769 case glslang::EbvSubgroupInvocation2:
770 builder.addCapability(spv::CapabilityGroupNonUniform);
771 return spv::BuiltInSubgroupLocalInvocationId;
772
773 case glslang::EbvSubgroupEqMask2:
774 builder.addCapability(spv::CapabilityGroupNonUniform);
775 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
776 return spv::BuiltInSubgroupEqMask;
777
778 case glslang::EbvSubgroupGeMask2:
779 builder.addCapability(spv::CapabilityGroupNonUniform);
780 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
781 return spv::BuiltInSubgroupGeMask;
782
783 case glslang::EbvSubgroupGtMask2:
784 builder.addCapability(spv::CapabilityGroupNonUniform);
785 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
786 return spv::BuiltInSubgroupGtMask;
787
788 case glslang::EbvSubgroupLeMask2:
789 builder.addCapability(spv::CapabilityGroupNonUniform);
790 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
791 return spv::BuiltInSubgroupLeMask;
792
793 case glslang::EbvSubgroupLtMask2:
794 builder.addCapability(spv::CapabilityGroupNonUniform);
795 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
796 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800797#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800798 case glslang::EbvBaryCoordNoPersp:
799 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
800 return spv::BuiltInBaryCoordNoPerspAMD;
801
802 case glslang::EbvBaryCoordNoPerspCentroid:
803 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
804 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
805
806 case glslang::EbvBaryCoordNoPerspSample:
807 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
808 return spv::BuiltInBaryCoordNoPerspSampleAMD;
809
810 case glslang::EbvBaryCoordSmooth:
811 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
812 return spv::BuiltInBaryCoordSmoothAMD;
813
814 case glslang::EbvBaryCoordSmoothCentroid:
815 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
816 return spv::BuiltInBaryCoordSmoothCentroidAMD;
817
818 case glslang::EbvBaryCoordSmoothSample:
819 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
820 return spv::BuiltInBaryCoordSmoothSampleAMD;
821
822 case glslang::EbvBaryCoordPullModel:
823 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
824 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800825#endif
chaoc771d89f2017-01-13 01:10:53 -0800826
John Kessenich6c8aaac2017-02-27 01:20:51 -0700827 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700828 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700829 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700830 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700831
832 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700833 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700834 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700835 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700836
Daniel Koch5154db52018-11-26 10:01:58 -0500837 case glslang::EbvFragSizeEXT:
838 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
839 builder.addCapability(spv::CapabilityFragmentDensityEXT);
840 return spv::BuiltInFragSizeEXT;
841
842 case glslang::EbvFragInvocationCountEXT:
843 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
844 builder.addCapability(spv::CapabilityFragmentDensityEXT);
845 return spv::BuiltInFragInvocationCountEXT;
846
chaoc771d89f2017-01-13 01:10:53 -0800847#ifdef NV_EXTENSIONS
848 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800849 if (!memberDeclaration) {
850 builder.addExtension(spv::E_SPV_NV_viewport_array2);
851 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
852 }
chaoc771d89f2017-01-13 01:10:53 -0800853 return spv::BuiltInViewportMaskNV;
854 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800855 if (!memberDeclaration) {
856 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
857 builder.addCapability(spv::CapabilityShaderStereoViewNV);
858 }
chaoc771d89f2017-01-13 01:10:53 -0800859 return spv::BuiltInSecondaryPositionNV;
860 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800861 if (!memberDeclaration) {
862 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
863 builder.addCapability(spv::CapabilityShaderStereoViewNV);
864 }
chaoc771d89f2017-01-13 01:10:53 -0800865 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800866 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800867 if (!memberDeclaration) {
868 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
869 builder.addCapability(spv::CapabilityPerViewAttributesNV);
870 }
chaocdf3956c2017-02-14 14:52:34 -0800871 return spv::BuiltInPositionPerViewNV;
872 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800873 if (!memberDeclaration) {
874 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
875 builder.addCapability(spv::CapabilityPerViewAttributesNV);
876 }
chaocdf3956c2017-02-14 14:52:34 -0800877 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700878 case glslang::EbvFragFullyCoveredNV:
879 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
880 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
881 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700882 case glslang::EbvFragmentSizeNV:
883 builder.addExtension(spv::E_SPV_NV_shading_rate);
884 builder.addCapability(spv::CapabilityShadingRateNV);
885 return spv::BuiltInFragmentSizeNV;
886 case glslang::EbvInvocationsPerPixelNV:
887 builder.addExtension(spv::E_SPV_NV_shading_rate);
888 builder.addCapability(spv::CapabilityShadingRateNV);
889 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700890
891 // raytracing
892 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700893 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700894 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700895 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700896 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700897 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700898 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700899 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700900 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700901 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700902 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700903 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700904 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700905 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700906 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700907 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700908 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700909 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700910 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700911 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700912 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700913 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700914 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700915 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700916 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700917 return spv::BuiltInWorldToObjectNV;
918 case glslang::EbvIncomingRayFlagsNV:
919 return spv::BuiltInIncomingRayFlagsNV;
Chao Chen9eada4b2018-09-19 11:39:56 -0700920 case glslang::EbvBaryCoordNV:
921 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
922 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
923 return spv::BuiltInBaryCoordNV;
924 case glslang::EbvBaryCoordNoPerspNV:
925 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
926 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
927 return spv::BuiltInBaryCoordNoPerspNV;
Chao Chen3c366992018-09-19 11:41:59 -0700928 case glslang::EbvTaskCountNV:
929 return spv::BuiltInTaskCountNV;
930 case glslang::EbvPrimitiveCountNV:
931 return spv::BuiltInPrimitiveCountNV;
932 case glslang::EbvPrimitiveIndicesNV:
933 return spv::BuiltInPrimitiveIndicesNV;
934 case glslang::EbvClipDistancePerViewNV:
935 return spv::BuiltInClipDistancePerViewNV;
936 case glslang::EbvCullDistancePerViewNV:
937 return spv::BuiltInCullDistancePerViewNV;
938 case glslang::EbvLayerPerViewNV:
939 return spv::BuiltInLayerPerViewNV;
940 case glslang::EbvMeshViewCountNV:
941 return spv::BuiltInMeshViewCountNV;
942 case glslang::EbvMeshViewIndicesNV:
943 return spv::BuiltInMeshViewIndicesNV;
chaoc771d89f2017-01-13 01:10:53 -0800944#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800945 default:
946 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600947 }
948}
949
Rex Xufc618912015-09-09 16:42:49 +0800950// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700951spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800952{
953 assert(type.getBasicType() == glslang::EbtSampler);
954
John Kessenich5d0fa972016-02-15 11:57:00 -0700955 // Check for capabilities
956 switch (type.getQualifier().layoutFormat) {
957 case glslang::ElfRg32f:
958 case glslang::ElfRg16f:
959 case glslang::ElfR11fG11fB10f:
960 case glslang::ElfR16f:
961 case glslang::ElfRgba16:
962 case glslang::ElfRgb10A2:
963 case glslang::ElfRg16:
964 case glslang::ElfRg8:
965 case glslang::ElfR16:
966 case glslang::ElfR8:
967 case glslang::ElfRgba16Snorm:
968 case glslang::ElfRg16Snorm:
969 case glslang::ElfRg8Snorm:
970 case glslang::ElfR16Snorm:
971 case glslang::ElfR8Snorm:
972
973 case glslang::ElfRg32i:
974 case glslang::ElfRg16i:
975 case glslang::ElfRg8i:
976 case glslang::ElfR16i:
977 case glslang::ElfR8i:
978
979 case glslang::ElfRgb10a2ui:
980 case glslang::ElfRg32ui:
981 case glslang::ElfRg16ui:
982 case glslang::ElfRg8ui:
983 case glslang::ElfR16ui:
984 case glslang::ElfR8ui:
985 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
986 break;
987
988 default:
989 break;
990 }
991
992 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800993 switch (type.getQualifier().layoutFormat) {
994 case glslang::ElfNone: return spv::ImageFormatUnknown;
995 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
996 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
997 case glslang::ElfR32f: return spv::ImageFormatR32f;
998 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
999 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1000 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1001 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1002 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1003 case glslang::ElfR16f: return spv::ImageFormatR16f;
1004 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1005 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1006 case glslang::ElfRg16: return spv::ImageFormatRg16;
1007 case glslang::ElfRg8: return spv::ImageFormatRg8;
1008 case glslang::ElfR16: return spv::ImageFormatR16;
1009 case glslang::ElfR8: return spv::ImageFormatR8;
1010 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1011 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1012 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1013 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1014 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1015 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1016 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1017 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1018 case glslang::ElfR32i: return spv::ImageFormatR32i;
1019 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1020 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1021 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1022 case glslang::ElfR16i: return spv::ImageFormatR16i;
1023 case glslang::ElfR8i: return spv::ImageFormatR8i;
1024 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1025 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1026 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1027 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1028 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1029 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1030 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1031 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1032 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1033 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001034 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001035 }
1036}
1037
John Kesseniche18fd202018-01-30 11:01:39 -07001038spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001039{
John Kesseniche18fd202018-01-30 11:01:39 -07001040 if (selectionNode.getFlatten())
1041 return spv::SelectionControlFlattenMask;
1042 if (selectionNode.getDontFlatten())
1043 return spv::SelectionControlDontFlattenMask;
1044 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001045}
1046
John Kesseniche18fd202018-01-30 11:01:39 -07001047spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001048{
John Kesseniche18fd202018-01-30 11:01:39 -07001049 if (switchNode.getFlatten())
1050 return spv::SelectionControlFlattenMask;
1051 if (switchNode.getDontFlatten())
1052 return spv::SelectionControlDontFlattenMask;
1053 return spv::SelectionControlMaskNone;
1054}
1055
John Kessenicha2858d92018-01-31 08:11:18 -07001056// return a non-0 dependency if the dependency argument must be set
1057spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001058 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001059{
1060 spv::LoopControlMask control = spv::LoopControlMaskNone;
1061
1062 if (loopNode.getDontUnroll())
1063 control = control | spv::LoopControlDontUnrollMask;
1064 if (loopNode.getUnroll())
1065 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001066 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001067 control = control | spv::LoopControlDependencyInfiniteMask;
1068 else if (loopNode.getLoopDependency() > 0) {
1069 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001070 operands.push_back((unsigned int)loopNode.getLoopDependency());
1071 }
1072 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1073 if (loopNode.getMinIterations() > 0) {
1074 control = control | spv::LoopControlMinIterationsMask;
1075 operands.push_back(loopNode.getMinIterations());
1076 }
1077 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1078 control = control | spv::LoopControlMaxIterationsMask;
1079 operands.push_back(loopNode.getMaxIterations());
1080 }
1081 if (loopNode.getIterationMultiple() > 1) {
1082 control = control | spv::LoopControlIterationMultipleMask;
1083 operands.push_back(loopNode.getIterationMultiple());
1084 }
1085 if (loopNode.getPeelCount() > 0) {
1086 control = control | spv::LoopControlPeelCountMask;
1087 operands.push_back(loopNode.getPeelCount());
1088 }
1089 if (loopNode.getPartialCount() > 0) {
1090 control = control | spv::LoopControlPartialCountMask;
1091 operands.push_back(loopNode.getPartialCount());
1092 }
John Kessenicha2858d92018-01-31 08:11:18 -07001093 }
John Kesseniche18fd202018-01-30 11:01:39 -07001094
1095 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001096}
1097
John Kessenicha5c5fb62017-05-05 05:09:58 -06001098// Translate glslang type to SPIR-V storage class.
1099spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1100{
1101 if (type.getQualifier().isPipeInput())
1102 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001103 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001104 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001105
1106 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1107 type.getQualifier().storage == glslang::EvqUniform) {
1108 if (type.getBasicType() == glslang::EbtAtomicUint)
1109 return spv::StorageClassAtomicCounter;
1110 if (type.containsOpaque())
1111 return spv::StorageClassUniformConstant;
1112 }
1113
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001114#ifdef NV_EXTENSIONS
1115 if (type.getQualifier().isUniformOrBuffer() &&
1116 type.getQualifier().layoutShaderRecordNV) {
1117 return spv::StorageClassShaderRecordBufferNV;
1118 }
1119#endif
1120
John Kessenichbed4e4f2017-09-08 02:38:07 -06001121 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001122 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001123 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001124 }
1125
1126 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001127 if (type.getQualifier().layoutPushConstant)
1128 return spv::StorageClassPushConstant;
1129 if (type.getBasicType() == glslang::EbtBlock)
1130 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001131 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001132 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001133
1134 switch (type.getQualifier().storage) {
1135 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1136 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1137 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1138 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001139#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001140 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1141 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1142 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1143 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1144 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001145#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001146 default:
1147 assert(0);
1148 break;
1149 }
1150
1151 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001152}
1153
John Kessenich5611c6d2018-04-05 11:25:02 -06001154// Add capabilities pertaining to how an array is indexed.
1155void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1156 const glslang::TType& indexType)
1157{
1158 if (indexType.getQualifier().isNonUniform()) {
1159 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001160 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001161 if (baseType.getBasicType() == glslang::EbtSampler) {
1162 if (baseType.getQualifier().hasAttachment())
1163 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1164 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1165 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1166 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1167 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1168 else if (baseType.isImage())
1169 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1170 else if (baseType.isTexture())
1171 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1172 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1173 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1174 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1175 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1176 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1177 }
1178 } else {
1179 // assume a dynamically uniform index
1180 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001181 if (baseType.getQualifier().hasAttachment()) {
1182 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001183 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001184 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1185 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001186 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001187 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1188 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001189 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001190 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001191 }
1192 }
1193}
1194
qining25262b32016-05-06 17:25:16 -04001195// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001196// descriptor set.
1197bool IsDescriptorResource(const glslang::TType& type)
1198{
John Kessenichf7497e22016-03-08 21:36:22 -07001199 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001200 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001201 return type.getQualifier().isUniformOrBuffer() &&
1202#ifdef NV_EXTENSIONS
1203 ! type.getQualifier().layoutShaderRecordNV &&
1204#endif
1205 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001206
1207 // non block...
1208 // basically samplerXXX/subpass/sampler/texture are all included
1209 // if they are the global-scope-class, not the function parameter
1210 // (or local, if they ever exist) class.
1211 if (type.getBasicType() == glslang::EbtSampler)
1212 return type.getQualifier().isUniformOrBuffer();
1213
1214 // None of the above.
1215 return false;
1216}
1217
John Kesseniche0b6cad2015-12-24 10:30:13 -07001218void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1219{
1220 if (child.layoutMatrix == glslang::ElmNone)
1221 child.layoutMatrix = parent.layoutMatrix;
1222
1223 if (parent.invariant)
1224 child.invariant = true;
1225 if (parent.nopersp)
1226 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001227#ifdef AMD_EXTENSIONS
1228 if (parent.explicitInterp)
1229 child.explicitInterp = true;
1230#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001231 if (parent.flat)
1232 child.flat = true;
1233 if (parent.centroid)
1234 child.centroid = true;
1235 if (parent.patch)
1236 child.patch = true;
1237 if (parent.sample)
1238 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001239 if (parent.coherent)
1240 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001241 if (parent.devicecoherent)
1242 child.devicecoherent = true;
1243 if (parent.queuefamilycoherent)
1244 child.queuefamilycoherent = true;
1245 if (parent.workgroupcoherent)
1246 child.workgroupcoherent = true;
1247 if (parent.subgroupcoherent)
1248 child.subgroupcoherent = true;
1249 if (parent.nonprivate)
1250 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001251 if (parent.volatil)
1252 child.volatil = true;
1253 if (parent.restrict)
1254 child.restrict = true;
1255 if (parent.readonly)
1256 child.readonly = true;
1257 if (parent.writeonly)
1258 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001259#ifdef NV_EXTENSIONS
1260 if (parent.perPrimitiveNV)
1261 child.perPrimitiveNV = true;
1262 if (parent.perViewNV)
1263 child.perViewNV = true;
1264 if (parent.perTaskNV)
1265 child.perTaskNV = true;
1266#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001267}
1268
John Kessenichf2b7f332016-09-01 17:05:23 -06001269bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001270{
John Kessenich7b9fa252016-01-21 18:56:57 -07001271 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001272 // - struct members might inherit from a struct declaration
1273 // (note that non-block structs don't explicitly inherit,
1274 // only implicitly, meaning no decoration involved)
1275 // - affect decorations on the struct members
1276 // (note smooth does not, and expecting something like volatile
1277 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001278 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001279 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001280}
1281
John Kessenich140f3df2015-06-26 16:58:36 -06001282//
1283// Implement the TGlslangToSpvTraverser class.
1284//
1285
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001286TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001287 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1288 : TIntermTraverser(true, false, true),
1289 options(options),
1290 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001291 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001292 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001293 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001294 glslangIntermediate(glslangIntermediate)
1295{
1296 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1297
1298 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001299 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1300 glslangIntermediate->getVersion());
1301
John Kessenich121853f2017-05-31 17:11:16 -06001302 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001303 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001304 builder.setSourceFile(glslangIntermediate->getSourceFile());
1305
1306 // Set the source shader's text. If for SPV version 1.0, include
1307 // a preamble in comments stating the OpModuleProcessed instructions.
1308 // Otherwise, emit those as actual instructions.
1309 std::string text;
1310 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1311 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001312 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001313 text.append("// OpModuleProcessed ");
1314 text.append(processes[p]);
1315 text.append("\n");
1316 } else
1317 builder.addModuleProcessed(processes[p]);
1318 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001319 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001320 text.append("#line 1\n");
1321 text.append(glslangIntermediate->getSourceText());
1322 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001323 // Pass name and text for all included files
1324 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1325 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1326 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001327 }
John Kessenich140f3df2015-06-26 16:58:36 -06001328 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001329
1330 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1331 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1332
1333 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1334 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1335 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1336 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1337 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001338 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001339 memoryModel = spv::MemoryModelVulkanKHR;
1340 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001341 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001342 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001343 builder.setMemoryModel(addressingModel, memoryModel);
1344
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001345 if (glslangIntermediate->usingVariablePointers()) {
1346 builder.addCapability(spv::CapabilityVariablePointers);
1347 }
1348
John Kessenicheee9d532016-09-19 18:09:30 -06001349 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1350 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001351
1352 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001353 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1354 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001355 builder.addSourceExtension(it->c_str());
1356
1357 // Add the top-level modes for this shader.
1358
John Kessenich92187592016-02-01 13:45:25 -07001359 if (glslangIntermediate->getXfbMode()) {
1360 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001361 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001362 }
John Kessenich140f3df2015-06-26 16:58:36 -06001363
1364 unsigned int mode;
1365 switch (glslangIntermediate->getStage()) {
1366 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001367 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001368 break;
1369
steve-lunarge7412492017-03-23 11:56:07 -06001370 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001371 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001372 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001373
steve-lunarge7412492017-03-23 11:56:07 -06001374 glslang::TLayoutGeometry primitive;
1375
1376 if (glslangIntermediate->getStage() == EShLangTessControl) {
1377 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1378 primitive = glslangIntermediate->getOutputPrimitive();
1379 } else {
1380 primitive = glslangIntermediate->getInputPrimitive();
1381 }
1382
1383 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001384 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1385 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1386 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001387 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001388 }
John Kessenich4016e382016-07-15 11:53:56 -06001389 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001390 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1391
John Kesseniche6903322015-10-13 16:29:02 -06001392 switch (glslangIntermediate->getVertexSpacing()) {
1393 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1394 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1395 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001396 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001397 }
John Kessenich4016e382016-07-15 11:53:56 -06001398 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001399 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1400
1401 switch (glslangIntermediate->getVertexOrder()) {
1402 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1403 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001404 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001405 }
John Kessenich4016e382016-07-15 11:53:56 -06001406 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001407 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1408
1409 if (glslangIntermediate->getPointMode())
1410 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001411 break;
1412
1413 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001414 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001415 switch (glslangIntermediate->getInputPrimitive()) {
1416 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1417 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1418 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001419 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001420 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001421 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001422 }
John Kessenich4016e382016-07-15 11:53:56 -06001423 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001424 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001425
John Kessenich140f3df2015-06-26 16:58:36 -06001426 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1427
1428 switch (glslangIntermediate->getOutputPrimitive()) {
1429 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1430 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1431 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001432 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001433 }
John Kessenich4016e382016-07-15 11:53:56 -06001434 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001435 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1436 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1437 break;
1438
1439 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001440 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001441 if (glslangIntermediate->getPixelCenterInteger())
1442 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001443
John Kessenich140f3df2015-06-26 16:58:36 -06001444 if (glslangIntermediate->getOriginUpperLeft())
1445 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001446 else
1447 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001448
1449 if (glslangIntermediate->getEarlyFragmentTests())
1450 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1451
chaocc1204522017-06-30 17:14:30 -07001452 if (glslangIntermediate->getPostDepthCoverage()) {
1453 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1454 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1455 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1456 }
1457
John Kesseniche6903322015-10-13 16:29:02 -06001458 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001459 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1460 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001461 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001462 }
John Kessenich4016e382016-07-15 11:53:56 -06001463 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001464 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1465
1466 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1467 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001468 break;
1469
1470 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001471 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001472 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1473 glslangIntermediate->getLocalSize(1),
1474 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001475#ifdef NV_EXTENSIONS
1476 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1477 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1478 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1479 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1480 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1481 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1482 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1483 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1484 }
1485#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001486 break;
1487
Chao Chen3c366992018-09-19 11:41:59 -07001488#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001489 case EShLangRayGenNV:
1490 case EShLangIntersectNV:
1491 case EShLangAnyHitNV:
1492 case EShLangClosestHitNV:
1493 case EShLangMissNV:
1494 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001495 builder.addCapability(spv::CapabilityRayTracingNV);
1496 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001497 break;
Chao Chen3c366992018-09-19 11:41:59 -07001498 case EShLangTaskNV:
1499 case EShLangMeshNV:
1500 builder.addCapability(spv::CapabilityMeshShadingNV);
1501 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1502 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1503 glslangIntermediate->getLocalSize(1),
1504 glslangIntermediate->getLocalSize(2));
1505 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1506 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1507 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1508
1509 switch (glslangIntermediate->getOutputPrimitive()) {
1510 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1511 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1512 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1513 default: mode = spv::ExecutionModeMax; break;
1514 }
1515 if (mode != spv::ExecutionModeMax)
1516 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1517 }
1518 break;
1519#endif
1520
John Kessenich140f3df2015-06-26 16:58:36 -06001521 default:
1522 break;
1523 }
John Kessenich140f3df2015-06-26 16:58:36 -06001524}
1525
John Kessenichfca82622016-11-26 13:23:20 -07001526// Finish creating SPV, after the traversal is complete.
1527void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001528{
John Kessenichf04c51b2018-08-03 15:56:12 -06001529 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001530 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001531 builder.setBuildPoint(shaderEntry->getLastBlock());
1532 builder.leaveFunction();
1533 }
1534
John Kessenich7ba63412015-12-20 17:37:07 -07001535 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001536 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1537 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001538
John Kessenichf04c51b2018-08-03 15:56:12 -06001539 // Add capabilities, extensions, remove unneeded decorations, etc.,
1540 // based on the resulting SPIR-V.
1541 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001542}
1543
John Kessenichfca82622016-11-26 13:23:20 -07001544// Write the SPV into 'out'.
1545void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001546{
John Kessenichfca82622016-11-26 13:23:20 -07001547 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001548}
1549
1550//
1551// Implement the traversal functions.
1552//
1553// Return true from interior nodes to have the external traversal
1554// continue on to children. Return false if children were
1555// already processed.
1556//
1557
1558//
qining25262b32016-05-06 17:25:16 -04001559// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001560// - uniform/input reads
1561// - output writes
1562// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1563// - something simple that degenerates into the last bullet
1564//
1565void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1566{
qining75d1d802016-04-06 14:42:01 -04001567 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1568 if (symbol->getType().getQualifier().isSpecConstant())
1569 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1570
John Kessenich140f3df2015-06-26 16:58:36 -06001571 // getSymbolId() will set up all the IO decorations on the first call.
1572 // Formal function parameters were mapped during makeFunctions().
1573 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001574
1575 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1576 if (builder.isPointer(id)) {
John Kessenich7c7731e2019-01-04 16:47:06 +07001577 // Consider adding to the OpEntryPoint interface list.
1578 // Only looking at structures if they have at least one member.
1579 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1580 spv::StorageClass sc = builder.getStorageClass(id);
1581 // Before SPIR-V 1.4, we only want to include Input and Output.
1582 // Starting with SPIR-V 1.4, we want all globals.
1583 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1584 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001585 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001586 }
John Kessenich5f77d862017-09-19 11:09:59 -06001587 }
John Kessenich7ba63412015-12-20 17:37:07 -07001588 }
1589
1590 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001591 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001592 // Prepare to generate code for the access
1593
1594 // L-value chains will be computed left to right. We're on the symbol now,
1595 // which is the left-most part of the access chain, so now is "clear" time,
1596 // followed by setting the base.
1597 builder.clearAccessChain();
1598
1599 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001600 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001601 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001602 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001603 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001604 // These are also pure R-values.
1605 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001606 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001607 builder.setAccessChainRValue(id);
1608 else
1609 builder.setAccessChainLValue(id);
1610 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001611
1612 // Process linkage-only nodes for any special additional interface work.
1613 if (linkageOnly) {
1614 if (glslangIntermediate->getHlslFunctionality1()) {
1615 // Map implicit counter buffers to their originating buffers, which should have been
1616 // seen by now, given earlier pruning of unused counters, and preservation of order
1617 // of declaration.
1618 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1619 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1620 // Save possible originating buffers for counter buffers, keyed by
1621 // making the potential counter-buffer name.
1622 std::string keyName = symbol->getName().c_str();
1623 keyName = glslangIntermediate->addCounterBufferName(keyName);
1624 counterOriginator[keyName] = symbol;
1625 } else {
1626 // Handle a counter buffer, by finding the saved originating buffer.
1627 std::string keyName = symbol->getName().c_str();
1628 auto it = counterOriginator.find(keyName);
1629 if (it != counterOriginator.end()) {
1630 id = getSymbolId(it->second);
1631 if (id != spv::NoResult) {
1632 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001633 if (counterId != spv::NoResult) {
1634 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001635 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001636 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001637 }
1638 }
1639 }
1640 }
1641 }
1642 }
John Kessenich140f3df2015-06-26 16:58:36 -06001643}
1644
1645bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1646{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001647 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001648
qining40887662016-04-03 22:20:42 -04001649 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1650 if (node->getType().getQualifier().isSpecConstant())
1651 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1652
John Kessenich140f3df2015-06-26 16:58:36 -06001653 // First, handle special cases
1654 switch (node->getOp()) {
1655 case glslang::EOpAssign:
1656 case glslang::EOpAddAssign:
1657 case glslang::EOpSubAssign:
1658 case glslang::EOpMulAssign:
1659 case glslang::EOpVectorTimesMatrixAssign:
1660 case glslang::EOpVectorTimesScalarAssign:
1661 case glslang::EOpMatrixTimesScalarAssign:
1662 case glslang::EOpMatrixTimesMatrixAssign:
1663 case glslang::EOpDivAssign:
1664 case glslang::EOpModAssign:
1665 case glslang::EOpAndAssign:
1666 case glslang::EOpInclusiveOrAssign:
1667 case glslang::EOpExclusiveOrAssign:
1668 case glslang::EOpLeftShiftAssign:
1669 case glslang::EOpRightShiftAssign:
1670 // A bin-op assign "a += b" means the same thing as "a = a + b"
1671 // where a is evaluated before b. For a simple assignment, GLSL
1672 // says to evaluate the left before the right. So, always, left
1673 // node then right node.
1674 {
1675 // get the left l-value, save it away
1676 builder.clearAccessChain();
1677 node->getLeft()->traverse(this);
1678 spv::Builder::AccessChain lValue = builder.getAccessChain();
1679
1680 // evaluate the right
1681 builder.clearAccessChain();
1682 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001683 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001684
1685 if (node->getOp() != glslang::EOpAssign) {
1686 // the left is also an r-value
1687 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001688 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001689
1690 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001691 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001692 TranslateNoContractionDecoration(node->getType().getQualifier()),
1693 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001694 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001695 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1696 node->getType().getBasicType());
1697
1698 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001699 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001700 }
1701
1702 // store the result
1703 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001704 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001705
1706 // assignments are expressions having an rValue after they are evaluated...
1707 builder.clearAccessChain();
1708 builder.setAccessChainRValue(rValue);
1709 }
1710 return false;
1711 case glslang::EOpIndexDirect:
1712 case glslang::EOpIndexDirectStruct:
1713 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001714 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001715 // Get the left part of the access chain.
1716 node->getLeft()->traverse(this);
1717
1718 // Add the next element in the chain
1719
David Netoa901ffe2016-06-08 14:11:40 +01001720 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001721 if (! node->getLeft()->getType().isArray() &&
1722 node->getLeft()->getType().isVector() &&
1723 node->getOp() == glslang::EOpIndexDirect) {
1724 // This is essentially a hard-coded vector swizzle of size 1,
1725 // so short circuit the access-chain stuff with a swizzle.
1726 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001727 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001728 int dummySize;
1729 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1730 TranslateCoherent(node->getLeft()->getType()),
1731 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001732 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001733
1734 // Load through a block reference is performed with a dot operator that
1735 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1736 // do a load and reset the access chain.
1737 if (node->getLeft()->getBasicType() == glslang::EbtReference &&
1738 !node->getLeft()->getType().isArray() &&
1739 node->getOp() == glslang::EOpIndexDirectStruct)
1740 {
1741 spv::Id left = accessChainLoad(node->getLeft()->getType());
1742 builder.clearAccessChain();
1743 builder.setAccessChainLValue(left);
1744 }
1745
David Netoa901ffe2016-06-08 14:11:40 +01001746 int spvIndex = glslangIndex;
1747 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1748 node->getOp() == glslang::EOpIndexDirectStruct)
1749 {
1750 // This may be, e.g., an anonymous block-member selection, which generally need
1751 // index remapping due to hidden members in anonymous blocks.
1752 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1753 assert(remapper.size() > 0);
1754 spvIndex = remapper[glslangIndex];
1755 }
John Kessenichebb50532016-05-16 19:22:05 -06001756
David Netoa901ffe2016-06-08 14:11:40 +01001757 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001758 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001759
1760 // Add capabilities here for accessing PointSize and clip/cull distance.
1761 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001762 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001763 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001764 }
1765 }
1766 return false;
1767 case glslang::EOpIndexIndirect:
1768 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001769 // Array, matrix, or vector indirection with variable index.
1770 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001771 // matrices are arrays of vectors, so will also work for a matrix.
1772 // Will use the access chain's 'component' for variable index into a vector.
1773
1774 // This adapter is building access chains left to right.
1775 // Set up the access chain to the left.
1776 node->getLeft()->traverse(this);
1777
1778 // save it so that computing the right side doesn't trash it
1779 spv::Builder::AccessChain partial = builder.getAccessChain();
1780
1781 // compute the next index in the chain
1782 builder.clearAccessChain();
1783 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001784 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001785
John Kessenich5611c6d2018-04-05 11:25:02 -06001786 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1787
John Kessenich140f3df2015-06-26 16:58:36 -06001788 // restore the saved access chain
1789 builder.setAccessChain(partial);
1790
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001791 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1792 int dummySize;
1793 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1794 TranslateCoherent(node->getLeft()->getType()),
1795 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1796 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001797 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001798 }
1799 return false;
1800 case glslang::EOpVectorSwizzle:
1801 {
1802 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001803 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001804 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001805 int dummySize;
1806 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1807 TranslateCoherent(node->getLeft()->getType()),
1808 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001809 }
1810 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001811 case glslang::EOpMatrixSwizzle:
1812 logger->missingFunctionality("matrix swizzle");
1813 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001814 case glslang::EOpLogicalOr:
1815 case glslang::EOpLogicalAnd:
1816 {
1817
1818 // These may require short circuiting, but can sometimes be done as straight
1819 // binary operations. The right operand must be short circuited if it has
1820 // side effects, and should probably be if it is complex.
1821 if (isTrivial(node->getRight()->getAsTyped()))
1822 break; // handle below as a normal binary operation
1823 // otherwise, we need to do dynamic short circuiting on the right operand
1824 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1825 builder.clearAccessChain();
1826 builder.setAccessChainRValue(result);
1827 }
1828 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001829 default:
1830 break;
1831 }
1832
1833 // Assume generic binary op...
1834
John Kessenich32cfd492016-02-02 12:37:46 -07001835 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001836 builder.clearAccessChain();
1837 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001838 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001839
John Kessenich32cfd492016-02-02 12:37:46 -07001840 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001841 builder.clearAccessChain();
1842 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001843 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001844
John Kessenich32cfd492016-02-02 12:37:46 -07001845 // get result
John Kessenichead86222018-03-28 18:01:20 -06001846 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001847 TranslateNoContractionDecoration(node->getType().getQualifier()),
1848 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001849 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001850 convertGlslangToSpvType(node->getType()), left, right,
1851 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001852
John Kessenich50e57562015-12-21 21:21:11 -07001853 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001854 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001855 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001856 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001857 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001858 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001859 return false;
1860 }
John Kessenich140f3df2015-06-26 16:58:36 -06001861}
1862
1863bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1864{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001865 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001866
qining40887662016-04-03 22:20:42 -04001867 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1868 if (node->getType().getQualifier().isSpecConstant())
1869 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1870
John Kessenichfc51d282015-08-19 13:34:18 -06001871 spv::Id result = spv::NoResult;
1872
1873 // try texturing first
1874 result = createImageTextureFunctionCall(node);
1875 if (result != spv::NoResult) {
1876 builder.clearAccessChain();
1877 builder.setAccessChainRValue(result);
1878
1879 return false; // done with this node
1880 }
1881
1882 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001883
1884 if (node->getOp() == glslang::EOpArrayLength) {
1885 // Quite special; won't want to evaluate the operand.
1886
John Kessenich5611c6d2018-04-05 11:25:02 -06001887 // Currently, the front-end does not allow .length() on an array until it is sized,
1888 // except for the last block membeor of an SSBO.
1889 // TODO: If this changes, link-time sized arrays might show up here, and need their
1890 // size extracted.
1891
John Kessenichc9a80832015-09-12 12:17:44 -06001892 // Normal .length() would have been constant folded by the front-end.
1893 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001894 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001895
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001896 spv::Id length;
1897 if (node->getOperand()->getType().isCoopMat()) {
1898 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1899
1900 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
1901 assert(builder.isCooperativeMatrixType(typeId));
1902
1903 length = builder.createCooperativeMatrixLength(typeId);
1904 } else {
1905 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1906 block->traverse(this);
1907 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1908 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
1909 }
John Kessenichc9a80832015-09-12 12:17:44 -06001910
John Kessenich8c869672018-11-28 07:01:37 -07001911 // GLSL semantics say the result of .length() is an int, while SPIR-V says
1912 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
1913 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001914 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
1915 if (builder.isInSpecConstCodeGenMode()) {
1916 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
1917 } else {
1918 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
1919 }
1920 }
John Kessenich8c869672018-11-28 07:01:37 -07001921
John Kessenichc9a80832015-09-12 12:17:44 -06001922 builder.clearAccessChain();
1923 builder.setAccessChainRValue(length);
1924
1925 return false;
1926 }
1927
John Kessenichfc51d282015-08-19 13:34:18 -06001928 // Start by evaluating the operand
1929
John Kessenich8c8505c2016-07-26 12:50:38 -06001930 // Does it need a swizzle inversion? If so, evaluation is inverted;
1931 // operate first on the swizzle base, then apply the swizzle.
1932 spv::Id invertedType = spv::NoType;
1933 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1934 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1935 invertedType = getInvertedSwizzleType(*node->getOperand());
1936
John Kessenich140f3df2015-06-26 16:58:36 -06001937 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001938 if (invertedType != spv::NoType)
1939 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1940 else
1941 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001942
Rex Xufc618912015-09-09 16:42:49 +08001943 spv::Id operand = spv::NoResult;
1944
1945 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1946 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001947 node->getOp() == glslang::EOpAtomicCounter ||
1948 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001949 operand = builder.accessChainGetLValue(); // Special case l-value operands
1950 else
John Kessenich32cfd492016-02-02 12:37:46 -07001951 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001952
John Kessenichead86222018-03-28 18:01:20 -06001953 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001954 TranslateNoContractionDecoration(node->getType().getQualifier()),
1955 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001956
1957 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001958 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001959 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001960
1961 // if not, then possibly an operation
1962 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001963 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001964
1965 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001966 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001967 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001968 builder.addDecoration(result, decorations.nonUniform);
1969 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001970
John Kessenich140f3df2015-06-26 16:58:36 -06001971 builder.clearAccessChain();
1972 builder.setAccessChainRValue(result);
1973
1974 return false; // done with this node
1975 }
1976
1977 // it must be a special case, check...
1978 switch (node->getOp()) {
1979 case glslang::EOpPostIncrement:
1980 case glslang::EOpPostDecrement:
1981 case glslang::EOpPreIncrement:
1982 case glslang::EOpPreDecrement:
1983 {
1984 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001985 spv::Id one = 0;
1986 if (node->getBasicType() == glslang::EbtFloat)
1987 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001988 else if (node->getBasicType() == glslang::EbtDouble)
1989 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001990 else if (node->getBasicType() == glslang::EbtFloat16)
1991 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001992 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1993 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001994 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1995 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001996 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1997 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001998 else
1999 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002000 glslang::TOperator op;
2001 if (node->getOp() == glslang::EOpPreIncrement ||
2002 node->getOp() == glslang::EOpPostIncrement)
2003 op = glslang::EOpAdd;
2004 else
2005 op = glslang::EOpSub;
2006
John Kessenichead86222018-03-28 18:01:20 -06002007 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002008 convertGlslangToSpvType(node->getType()), operand, one,
2009 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002010 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002011
2012 // The result of operation is always stored, but conditionally the
2013 // consumed result. The consumed result is always an r-value.
2014 builder.accessChainStore(result);
2015 builder.clearAccessChain();
2016 if (node->getOp() == glslang::EOpPreIncrement ||
2017 node->getOp() == glslang::EOpPreDecrement)
2018 builder.setAccessChainRValue(result);
2019 else
2020 builder.setAccessChainRValue(operand);
2021 }
2022
2023 return false;
2024
2025 case glslang::EOpEmitStreamVertex:
2026 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2027 return false;
2028 case glslang::EOpEndStreamPrimitive:
2029 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2030 return false;
2031
2032 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002033 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002034 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002035 }
John Kessenich140f3df2015-06-26 16:58:36 -06002036}
2037
2038bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2039{
qining27e04a02016-04-14 16:40:20 -04002040 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2041 if (node->getType().getQualifier().isSpecConstant())
2042 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2043
John Kessenichfc51d282015-08-19 13:34:18 -06002044 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002045 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2046 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002047
2048 // try texturing
2049 result = createImageTextureFunctionCall(node);
2050 if (result != spv::NoResult) {
2051 builder.clearAccessChain();
2052 builder.setAccessChainRValue(result);
2053
2054 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05002055 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08002056#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05002057 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08002058#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05002059 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002060 // "imageStore" is a special case, which has no result
2061 return false;
2062 }
John Kessenichfc51d282015-08-19 13:34:18 -06002063
John Kessenich140f3df2015-06-26 16:58:36 -06002064 glslang::TOperator binOp = glslang::EOpNull;
2065 bool reduceComparison = true;
2066 bool isMatrix = false;
2067 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002068 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002069
2070 assert(node->getOp());
2071
John Kessenichf6640762016-08-01 19:44:00 -06002072 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002073
2074 switch (node->getOp()) {
2075 case glslang::EOpSequence:
2076 {
2077 if (preVisit)
2078 ++sequenceDepth;
2079 else
2080 --sequenceDepth;
2081
2082 if (sequenceDepth == 1) {
2083 // If this is the parent node of all the functions, we want to see them
2084 // early, so all call points have actual SPIR-V functions to reference.
2085 // In all cases, still let the traverser visit the children for us.
2086 makeFunctions(node->getAsAggregate()->getSequence());
2087
John Kessenich6fccb3c2016-09-19 16:01:41 -06002088 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002089 // anything else gets there, so visit out of order, doing them all now.
2090 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2091
John Kessenich6a60c2f2016-12-08 21:01:59 -07002092 // Initializers are done, don't want to visit again, but functions and link objects need to be processed,
John Kessenich140f3df2015-06-26 16:58:36 -06002093 // so do them manually.
2094 visitFunctions(node->getAsAggregate()->getSequence());
2095
2096 return false;
2097 }
2098
2099 return true;
2100 }
2101 case glslang::EOpLinkerObjects:
2102 {
2103 if (visit == glslang::EvPreVisit)
2104 linkageOnly = true;
2105 else
2106 linkageOnly = false;
2107
2108 return true;
2109 }
2110 case glslang::EOpComma:
2111 {
2112 // processing from left to right naturally leaves the right-most
2113 // lying around in the access chain
2114 glslang::TIntermSequence& glslangOperands = node->getSequence();
2115 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2116 glslangOperands[i]->traverse(this);
2117
2118 return false;
2119 }
2120 case glslang::EOpFunction:
2121 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002122 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002123 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002124 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002125 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002126 } else {
2127 handleFunctionEntry(node);
2128 }
2129 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002130 if (inEntryPoint)
2131 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002132 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002133 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002134 }
2135
2136 return true;
2137 case glslang::EOpParameters:
2138 // Parameters will have been consumed by EOpFunction processing, but not
2139 // the body, so we still visited the function node's children, making this
2140 // child redundant.
2141 return false;
2142 case glslang::EOpFunctionCall:
2143 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002144 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002145 if (node->isUserDefined())
2146 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002147 // assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
John Kessenich6c292d32016-02-15 20:58:50 -07002148 if (result) {
2149 builder.clearAccessChain();
2150 builder.setAccessChainRValue(result);
2151 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002152 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002153
2154 return false;
2155 }
2156 case glslang::EOpConstructMat2x2:
2157 case glslang::EOpConstructMat2x3:
2158 case glslang::EOpConstructMat2x4:
2159 case glslang::EOpConstructMat3x2:
2160 case glslang::EOpConstructMat3x3:
2161 case glslang::EOpConstructMat3x4:
2162 case glslang::EOpConstructMat4x2:
2163 case glslang::EOpConstructMat4x3:
2164 case glslang::EOpConstructMat4x4:
2165 case glslang::EOpConstructDMat2x2:
2166 case glslang::EOpConstructDMat2x3:
2167 case glslang::EOpConstructDMat2x4:
2168 case glslang::EOpConstructDMat3x2:
2169 case glslang::EOpConstructDMat3x3:
2170 case glslang::EOpConstructDMat3x4:
2171 case glslang::EOpConstructDMat4x2:
2172 case glslang::EOpConstructDMat4x3:
2173 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002174 case glslang::EOpConstructIMat2x2:
2175 case glslang::EOpConstructIMat2x3:
2176 case glslang::EOpConstructIMat2x4:
2177 case glslang::EOpConstructIMat3x2:
2178 case glslang::EOpConstructIMat3x3:
2179 case glslang::EOpConstructIMat3x4:
2180 case glslang::EOpConstructIMat4x2:
2181 case glslang::EOpConstructIMat4x3:
2182 case glslang::EOpConstructIMat4x4:
2183 case glslang::EOpConstructUMat2x2:
2184 case glslang::EOpConstructUMat2x3:
2185 case glslang::EOpConstructUMat2x4:
2186 case glslang::EOpConstructUMat3x2:
2187 case glslang::EOpConstructUMat3x3:
2188 case glslang::EOpConstructUMat3x4:
2189 case glslang::EOpConstructUMat4x2:
2190 case glslang::EOpConstructUMat4x3:
2191 case glslang::EOpConstructUMat4x4:
2192 case glslang::EOpConstructBMat2x2:
2193 case glslang::EOpConstructBMat2x3:
2194 case glslang::EOpConstructBMat2x4:
2195 case glslang::EOpConstructBMat3x2:
2196 case glslang::EOpConstructBMat3x3:
2197 case glslang::EOpConstructBMat3x4:
2198 case glslang::EOpConstructBMat4x2:
2199 case glslang::EOpConstructBMat4x3:
2200 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002201 case glslang::EOpConstructF16Mat2x2:
2202 case glslang::EOpConstructF16Mat2x3:
2203 case glslang::EOpConstructF16Mat2x4:
2204 case glslang::EOpConstructF16Mat3x2:
2205 case glslang::EOpConstructF16Mat3x3:
2206 case glslang::EOpConstructF16Mat3x4:
2207 case glslang::EOpConstructF16Mat4x2:
2208 case glslang::EOpConstructF16Mat4x3:
2209 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002210 isMatrix = true;
2211 // fall through
2212 case glslang::EOpConstructFloat:
2213 case glslang::EOpConstructVec2:
2214 case glslang::EOpConstructVec3:
2215 case glslang::EOpConstructVec4:
2216 case glslang::EOpConstructDouble:
2217 case glslang::EOpConstructDVec2:
2218 case glslang::EOpConstructDVec3:
2219 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002220 case glslang::EOpConstructFloat16:
2221 case glslang::EOpConstructF16Vec2:
2222 case glslang::EOpConstructF16Vec3:
2223 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002224 case glslang::EOpConstructBool:
2225 case glslang::EOpConstructBVec2:
2226 case glslang::EOpConstructBVec3:
2227 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002228 case glslang::EOpConstructInt8:
2229 case glslang::EOpConstructI8Vec2:
2230 case glslang::EOpConstructI8Vec3:
2231 case glslang::EOpConstructI8Vec4:
2232 case glslang::EOpConstructUint8:
2233 case glslang::EOpConstructU8Vec2:
2234 case glslang::EOpConstructU8Vec3:
2235 case glslang::EOpConstructU8Vec4:
2236 case glslang::EOpConstructInt16:
2237 case glslang::EOpConstructI16Vec2:
2238 case glslang::EOpConstructI16Vec3:
2239 case glslang::EOpConstructI16Vec4:
2240 case glslang::EOpConstructUint16:
2241 case glslang::EOpConstructU16Vec2:
2242 case glslang::EOpConstructU16Vec3:
2243 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002244 case glslang::EOpConstructInt:
2245 case glslang::EOpConstructIVec2:
2246 case glslang::EOpConstructIVec3:
2247 case glslang::EOpConstructIVec4:
2248 case glslang::EOpConstructUint:
2249 case glslang::EOpConstructUVec2:
2250 case glslang::EOpConstructUVec3:
2251 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002252 case glslang::EOpConstructInt64:
2253 case glslang::EOpConstructI64Vec2:
2254 case glslang::EOpConstructI64Vec3:
2255 case glslang::EOpConstructI64Vec4:
2256 case glslang::EOpConstructUint64:
2257 case glslang::EOpConstructU64Vec2:
2258 case glslang::EOpConstructU64Vec3:
2259 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002260 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002261 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002262 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002263 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002264 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002265 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002266 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002267 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002268 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002269 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002270 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002271 else if (node->getOp() == glslang::EOpConstructStruct ||
2272 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2273 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002274 std::vector<spv::Id> constituents;
2275 for (int c = 0; c < (int)arguments.size(); ++c)
2276 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002277 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002278 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002279 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002280 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002281 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002282
2283 builder.clearAccessChain();
2284 builder.setAccessChainRValue(constructed);
2285
2286 return false;
2287 }
2288
2289 // These six are component-wise compares with component-wise results.
2290 // Forward on to createBinaryOperation(), requesting a vector result.
2291 case glslang::EOpLessThan:
2292 case glslang::EOpGreaterThan:
2293 case glslang::EOpLessThanEqual:
2294 case glslang::EOpGreaterThanEqual:
2295 case glslang::EOpVectorEqual:
2296 case glslang::EOpVectorNotEqual:
2297 {
2298 // Map the operation to a binary
2299 binOp = node->getOp();
2300 reduceComparison = false;
2301 switch (node->getOp()) {
2302 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2303 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2304 default: binOp = node->getOp(); break;
2305 }
2306
2307 break;
2308 }
2309 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002310 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002311 binOp = glslang::EOpMul;
2312 break;
2313 case glslang::EOpOuterProduct:
2314 // two vectors multiplied to make a matrix
2315 binOp = glslang::EOpOuterProduct;
2316 break;
2317 case glslang::EOpDot:
2318 {
qining25262b32016-05-06 17:25:16 -04002319 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002320 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002321 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002322 binOp = glslang::EOpMul;
2323 break;
2324 }
2325 case glslang::EOpMod:
2326 // when an aggregate, this is the floating-point mod built-in function,
2327 // which can be emitted by the one in createBinaryOperation()
2328 binOp = glslang::EOpMod;
2329 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002330 case glslang::EOpEmitVertex:
2331 case glslang::EOpEndPrimitive:
2332 case glslang::EOpBarrier:
2333 case glslang::EOpMemoryBarrier:
2334 case glslang::EOpMemoryBarrierAtomicCounter:
2335 case glslang::EOpMemoryBarrierBuffer:
2336 case glslang::EOpMemoryBarrierImage:
2337 case glslang::EOpMemoryBarrierShared:
2338 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002339 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002340 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002341 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002342 case glslang::EOpWorkgroupMemoryBarrier:
2343 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002344 case glslang::EOpSubgroupBarrier:
2345 case glslang::EOpSubgroupMemoryBarrier:
2346 case glslang::EOpSubgroupMemoryBarrierBuffer:
2347 case glslang::EOpSubgroupMemoryBarrierImage:
2348 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002349 noReturnValue = true;
2350 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2351 break;
2352
Jeff Bolz36831c92018-09-05 10:11:41 -05002353 case glslang::EOpAtomicStore:
2354 noReturnValue = true;
2355 // fallthrough
2356 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002357 case glslang::EOpAtomicAdd:
2358 case glslang::EOpAtomicMin:
2359 case glslang::EOpAtomicMax:
2360 case glslang::EOpAtomicAnd:
2361 case glslang::EOpAtomicOr:
2362 case glslang::EOpAtomicXor:
2363 case glslang::EOpAtomicExchange:
2364 case glslang::EOpAtomicCompSwap:
2365 atomic = true;
2366 break;
2367
John Kessenich0d0c6d32017-07-23 16:08:26 -06002368 case glslang::EOpAtomicCounterAdd:
2369 case glslang::EOpAtomicCounterSubtract:
2370 case glslang::EOpAtomicCounterMin:
2371 case glslang::EOpAtomicCounterMax:
2372 case glslang::EOpAtomicCounterAnd:
2373 case glslang::EOpAtomicCounterOr:
2374 case glslang::EOpAtomicCounterXor:
2375 case glslang::EOpAtomicCounterExchange:
2376 case glslang::EOpAtomicCounterCompSwap:
2377 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2378 builder.addCapability(spv::CapabilityAtomicStorageOps);
2379 atomic = true;
2380 break;
2381
Chao Chen3c366992018-09-19 11:41:59 -07002382#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002383 case glslang::EOpIgnoreIntersectionNV:
2384 case glslang::EOpTerminateRayNV:
2385 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002386 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002387 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2388 noReturnValue = true;
2389 break;
2390#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002391 case glslang::EOpCooperativeMatrixLoad:
2392 case glslang::EOpCooperativeMatrixStore:
2393 noReturnValue = true;
2394 break;
Chao Chen3c366992018-09-19 11:41:59 -07002395
John Kessenich140f3df2015-06-26 16:58:36 -06002396 default:
2397 break;
2398 }
2399
2400 //
2401 // See if it maps to a regular operation.
2402 //
John Kessenich140f3df2015-06-26 16:58:36 -06002403 if (binOp != glslang::EOpNull) {
2404 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2405 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2406 assert(left && right);
2407
2408 builder.clearAccessChain();
2409 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002410 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002411
2412 builder.clearAccessChain();
2413 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002414 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002415
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002416 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002417 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002418 TranslateNoContractionDecoration(node->getType().getQualifier()),
2419 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002420 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002421 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002422 left->getType().getBasicType(), reduceComparison);
2423
2424 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002425 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002426 builder.clearAccessChain();
2427 builder.setAccessChainRValue(result);
2428
2429 return false;
2430 }
2431
John Kessenich426394d2015-07-23 10:22:48 -06002432 //
2433 // Create the list of operands.
2434 //
John Kessenich140f3df2015-06-26 16:58:36 -06002435 glslang::TIntermSequence& glslangOperands = node->getSequence();
2436 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002437 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002438 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002439 // special case l-value operands; there are just a few
2440 bool lvalue = false;
2441 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002442 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002443 case glslang::EOpModf:
2444 if (arg == 1)
2445 lvalue = true;
2446 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002447 case glslang::EOpInterpolateAtSample:
2448 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002449#ifdef AMD_EXTENSIONS
2450 case glslang::EOpInterpolateAtVertex:
2451#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002452 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002453 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002454
2455 // Does it need a swizzle inversion? If so, evaluation is inverted;
2456 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002457 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002458 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2459 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2460 }
Rex Xu7a26c172015-12-08 17:12:09 +08002461 break;
Rex Xud4782c12015-09-06 16:30:11 +08002462 case glslang::EOpAtomicAdd:
2463 case glslang::EOpAtomicMin:
2464 case glslang::EOpAtomicMax:
2465 case glslang::EOpAtomicAnd:
2466 case glslang::EOpAtomicOr:
2467 case glslang::EOpAtomicXor:
2468 case glslang::EOpAtomicExchange:
2469 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002470 case glslang::EOpAtomicLoad:
2471 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002472 case glslang::EOpAtomicCounterAdd:
2473 case glslang::EOpAtomicCounterSubtract:
2474 case glslang::EOpAtomicCounterMin:
2475 case glslang::EOpAtomicCounterMax:
2476 case glslang::EOpAtomicCounterAnd:
2477 case glslang::EOpAtomicCounterOr:
2478 case glslang::EOpAtomicCounterXor:
2479 case glslang::EOpAtomicCounterExchange:
2480 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002481 if (arg == 0)
2482 lvalue = true;
2483 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002484 case glslang::EOpAddCarry:
2485 case glslang::EOpSubBorrow:
2486 if (arg == 2)
2487 lvalue = true;
2488 break;
2489 case glslang::EOpUMulExtended:
2490 case glslang::EOpIMulExtended:
2491 if (arg >= 2)
2492 lvalue = true;
2493 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002494 case glslang::EOpCooperativeMatrixLoad:
2495 if (arg == 0 || arg == 1)
2496 lvalue = true;
2497 break;
2498 case glslang::EOpCooperativeMatrixStore:
2499 if (arg == 1)
2500 lvalue = true;
2501 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002502 default:
2503 break;
2504 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002505 builder.clearAccessChain();
2506 if (invertedType != spv::NoType && arg == 0)
2507 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2508 else
2509 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002510
2511 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2512 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2513
2514 if (arg == 1) {
2515 // fold "element" parameter into the access chain
2516 spv::Builder::AccessChain save = builder.getAccessChain();
2517 builder.clearAccessChain();
2518 glslangOperands[2]->traverse(this);
2519
2520 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2521
2522 builder.setAccessChain(save);
2523
2524 // Point to the first element of the array.
2525 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002526 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002527
2528 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2529 unsigned int alignment = builder.getAccessChain().alignment;
2530
2531 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2532 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2533 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2534 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2535 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2536 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2537 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2538 }
2539
2540 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2541
2542 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2543 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2544 }
2545
2546 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2547 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2548 }
2549 } else if (arg == 2) {
2550 continue;
2551 }
2552 }
2553
John Kessenich140f3df2015-06-26 16:58:36 -06002554 if (lvalue)
2555 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002556 else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002557 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002558 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002559 }
John Kessenich140f3df2015-06-26 16:58:36 -06002560 }
John Kessenich426394d2015-07-23 10:22:48 -06002561
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002562 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002563 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2564 std::vector<spv::IdImmediate> idImmOps;
2565
2566 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2567 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2568 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2569 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2570 // get the pointee type
2571 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2572 assert(builder.isCooperativeMatrixType(typeId));
2573 // do the op
2574 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2575 // store the result to the pointer (out param 'm')
2576 builder.createStore(result, operands[0]);
2577 result = 0;
2578 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2579 std::vector<spv::IdImmediate> idImmOps;
2580
2581 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2582 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2583 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2584 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2585 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2586
2587 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2588 result = 0;
2589 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002590 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002591 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002592 } else {
2593 // Pass through to generic operations.
2594 switch (glslangOperands.size()) {
2595 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002596 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002597 break;
2598 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002599 {
2600 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002601 TranslateNoContractionDecoration(node->getType().getQualifier()),
2602 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002603 result = createUnaryOperation(
2604 node->getOp(), decorations,
2605 resultType(), operands.front(),
2606 glslangOperands[0]->getAsTyped()->getBasicType());
2607 }
John Kessenich426394d2015-07-23 10:22:48 -06002608 break;
2609 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002610 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002611 break;
2612 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002613 if (invertedType)
2614 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002615 }
2616
2617 if (noReturnValue)
2618 return false;
2619
2620 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002621 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002622 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002623 } else {
2624 builder.clearAccessChain();
2625 builder.setAccessChainRValue(result);
2626 return false;
2627 }
2628}
2629
John Kessenich433e9ff2017-01-26 20:31:11 -07002630// This path handles both if-then-else and ?:
2631// The if-then-else has a node type of void, while
2632// ?: has either a void or a non-void node type
2633//
2634// Leaving the result, when not void:
2635// GLSL only has r-values as the result of a :?, but
2636// if we have an l-value, that can be more efficient if it will
2637// become the base of a complex r-value expression, because the
2638// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002639bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2640{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002641 // see if OpSelect can handle it
2642 const auto isOpSelectable = [&]() {
2643 if (node->getBasicType() == glslang::EbtVoid)
2644 return false;
2645 // OpSelect can do all other types starting with SPV 1.4
2646 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2647 // pre-1.4, only scalars and vectors can be handled
2648 if ((!node->getType().isScalar() && !node->getType().isVector()))
2649 return false;
2650 }
2651 return true;
2652 };
2653
John Kessenich4bee5312018-02-20 21:29:05 -07002654 // See if it simple and safe, or required, to execute both sides.
2655 // Crucially, side effects must be either semantically required or avoided,
2656 // and there are performance trade-offs.
2657 // Return true if required or a good idea (and safe) to execute both sides,
2658 // false otherwise.
2659 const auto bothSidesPolicy = [&]() -> bool {
2660 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002661 if (node->getTrueBlock() == nullptr ||
2662 node->getFalseBlock() == nullptr)
2663 return false;
2664
John Kessenich4bee5312018-02-20 21:29:05 -07002665 // required? (unless we write additional code to look for side effects
2666 // and make performance trade-offs if none are present)
2667 if (!node->getShortCircuit())
2668 return true;
2669
2670 // if not required to execute both, decide based on performance/practicality...
2671
John Kessenich0c1e71a2019-01-10 18:23:06 +07002672 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002673 return false;
2674
John Kessenich433e9ff2017-01-26 20:31:11 -07002675 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2676 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2677
2678 // return true if a single operand to ? : is okay for OpSelect
2679 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002680 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002681 };
2682
2683 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2684 operandOkay(node->getFalseBlock()->getAsTyped());
2685 };
2686
John Kessenich4bee5312018-02-20 21:29:05 -07002687 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2688 // emit the condition before doing anything with selection
2689 node->getCondition()->traverse(this);
2690 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2691
2692 // Find a way of executing both sides and selecting the right result.
2693 const auto executeBothSides = [&]() -> void {
2694 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002695 node->getTrueBlock()->traverse(this);
2696 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2697 node->getFalseBlock()->traverse(this);
2698 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2699
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002700 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002701
John Kessenich4bee5312018-02-20 21:29:05 -07002702 // done if void
2703 if (node->getBasicType() == glslang::EbtVoid)
2704 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002705
John Kessenich4bee5312018-02-20 21:29:05 -07002706 // emit code to select between trueValue and falseValue
2707
2708 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002709 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002710 // Emit OpSelect for this selection.
2711
2712 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002713 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2714 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002715 condition = builder.smearScalar(spv::NoPrecision, condition,
2716 builder.makeVectorType(builder.makeBoolType(),
2717 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002718 }
John Kessenich4bee5312018-02-20 21:29:05 -07002719
2720 // OpSelect
2721 result = builder.createTriOp(spv::OpSelect,
2722 convertGlslangToSpvType(node->getType()), condition,
2723 trueValue, falseValue);
2724
2725 builder.clearAccessChain();
2726 builder.setAccessChainRValue(result);
2727 } else {
2728 // We need control flow to select the result.
2729 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2730 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2731
2732 // Selection control:
2733 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2734
2735 // make an "if" based on the value created by the condition
2736 spv::Builder::If ifBuilder(condition, control, builder);
2737
2738 // emit the "then" statement
2739 builder.createStore(trueValue, result);
2740 ifBuilder.makeBeginElse();
2741 // emit the "else" statement
2742 builder.createStore(falseValue, result);
2743
2744 // finish off the control flow
2745 ifBuilder.makeEndIf();
2746
2747 builder.clearAccessChain();
2748 builder.setAccessChainLValue(result);
2749 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002750 };
2751
John Kessenich4bee5312018-02-20 21:29:05 -07002752 // Execute the one side needed, as per the condition
2753 const auto executeOneSide = [&]() {
2754 // Always emit control flow.
2755 if (node->getBasicType() != glslang::EbtVoid)
2756 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002757
John Kessenich4bee5312018-02-20 21:29:05 -07002758 // Selection control:
2759 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2760
2761 // make an "if" based on the value created by the condition
2762 spv::Builder::If ifBuilder(condition, control, builder);
2763
2764 // emit the "then" statement
2765 if (node->getTrueBlock() != nullptr) {
2766 node->getTrueBlock()->traverse(this);
2767 if (result != spv::NoResult)
2768 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2769 }
2770
2771 if (node->getFalseBlock() != nullptr) {
2772 ifBuilder.makeBeginElse();
2773 // emit the "else" statement
2774 node->getFalseBlock()->traverse(this);
2775 if (result != spv::NoResult)
2776 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2777 }
2778
2779 // finish off the control flow
2780 ifBuilder.makeEndIf();
2781
2782 if (result != spv::NoResult) {
2783 builder.clearAccessChain();
2784 builder.setAccessChainLValue(result);
2785 }
2786 };
2787
2788 // Try for OpSelect (or a requirement to execute both sides)
2789 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002790 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2791 if (node->getType().getQualifier().isSpecConstant())
2792 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002793 executeBothSides();
2794 } else
2795 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002796
2797 return false;
2798}
2799
2800bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2801{
2802 // emit and get the condition before doing anything with switch
2803 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002804 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002805
Rex Xu57e65922017-07-04 23:23:40 +08002806 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002807 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002808
John Kessenich140f3df2015-06-26 16:58:36 -06002809 // browse the children to sort out code segments
2810 int defaultSegment = -1;
2811 std::vector<TIntermNode*> codeSegments;
2812 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2813 std::vector<int> caseValues;
2814 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2815 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2816 TIntermNode* child = *c;
2817 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002818 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002819 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002820 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002821 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2822 } else
2823 codeSegments.push_back(child);
2824 }
2825
qining25262b32016-05-06 17:25:16 -04002826 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002827 // statements between the last case and the end of the switch statement
2828 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2829 (int)codeSegments.size() == defaultSegment)
2830 codeSegments.push_back(nullptr);
2831
2832 // make the switch statement
2833 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002834 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002835
2836 // emit all the code in the segments
2837 breakForLoop.push(false);
2838 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2839 builder.nextSwitchSegment(segmentBlocks, s);
2840 if (codeSegments[s])
2841 codeSegments[s]->traverse(this);
2842 else
2843 builder.addSwitchBreak();
2844 }
2845 breakForLoop.pop();
2846
2847 builder.endSwitch(segmentBlocks);
2848
2849 return false;
2850}
2851
2852void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2853{
2854 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002855 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002856
2857 builder.clearAccessChain();
2858 builder.setAccessChainRValue(constant);
2859}
2860
2861bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2862{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002863 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002864 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002865
2866 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07002867 std::vector<unsigned int> operands;
2868 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06002869
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002870 // Spec requires back edges to target header blocks, and every header block
2871 // must dominate its merge block. Make a header block first to ensure these
2872 // conditions are met. By definition, it will contain OpLoopMerge, followed
2873 // by a block-ending branch. But we don't want to put any other body/test
2874 // instructions in it, since the body/test may have arbitrary instructions,
2875 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002876 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002877 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07002878 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002879 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002880 spv::Block& test = builder.makeNewBlock();
2881 builder.createBranch(&test);
2882
2883 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002884 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002885 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002886 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2887
2888 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002889 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002890 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002891 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002892 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002893 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002894
2895 builder.setBuildPoint(&blocks.continue_target);
2896 if (node->getTerminal())
2897 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002898 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002899 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002900 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002901 builder.createBranch(&blocks.body);
2902
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002903 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002904 builder.setBuildPoint(&blocks.body);
2905 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002906 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002907 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002908 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002909
2910 builder.setBuildPoint(&blocks.continue_target);
2911 if (node->getTerminal())
2912 node->getTerminal()->traverse(this);
2913 if (node->getTest()) {
2914 node->getTest()->traverse(this);
2915 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002916 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002917 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002918 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002919 // TODO: unless there was a break/return/discard instruction
2920 // somewhere in the body, this is an infinite loop, so we should
2921 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002922 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002923 }
John Kessenich140f3df2015-06-26 16:58:36 -06002924 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002925 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002926 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002927 return false;
2928}
2929
2930bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2931{
2932 if (node->getExpression())
2933 node->getExpression()->traverse(this);
2934
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002935 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002936
John Kessenich140f3df2015-06-26 16:58:36 -06002937 switch (node->getFlowOp()) {
2938 case glslang::EOpKill:
2939 builder.makeDiscard();
2940 break;
2941 case glslang::EOpBreak:
2942 if (breakForLoop.top())
2943 builder.createLoopExit();
2944 else
2945 builder.addSwitchBreak();
2946 break;
2947 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002948 builder.createLoopContinue();
2949 break;
2950 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002951 if (node->getExpression()) {
2952 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2953 spv::Id returnId = accessChainLoad(glslangReturnType);
2954 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2955 builder.clearAccessChain();
2956 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2957 builder.setAccessChainLValue(copyId);
2958 multiTypeStore(glslangReturnType, returnId);
2959 returnId = builder.createLoad(copyId);
2960 }
2961 builder.makeReturn(false, returnId);
2962 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002963 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002964
2965 builder.clearAccessChain();
2966 break;
2967
2968 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002969 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002970 break;
2971 }
2972
2973 return false;
2974}
2975
2976spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2977{
qining25262b32016-05-06 17:25:16 -04002978 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002979 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002980 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002981 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05002982 spv::Id result = createSpvConstant(*node);
2983 if (result != spv::NoResult)
2984 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06002985 }
2986
2987 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002988 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002989 spv::Id spvType = convertGlslangToSpvType(node->getType());
2990
Rex Xucabbb782017-03-24 13:41:14 +08002991 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2992 node->getType().containsBasicType(glslang::EbtInt16) ||
2993 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002994 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002995 switch (storageClass) {
2996 case spv::StorageClassInput:
2997 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002998 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002999 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003000 break;
3001 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07003002 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003003 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06003004 break;
3005 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003006 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003007 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3008 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003009 else
3010 builder.addCapability(spv::CapabilityStorageUniform16);
3011 break;
3012 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003013 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003014 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3015 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3016 break;
3017 default:
3018 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003019 }
3020 }
Rex Xuf89ad982017-04-07 23:22:33 +08003021
John Kessenich312dcfb2018-07-03 13:19:51 -06003022 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3023 node->getType().containsBasicType(glslang::EbtUint8);
3024 if (contains8BitType) {
3025 if (storageClass == spv::StorageClassPushConstant) {
3026 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3027 builder.addCapability(spv::CapabilityStoragePushConstant8);
3028 } else if (storageClass == spv::StorageClassUniform) {
3029 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3030 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003031 } else if (storageClass == spv::StorageClassStorageBuffer) {
3032 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3033 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
John Kessenich312dcfb2018-07-03 13:19:51 -06003034 }
3035 }
3036
John Kessenich140f3df2015-06-26 16:58:36 -06003037 const char* name = node->getName().c_str();
3038 if (glslang::IsAnonymous(name))
3039 name = "";
3040
3041 return builder.createVariable(storageClass, spvType, name);
3042}
3043
3044// Return type Id of the sampled type.
3045spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3046{
3047 switch (sampler.type) {
3048 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003049#ifdef AMD_EXTENSIONS
3050 case glslang::EbtFloat16:
3051 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3052 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3053 return builder.makeFloatType(16);
3054#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003055 case glslang::EbtInt: return builder.makeIntType(32);
3056 case glslang::EbtUint: return builder.makeUintType(32);
3057 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003058 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003059 return builder.makeFloatType(32);
3060 }
3061}
3062
John Kessenich8c8505c2016-07-26 12:50:38 -06003063// If node is a swizzle operation, return the type that should be used if
3064// the swizzle base is first consumed by another operation, before the swizzle
3065// is applied.
3066spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3067{
John Kessenichecba76f2017-01-06 00:34:48 -07003068 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003069 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3070 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3071 else
3072 return spv::NoType;
3073}
3074
3075// When inverting a swizzle with a parent op, this function
3076// will apply the swizzle operation to a completed parent operation.
3077spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3078{
3079 std::vector<unsigned> swizzle;
3080 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3081 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3082}
3083
John Kessenich8c8505c2016-07-26 12:50:38 -06003084// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3085void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3086{
3087 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3088 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3089 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3090}
3091
John Kessenich3ac051e2015-12-20 11:29:16 -07003092// Convert from a glslang type to an SPV type, by calling into a
3093// recursive version of this function. This establishes the inherited
3094// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003095spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003096{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003097 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003098}
3099
3100// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003101// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003102// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003103spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003104 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3105 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003106{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003107 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003108
3109 switch (type.getBasicType()) {
3110 case glslang::EbtVoid:
3111 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003112 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003113 break;
3114 case glslang::EbtFloat:
3115 spvType = builder.makeFloatType(32);
3116 break;
3117 case glslang::EbtDouble:
3118 spvType = builder.makeFloatType(64);
3119 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003120 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003121 spvType = builder.makeFloatType(16);
3122 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003123 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003124 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3125 // a 32-bit int where non-0 means true.
3126 if (explicitLayout != glslang::ElpNone)
3127 spvType = builder.makeUintType(32);
3128 else
3129 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003130 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003131 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003132 spvType = builder.makeIntType(8);
3133 break;
3134 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003135 spvType = builder.makeUintType(8);
3136 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003137 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003138 spvType = builder.makeIntType(16);
3139 break;
3140 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003141 spvType = builder.makeUintType(16);
3142 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003143 case glslang::EbtInt:
3144 spvType = builder.makeIntType(32);
3145 break;
3146 case glslang::EbtUint:
3147 spvType = builder.makeUintType(32);
3148 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003149 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003150 spvType = builder.makeIntType(64);
3151 break;
3152 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003153 spvType = builder.makeUintType(64);
3154 break;
John Kessenich426394d2015-07-23 10:22:48 -06003155 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003156 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003157 spvType = builder.makeUintType(32);
3158 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003159#ifdef NV_EXTENSIONS
3160 case glslang::EbtAccStructNV:
3161 spvType = builder.makeAccelerationStructureNVType();
3162 break;
3163#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003164 case glslang::EbtSampler:
3165 {
3166 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003167 if (sampler.sampler) {
3168 // pure sampler
3169 spvType = builder.makeSamplerType();
3170 } else {
3171 // an image is present, make its type
3172 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3173 sampler.image ? 2 : 1, TranslateImageFormat(type));
3174 if (sampler.combined) {
3175 // already has both image and sampler, make the combined type
3176 spvType = builder.makeSampledImageType(spvType);
3177 }
John Kessenich55e7d112015-11-15 21:33:39 -07003178 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003179 }
John Kessenich140f3df2015-06-26 16:58:36 -06003180 break;
3181 case glslang::EbtStruct:
3182 case glslang::EbtBlock:
3183 {
3184 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003185 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003186
3187 // Try to share structs for different layouts, but not yet for other
3188 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003189 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003190 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003191 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003192 break;
3193
3194 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003195 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003196 memberRemapper[glslangMembers].resize(glslangMembers->size());
3197 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003198 }
3199 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003200 case glslang::EbtReference:
3201 {
3202 // Make the forward pointer, then recurse to convert the structure type, then
3203 // patch up the forward pointer with a real pointer type.
3204 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3205 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3206 forwardPointers[type.getReferentType()] = forwardId;
3207 }
3208 spvType = forwardPointers[type.getReferentType()];
3209 if (!forwardReferenceOnly) {
3210 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3211 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3212 forwardPointers[type.getReferentType()],
3213 referentType);
3214 }
3215 }
3216 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003217 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003218 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003219 break;
3220 }
3221
3222 if (type.isMatrix())
3223 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3224 else {
3225 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3226 if (type.getVectorSize() > 1)
3227 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3228 }
3229
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003230 if (type.isCoopMat()) {
3231 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3232 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3233 if (type.getBasicType() == glslang::EbtFloat16)
3234 builder.addCapability(spv::CapabilityFloat16);
3235
3236 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3237 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3238 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3239
3240 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3241 }
3242
John Kessenich140f3df2015-06-26 16:58:36 -06003243 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003244 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3245
John Kessenichc9a80832015-09-12 12:17:44 -06003246 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003247 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003248 // We need to decorate array strides for types needing explicit layout, except blocks.
3249 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003250 // Use a dummy glslang type for querying internal strides of
3251 // arrays of arrays, but using just a one-dimensional array.
3252 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003253 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3254 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003255
3256 // Will compute the higher-order strides here, rather than making a whole
3257 // pile of types and doing repetitive recursion on their contents.
3258 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3259 }
John Kessenichf8842e52016-01-04 19:22:56 -07003260
3261 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003262 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003263 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003264 if (stride > 0)
3265 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003266 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003267 }
3268 } else {
3269 // single-dimensional array, and don't yet have stride
3270
John Kessenichf8842e52016-01-04 19:22:56 -07003271 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003272 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3273 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003274 }
John Kessenich31ed4832015-09-09 17:51:38 -06003275
John Kessenichead86222018-03-28 18:01:20 -06003276 // Do the outer dimension, which might not be known for a runtime-sized array.
3277 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3278 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003279 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003280 else {
3281 if (!lastBufferBlockMember) {
3282 builder.addExtension("SPV_EXT_descriptor_indexing");
3283 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3284 }
John Kessenichead86222018-03-28 18:01:20 -06003285 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003286 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003287 if (stride > 0)
3288 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003289 }
3290
3291 return spvType;
3292}
3293
John Kessenich0e737842017-03-24 18:38:16 -06003294// TODO: this functionality should exist at a higher level, in creating the AST
3295//
3296// Identify interface members that don't have their required extension turned on.
3297//
3298bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3299{
Chao Chen3c366992018-09-19 11:41:59 -07003300#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003301 auto& extensions = glslangIntermediate->getRequestedExtensions();
3302
Rex Xubcf291a2017-03-29 23:01:36 +08003303 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3304 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3305 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003306 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3307 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3308 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003309
3310 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3311 if (member.getFieldName() == "gl_ViewportMask" &&
3312 extensions.find("GL_NV_viewport_array2") == extensions.end())
3313 return true;
3314 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3315 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3316 return true;
3317 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3318 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3319 return true;
3320 }
3321#endif
John Kessenich0e737842017-03-24 18:38:16 -06003322
3323 return false;
3324};
3325
John Kessenich6090df02016-06-30 21:18:02 -06003326// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3327// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3328// Mutually recursive with convertGlslangToSpvType().
3329spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3330 const glslang::TTypeList* glslangMembers,
3331 glslang::TLayoutPacking explicitLayout,
3332 const glslang::TQualifier& qualifier)
3333{
3334 // Create a vector of struct types for SPIR-V to consume
3335 std::vector<spv::Id> spvMembers;
3336 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003337 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003338 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3339 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3340 if (glslangMember.hiddenMember()) {
3341 ++memberDelta;
3342 if (type.getBasicType() == glslang::EbtBlock)
3343 memberRemapper[glslangMembers][i] = -1;
3344 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003345 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003346 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003347 if (filterMember(glslangMember))
3348 continue;
3349 }
John Kessenich6090df02016-06-30 21:18:02 -06003350 // modify just this child's view of the qualifier
3351 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3352 InheritQualifiers(memberQualifier, qualifier);
3353
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003354 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003355 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003356 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003357
3358 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003359 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3360 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003361
3362 // Make forward pointers for any pointer members, and create a list of members to
3363 // convert to spirv types after creating the struct.
3364 if (glslangMember.getBasicType() == glslang::EbtReference) {
3365 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3366 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3367 }
3368 spvMembers.push_back(
3369 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3370 } else {
3371 spvMembers.push_back(
3372 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3373 }
John Kessenich6090df02016-06-30 21:18:02 -06003374 }
3375 }
3376
3377 // Make the SPIR-V type
3378 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003379 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003380 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3381
3382 // Decorate it
3383 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3384
John Kessenichd72f4882019-01-16 14:55:37 +07003385 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003386 auto it = deferredForwardPointers[i];
3387 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3388 }
3389
John Kessenich6090df02016-06-30 21:18:02 -06003390 return spvType;
3391}
3392
3393void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3394 const glslang::TTypeList* glslangMembers,
3395 glslang::TLayoutPacking explicitLayout,
3396 const glslang::TQualifier& qualifier,
3397 spv::Id spvType)
3398{
3399 // Name and decorate the non-hidden members
3400 int offset = -1;
3401 int locationOffset = 0; // for use within the members of this struct
3402 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3403 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3404 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003405 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003406 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003407 if (filterMember(glslangMember))
3408 continue;
3409 }
John Kessenich6090df02016-06-30 21:18:02 -06003410
3411 // modify just this child's view of the qualifier
3412 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3413 InheritQualifiers(memberQualifier, qualifier);
3414
3415 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003416 if (member < 0)
3417 continue;
3418
3419 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3420 builder.addMemberDecoration(spvType, member,
3421 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3422 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3423 // Add interpolation and auxiliary storage decorations only to
3424 // top-level members of Input and Output storage classes
3425 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3426 type.getQualifier().storage == glslang::EvqVaryingOut) {
3427 if (type.getBasicType() == glslang::EbtBlock ||
3428 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3429 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3430 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003431#ifdef NV_EXTENSIONS
3432 addMeshNVDecoration(spvType, member, memberQualifier);
3433#endif
John Kessenich6090df02016-06-30 21:18:02 -06003434 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003435 }
3436 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003437
John Kessenich5d610ee2018-03-07 18:05:55 -07003438 if (type.getBasicType() == glslang::EbtBlock &&
3439 qualifier.storage == glslang::EvqBuffer) {
3440 // Add memory decorations only to top-level members of shader storage block
3441 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003442 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003443 for (unsigned int i = 0; i < memory.size(); ++i)
3444 builder.addMemberDecoration(spvType, member, memory[i]);
3445 }
John Kessenich6090df02016-06-30 21:18:02 -06003446
John Kessenich5d610ee2018-03-07 18:05:55 -07003447 // Location assignment was already completed correctly by the front end,
3448 // just track whether a member needs to be decorated.
3449 // Ignore member locations if the container is an array, as that's
3450 // ill-specified and decisions have been made to not allow this.
3451 if (! type.isArray() && memberQualifier.hasLocation())
3452 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003453
John Kessenich5d610ee2018-03-07 18:05:55 -07003454 if (qualifier.hasLocation()) // track for upcoming inheritance
3455 locationOffset += glslangIntermediate->computeTypeLocationSize(
3456 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003457
John Kessenich5d610ee2018-03-07 18:05:55 -07003458 // component, XFB, others
3459 if (glslangMember.getQualifier().hasComponent())
3460 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3461 glslangMember.getQualifier().layoutComponent);
3462 if (glslangMember.getQualifier().hasXfbOffset())
3463 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3464 glslangMember.getQualifier().layoutXfbOffset);
3465 else if (explicitLayout != glslang::ElpNone) {
3466 // figure out what to do with offset, which is accumulating
3467 int nextOffset;
3468 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3469 if (offset >= 0)
3470 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3471 offset = nextOffset;
3472 }
John Kessenich6090df02016-06-30 21:18:02 -06003473
John Kessenich5d610ee2018-03-07 18:05:55 -07003474 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3475 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3476 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003477
John Kessenich5d610ee2018-03-07 18:05:55 -07003478 // built-in variable decorations
3479 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3480 if (builtIn != spv::BuiltInMax)
3481 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003482
John Kessenich5611c6d2018-04-05 11:25:02 -06003483 // nonuniform
3484 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3485
John Kessenichead86222018-03-28 18:01:20 -06003486 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3487 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3488 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3489 memberQualifier.semanticName);
3490 }
3491
chaoc771d89f2017-01-13 01:10:53 -08003492#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003493 if (builtIn == spv::BuiltInLayer) {
3494 // SPV_NV_viewport_array2 extension
3495 if (glslangMember.getQualifier().layoutViewportRelative){
3496 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3497 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3498 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003499 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003500 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3501 builder.addMemberDecoration(spvType, member,
3502 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3503 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3504 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3505 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003506 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003507 }
3508 if (glslangMember.getQualifier().layoutPassthrough) {
3509 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3510 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3511 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3512 }
chaoc771d89f2017-01-13 01:10:53 -08003513#endif
John Kessenich6090df02016-06-30 21:18:02 -06003514 }
3515
3516 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003517 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3518 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003519}
3520
John Kessenich6c292d32016-02-15 20:58:50 -07003521// Turn the expression forming the array size into an id.
3522// This is not quite trivial, because of specialization constants.
3523// Sometimes, a raw constant is turned into an Id, and sometimes
3524// a specialization constant expression is.
3525spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3526{
3527 // First, see if this is sized with a node, meaning a specialization constant:
3528 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3529 if (specNode != nullptr) {
3530 builder.clearAccessChain();
3531 specNode->traverse(this);
3532 return accessChainLoad(specNode->getAsTyped()->getType());
3533 }
qining25262b32016-05-06 17:25:16 -04003534
John Kessenich6c292d32016-02-15 20:58:50 -07003535 // Otherwise, need a compile-time (front end) size, get it:
3536 int size = arraySizes.getDimSize(dim);
3537 assert(size > 0);
3538 return builder.makeUintConstant(size);
3539}
3540
John Kessenich103bef92016-02-08 21:38:15 -07003541// Wrap the builder's accessChainLoad to:
3542// - localize handling of RelaxedPrecision
3543// - use the SPIR-V inferred type instead of another conversion of the glslang type
3544// (avoids unnecessary work and possible type punning for structures)
3545// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003546spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3547{
John Kessenich103bef92016-02-08 21:38:15 -07003548 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003549
3550 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3551 coherentFlags |= TranslateCoherent(type);
3552
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003553 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003554 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003555
John Kessenich5611c6d2018-04-05 11:25:02 -06003556 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003557 TranslateNonUniformDecoration(type.getQualifier()),
3558 nominalTypeId,
3559 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003560 TranslateMemoryScope(coherentFlags),
3561 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003562
3563 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003564 if (type.getBasicType() == glslang::EbtBool) {
3565 if (builder.isScalarType(nominalTypeId)) {
3566 // Conversion for bool
3567 spv::Id boolType = builder.makeBoolType();
3568 if (nominalTypeId != boolType)
3569 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3570 } else if (builder.isVectorType(nominalTypeId)) {
3571 // Conversion for bvec
3572 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3573 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3574 if (nominalTypeId != bvecType)
3575 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3576 }
3577 }
John Kessenich103bef92016-02-08 21:38:15 -07003578
3579 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003580}
3581
Rex Xu27253232016-02-23 17:51:09 +08003582// Wrap the builder's accessChainStore to:
3583// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003584//
3585// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003586void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3587{
3588 // Need to convert to abstract types when necessary
3589 if (type.getBasicType() == glslang::EbtBool) {
3590 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3591
3592 if (builder.isScalarType(nominalTypeId)) {
3593 // Conversion for bool
3594 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003595 if (nominalTypeId != boolType) {
3596 // keep these outside arguments, for determinant order-of-evaluation
3597 spv::Id one = builder.makeUintConstant(1);
3598 spv::Id zero = builder.makeUintConstant(0);
3599 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3600 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003601 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003602 } else if (builder.isVectorType(nominalTypeId)) {
3603 // Conversion for bvec
3604 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3605 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003606 if (nominalTypeId != bvecType) {
3607 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003608 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3609 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3610 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003611 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003612 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3613 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003614 }
3615 }
3616
Jeff Bolz36831c92018-09-05 10:11:41 -05003617 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3618 coherentFlags |= TranslateCoherent(type);
3619
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003620 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003621 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003622
Jeff Bolz36831c92018-09-05 10:11:41 -05003623 builder.accessChainStore(rvalue,
3624 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003625 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003626}
3627
John Kessenich4bf71552016-09-02 11:20:21 -06003628// For storing when types match at the glslang level, but not might match at the
3629// SPIR-V level.
3630//
3631// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003632// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003633// as in a member-decorated way.
3634//
3635// NOTE: This function can handle any store request; if it's not special it
3636// simplifies to a simple OpStore.
3637//
3638// Implicitly uses the existing builder.accessChain as the storage target.
3639void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3640{
John Kessenichb3e24e42016-09-11 12:33:43 -06003641 // we only do the complex path here if it's an aggregate
3642 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003643 accessChainStore(type, rValue);
3644 return;
3645 }
3646
John Kessenichb3e24e42016-09-11 12:33:43 -06003647 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003648 spv::Id rType = builder.getTypeId(rValue);
3649 spv::Id lValue = builder.accessChainGetLValue();
3650 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3651 if (lType == rType) {
3652 accessChainStore(type, rValue);
3653 return;
3654 }
3655
John Kessenichb3e24e42016-09-11 12:33:43 -06003656 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003657 // where the two types were the same type in GLSL. This requires member
3658 // by member copy, recursively.
3659
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003660 // SPIR-V 1.4 added an instruction to do help do this.
3661 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3662 // However, bool in uniform space is changed to int, so
3663 // OpCopyLogical does not work for that.
3664 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3665 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3666 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3667 if (lBool == rBool) {
3668 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3669 accessChainStore(type, logicalCopy);
3670 return;
3671 }
3672 }
3673
John Kessenichb3e24e42016-09-11 12:33:43 -06003674 // If an array, copy element by element.
3675 if (type.isArray()) {
3676 glslang::TType glslangElementType(type, 0);
3677 spv::Id elementRType = builder.getContainedTypeId(rType);
3678 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3679 // get the source member
3680 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003681
John Kessenichb3e24e42016-09-11 12:33:43 -06003682 // set up the target storage
3683 builder.clearAccessChain();
3684 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003685 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003686
John Kessenichb3e24e42016-09-11 12:33:43 -06003687 // store the member
3688 multiTypeStore(glslangElementType, elementRValue);
3689 }
3690 } else {
3691 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003692
John Kessenichb3e24e42016-09-11 12:33:43 -06003693 // loop over structure members
3694 const glslang::TTypeList& members = *type.getStruct();
3695 for (int m = 0; m < (int)members.size(); ++m) {
3696 const glslang::TType& glslangMemberType = *members[m].type;
3697
3698 // get the source member
3699 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3700 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3701
3702 // set up the target storage
3703 builder.clearAccessChain();
3704 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003705 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003706
3707 // store the member
3708 multiTypeStore(glslangMemberType, memberRValue);
3709 }
John Kessenich4bf71552016-09-02 11:20:21 -06003710 }
3711}
3712
John Kessenichf85e8062015-12-19 13:57:10 -07003713// Decide whether or not this type should be
3714// decorated with offsets and strides, and if so
3715// whether std140 or std430 rules should be applied.
3716glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003717{
John Kessenichf85e8062015-12-19 13:57:10 -07003718 // has to be a block
3719 if (type.getBasicType() != glslang::EbtBlock)
3720 return glslang::ElpNone;
3721
Chao Chen3c366992018-09-19 11:41:59 -07003722 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003723 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003724 type.getQualifier().storage != glslang::EvqBuffer &&
3725 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003726 return glslang::ElpNone;
3727
3728 // return the layout to use
3729 switch (type.getQualifier().layoutPacking) {
3730 case glslang::ElpStd140:
3731 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003732 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003733 return type.getQualifier().layoutPacking;
3734 default:
3735 return glslang::ElpNone;
3736 }
John Kessenich31ed4832015-09-09 17:51:38 -06003737}
3738
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003739// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003740int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003741{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003742 int size;
John Kessenich49987892015-12-29 17:11:44 -07003743 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003744 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003745
3746 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003747}
3748
John Kessenich49987892015-12-29 17:11:44 -07003749// Given a matrix type, or array (of array) of matrixes type, returns the integer stride required for that matrix
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003750// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003751int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003752{
John Kessenich49987892015-12-29 17:11:44 -07003753 glslang::TType elementType;
3754 elementType.shallowCopy(matrixType);
3755 elementType.clearArraySizes();
3756
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003757 int size;
John Kessenich49987892015-12-29 17:11:44 -07003758 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003759 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003760
3761 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003762}
3763
John Kessenich5e4b1242015-08-06 22:53:06 -06003764// Given a member type of a struct, realign the current offset for it, and compute
3765// the next (not yet aligned) offset for the next member, which will get aligned
3766// on the next call.
3767// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3768// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3769// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003770void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003771 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003772{
3773 // this will get a positive value when deemed necessary
3774 nextOffset = -1;
3775
John Kessenich5e4b1242015-08-06 22:53:06 -06003776 // override anything in currentOffset with user-set offset
3777 if (memberType.getQualifier().hasOffset())
3778 currentOffset = memberType.getQualifier().layoutOffset;
3779
3780 // It could be that current linker usage in glslang updated all the layoutOffset,
3781 // in which case the following code does not matter. But, that's not quite right
3782 // once cross-compilation unit GLSL validation is done, as the original user
3783 // settings are needed in layoutOffset, and then the following will come into play.
3784
John Kessenichf85e8062015-12-19 13:57:10 -07003785 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003786 if (! memberType.getQualifier().hasOffset())
3787 currentOffset = -1;
3788
3789 return;
3790 }
3791
John Kessenichf85e8062015-12-19 13:57:10 -07003792 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003793 if (currentOffset < 0)
3794 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003795
John Kessenich5e4b1242015-08-06 22:53:06 -06003796 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3797 // but possibly not yet correctly aligned.
3798
3799 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003800 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003801 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003802
3803 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003804 // TODO: make this consistent in early phases of code:
3805 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3806 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3807 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003808 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003809 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003810 int dummySize;
3811 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3812 if (componentAlignment <= 4)
3813 memberAlignment = componentAlignment;
3814 }
3815
3816 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003817 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003818
3819 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003820 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003821 glslang::RoundToPow2(currentOffset, 16);
3822
John Kessenich5e4b1242015-08-06 22:53:06 -06003823 nextOffset = currentOffset + memberSize;
3824}
3825
David Netoa901ffe2016-06-08 14:11:40 +01003826void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003827{
David Netoa901ffe2016-06-08 14:11:40 +01003828 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3829 switch (glslangBuiltIn)
3830 {
3831 case glslang::EbvClipDistance:
3832 case glslang::EbvCullDistance:
3833 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003834#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003835 case glslang::EbvViewportMaskNV:
3836 case glslang::EbvSecondaryPositionNV:
3837 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003838 case glslang::EbvPositionPerViewNV:
3839 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003840 case glslang::EbvTaskCountNV:
3841 case glslang::EbvPrimitiveCountNV:
3842 case glslang::EbvPrimitiveIndicesNV:
3843 case glslang::EbvClipDistancePerViewNV:
3844 case glslang::EbvCullDistancePerViewNV:
3845 case glslang::EbvLayerPerViewNV:
3846 case glslang::EbvMeshViewCountNV:
3847 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003848#endif
David Netoa901ffe2016-06-08 14:11:40 +01003849 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3850 // Alternately, we could just call this for any glslang built-in, since the
3851 // capability already guards against duplicates.
3852 TranslateBuiltInDecoration(glslangBuiltIn, false);
3853 break;
3854 default:
3855 // Capabilities were already generated when the struct was declared.
3856 break;
3857 }
John Kessenichebb50532016-05-16 19:22:05 -06003858}
3859
John Kessenich6fccb3c2016-09-19 16:01:41 -06003860bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003861{
John Kessenicheee9d532016-09-19 18:09:30 -06003862 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003863}
3864
John Kessenichd41993d2017-09-10 15:21:05 -06003865// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003866// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3867// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003868bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003869{
John Kessenich6a14f782017-12-04 02:48:10 -07003870 assert(qualifier == glslang::EvqIn ||
3871 qualifier == glslang::EvqOut ||
3872 qualifier == glslang::EvqInOut ||
3873 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003874 return qualifier != glslang::EvqConstReadOnly;
3875}
3876
3877// Is parameter pass-by-original?
3878bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3879 bool implicitThisParam)
3880{
3881 if (implicitThisParam) // implicit this
3882 return true;
3883 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003884 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003885 return paramType.containsOpaque() || // sampler, etc.
3886 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3887}
3888
John Kessenich140f3df2015-06-26 16:58:36 -06003889// Make all the functions, skeletally, without actually visiting their bodies.
3890void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3891{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003892 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003893 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3894 if (paramPrecision != spv::NoPrecision)
3895 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003896 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003897 if (type.getBasicType() == glslang::EbtReference) {
3898 // Original and non-writable params pass the pointer directly and
3899 // use restrict/aliased, others are stored to a pointer in Function
3900 // memory and use RestrictPointer/AliasedPointer.
3901 if (originalParam(type.getQualifier().storage, type, false) ||
3902 !writableParam(type.getQualifier().storage)) {
3903 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
3904 } else {
3905 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
3906 }
3907 }
John Kessenichfad62972017-07-18 02:35:46 -06003908 };
3909
John Kessenich140f3df2015-06-26 16:58:36 -06003910 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3911 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003912 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003913 continue;
3914
3915 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003916 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003917 //
qining25262b32016-05-06 17:25:16 -04003918 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003919 // function. What it is an address of varies:
3920 //
John Kessenich4bf71552016-09-02 11:20:21 -06003921 // - "in" parameters not marked as "const" can be written to without modifying the calling
3922 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003923 //
3924 // - "const in" parameters can just be the r-value, as no writes need occur.
3925 //
John Kessenich4bf71552016-09-02 11:20:21 -06003926 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3927 // GLSL has copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
John Kessenich140f3df2015-06-26 16:58:36 -06003928
3929 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003930 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003931 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3932
John Kessenichfad62972017-07-18 02:35:46 -06003933 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3934 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003935
John Kessenichfad62972017-07-18 02:35:46 -06003936 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003937 for (int p = 0; p < (int)parameters.size(); ++p) {
3938 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3939 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003940 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003941 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003942 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003943 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3944 else
John Kessenich4bf71552016-09-02 11:20:21 -06003945 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003946 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003947 paramTypes.push_back(typeId);
3948 }
3949
3950 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003951 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3952 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003953 glslFunction->getName().c_str(), paramTypes,
3954 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003955 if (implicitThis)
3956 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003957
3958 // Track function to emit/call later
3959 functionMap[glslFunction->getName().c_str()] = function;
3960
3961 // Set the parameter id's
3962 for (int p = 0; p < (int)parameters.size(); ++p) {
3963 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3964 // give a name too
3965 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3966 }
3967 }
3968}
3969
3970// Process all the initializers, while skipping the functions and link objects
3971void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3972{
3973 builder.setBuildPoint(shaderEntry->getLastBlock());
3974 for (int i = 0; i < (int)initializers.size(); ++i) {
3975 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3976 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3977
3978 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003979 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003980 initializer->traverse(this);
3981 }
3982 }
3983}
3984
3985// Process all the functions, while skipping initializers.
3986void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3987{
3988 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3989 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003990 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003991 node->traverse(this);
3992 }
3993}
3994
3995void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3996{
qining25262b32016-05-06 17:25:16 -04003997 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003998 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003999 currentFunction = functionMap[node->getName().c_str()];
4000 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004001 builder.setBuildPoint(functionBlock);
4002}
4003
Rex Xu04db3f52015-09-16 11:44:02 +08004004void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004005{
Rex Xufc618912015-09-09 16:42:49 +08004006 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004007
4008 glslang::TSampler sampler = {};
4009 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004010#ifdef AMD_EXTENSIONS
4011 bool f16ShadowCompare = false;
4012#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004013 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004014 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4015 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004016#ifdef AMD_EXTENSIONS
4017 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4018#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004019 }
4020
John Kessenich140f3df2015-06-26 16:58:36 -06004021 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4022 builder.clearAccessChain();
4023 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004024
4025 // Special case l-value operands
4026 bool lvalue = false;
4027 switch (node.getOp()) {
4028 case glslang::EOpImageAtomicAdd:
4029 case glslang::EOpImageAtomicMin:
4030 case glslang::EOpImageAtomicMax:
4031 case glslang::EOpImageAtomicAnd:
4032 case glslang::EOpImageAtomicOr:
4033 case glslang::EOpImageAtomicXor:
4034 case glslang::EOpImageAtomicExchange:
4035 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004036 case glslang::EOpImageAtomicLoad:
4037 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004038 if (i == 0)
4039 lvalue = true;
4040 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004041 case glslang::EOpSparseImageLoad:
4042 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4043 lvalue = true;
4044 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004045#ifdef AMD_EXTENSIONS
4046 case glslang::EOpSparseTexture:
4047 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4048 lvalue = true;
4049 break;
4050 case glslang::EOpSparseTextureClamp:
4051 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4052 lvalue = true;
4053 break;
4054 case glslang::EOpSparseTextureLod:
4055 case glslang::EOpSparseTextureOffset:
4056 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4057 lvalue = true;
4058 break;
4059#else
Rex Xu48edadf2015-12-31 16:11:41 +08004060 case glslang::EOpSparseTexture:
4061 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4062 lvalue = true;
4063 break;
4064 case glslang::EOpSparseTextureClamp:
4065 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4066 lvalue = true;
4067 break;
4068 case glslang::EOpSparseTextureLod:
4069 case glslang::EOpSparseTextureOffset:
4070 if (i == 3)
4071 lvalue = true;
4072 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004073#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004074 case glslang::EOpSparseTextureFetch:
4075 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4076 lvalue = true;
4077 break;
4078 case glslang::EOpSparseTextureFetchOffset:
4079 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4080 lvalue = true;
4081 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004082#ifdef AMD_EXTENSIONS
4083 case glslang::EOpSparseTextureLodOffset:
4084 case glslang::EOpSparseTextureGrad:
4085 case glslang::EOpSparseTextureOffsetClamp:
4086 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4087 lvalue = true;
4088 break;
4089 case glslang::EOpSparseTextureGradOffset:
4090 case glslang::EOpSparseTextureGradClamp:
4091 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4092 lvalue = true;
4093 break;
4094 case glslang::EOpSparseTextureGradOffsetClamp:
4095 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4096 lvalue = true;
4097 break;
4098#else
Rex Xu48edadf2015-12-31 16:11:41 +08004099 case glslang::EOpSparseTextureLodOffset:
4100 case glslang::EOpSparseTextureGrad:
4101 case glslang::EOpSparseTextureOffsetClamp:
4102 if (i == 4)
4103 lvalue = true;
4104 break;
4105 case glslang::EOpSparseTextureGradOffset:
4106 case glslang::EOpSparseTextureGradClamp:
4107 if (i == 5)
4108 lvalue = true;
4109 break;
4110 case glslang::EOpSparseTextureGradOffsetClamp:
4111 if (i == 6)
4112 lvalue = true;
4113 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004114#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004115 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004116 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4117 lvalue = true;
4118 break;
4119 case glslang::EOpSparseTextureGatherOffset:
4120 case glslang::EOpSparseTextureGatherOffsets:
4121 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4122 lvalue = true;
4123 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004124#ifdef AMD_EXTENSIONS
4125 case glslang::EOpSparseTextureGatherLod:
4126 if (i == 3)
4127 lvalue = true;
4128 break;
4129 case glslang::EOpSparseTextureGatherLodOffset:
4130 case glslang::EOpSparseTextureGatherLodOffsets:
4131 if (i == 4)
4132 lvalue = true;
4133 break;
Rex Xu129799a2017-07-05 17:23:28 +08004134 case glslang::EOpSparseImageLoadLod:
4135 if (i == 3)
4136 lvalue = true;
4137 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004138#endif
Chao Chen3a137962018-09-19 11:41:27 -07004139#ifdef NV_EXTENSIONS
4140 case glslang::EOpImageSampleFootprintNV:
4141 if (i == 4)
4142 lvalue = true;
4143 break;
4144 case glslang::EOpImageSampleFootprintClampNV:
4145 case glslang::EOpImageSampleFootprintLodNV:
4146 if (i == 5)
4147 lvalue = true;
4148 break;
4149 case glslang::EOpImageSampleFootprintGradNV:
4150 if (i == 6)
4151 lvalue = true;
4152 break;
4153 case glslang::EOpImageSampleFootprintGradClampNV:
4154 if (i == 7)
4155 lvalue = true;
4156 break;
4157#endif
Rex Xufc618912015-09-09 16:42:49 +08004158 default:
4159 break;
4160 }
4161
Rex Xu6b86d492015-09-16 17:48:22 +08004162 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08004163 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08004164 else
John Kessenich32cfd492016-02-02 12:37:46 -07004165 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004166 }
4167}
4168
John Kessenichfc51d282015-08-19 13:34:18 -06004169void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004170{
John Kessenichfc51d282015-08-19 13:34:18 -06004171 builder.clearAccessChain();
4172 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004173 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004174}
John Kessenich140f3df2015-06-26 16:58:36 -06004175
John Kessenichfc51d282015-08-19 13:34:18 -06004176spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4177{
John Kesseniche485c7a2017-05-31 18:50:53 -06004178 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004179 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004180
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004181 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004182
John Kessenichfc51d282015-08-19 13:34:18 -06004183 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004184
4185 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4186 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
4187 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004188#ifdef AMD_EXTENSIONS
4189 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
4190 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4191 : false;
4192#endif
4193
John Kessenichfc51d282015-08-19 13:34:18 -06004194 std::vector<spv::Id> arguments;
4195 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08004196 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06004197 else
4198 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004199 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004200
4201 spv::Builder::TextureParameters params = { };
4202 params.sampler = arguments[0];
4203
Rex Xu04db3f52015-09-16 11:44:02 +08004204 glslang::TCrackedTextureOp cracked;
4205 node->crackTexture(sampler, cracked);
4206
amhagan05506bb2017-06-13 16:53:02 -04004207 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004208
John Kessenichfc51d282015-08-19 13:34:18 -06004209 // Check for queries
4210 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004211 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4212 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004213 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004214
John Kessenichfc51d282015-08-19 13:34:18 -06004215 switch (node->getOp()) {
4216 case glslang::EOpImageQuerySize:
4217 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004218 if (arguments.size() > 1) {
4219 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004220 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004221 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004222 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004223 case glslang::EOpImageQuerySamples:
4224 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004225 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004226 case glslang::EOpTextureQueryLod:
4227 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004228 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004229 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004230 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004231 case glslang::EOpSparseTexelsResident:
4232 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004233 default:
4234 assert(0);
4235 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004236 }
John Kessenich140f3df2015-06-26 16:58:36 -06004237 }
4238
LoopDawg4425f242018-02-18 11:40:01 -07004239 int components = node->getType().getVectorSize();
4240
4241 if (node->getOp() == glslang::EOpTextureFetch) {
4242 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4243 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4244 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4245 // here around e.g. which ones return scalars or other types.
4246 components = 4;
4247 }
4248
4249 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4250
4251 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4252
Rex Xufc618912015-09-09 16:42:49 +08004253 // Check for image functions other than queries
4254 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004255 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004256 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004257 spv::IdImmediate image = { true, *(opIt++) };
4258 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004259
4260 // Handle subpass operations
4261 // TODO: GLSL should change to have the "MS" only on the type rather than the
4262 // built-in function.
4263 if (cracked.subpass) {
4264 // add on the (0,0) coordinate
4265 spv::Id zero = builder.makeIntConstant(0);
4266 std::vector<spv::Id> comps;
4267 comps.push_back(zero);
4268 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004269 spv::IdImmediate coord = { true,
4270 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4271 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07004272 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06004273 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
4274 operands.push_back(imageOperands);
4275 spv::IdImmediate imageOperand = { true, *(opIt++) };
4276 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07004277 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004278 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4279 builder.setPrecision(result, precision);
4280 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004281 }
4282
John Kessenich149afc32018-08-14 13:31:43 -06004283 spv::IdImmediate coord = { true, *(opIt++) };
4284 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004285#ifdef AMD_EXTENSIONS
4286 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4287#else
John Kessenich56bab042015-09-16 10:54:31 -06004288 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004289#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004290 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004291 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004292 mask = mask | spv::ImageOperandsSampleMask;
4293 }
Rex Xu129799a2017-07-05 17:23:28 +08004294#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004295 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004296 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4297 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004298 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004299 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004300#endif
4301 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4302 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4303 if (mask) {
4304 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4305 operands.push_back(imageOperands);
4306 }
4307 if (mask & spv::ImageOperandsSampleMask) {
4308 spv::IdImmediate imageOperand = { true, *opIt++ };
4309 operands.push_back(imageOperand);
4310 }
4311#ifdef AMD_EXTENSIONS
4312 if (mask & spv::ImageOperandsLodMask) {
4313 spv::IdImmediate imageOperand = { true, *opIt++ };
4314 operands.push_back(imageOperand);
4315 }
4316#endif
4317 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4318 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4319 operands.push_back(imageOperand);
4320 }
4321
John Kessenich149afc32018-08-14 13:31:43 -06004322 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004323 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004324
John Kessenich149afc32018-08-14 13:31:43 -06004325 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004326 builder.setPrecision(result[0], precision);
4327
4328 // If needed, add a conversion constructor to the proper size.
4329 if (components != node->getType().getVectorSize())
4330 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4331
4332 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004333#ifdef AMD_EXTENSIONS
4334 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4335#else
John Kessenich56bab042015-09-16 10:54:31 -06004336 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004337#endif
Rex Xu129799a2017-07-05 17:23:28 +08004338
Jeff Bolz36831c92018-09-05 10:11:41 -05004339 // Push the texel value before the operands
4340#ifdef AMD_EXTENSIONS
4341 if (sampler.ms || cracked.lod) {
4342#else
4343 if (sampler.ms) {
4344#endif
John Kessenich149afc32018-08-14 13:31:43 -06004345 spv::IdImmediate texel = { true, *(opIt + 1) };
4346 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004347 } else {
4348 spv::IdImmediate texel = { true, *opIt };
4349 operands.push_back(texel);
4350 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004351
4352 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4353 if (sampler.ms) {
4354 mask = mask | spv::ImageOperandsSampleMask;
4355 }
4356#ifdef AMD_EXTENSIONS
4357 if (cracked.lod) {
4358 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4359 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4360 mask = mask | spv::ImageOperandsLodMask;
4361 }
4362#endif
4363 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4364 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
4365 if (mask) {
4366 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4367 operands.push_back(imageOperands);
4368 }
4369 if (mask & spv::ImageOperandsSampleMask) {
4370 spv::IdImmediate imageOperand = { true, *opIt++ };
4371 operands.push_back(imageOperand);
4372 }
4373#ifdef AMD_EXTENSIONS
4374 if (mask & spv::ImageOperandsLodMask) {
4375 spv::IdImmediate imageOperand = { true, *opIt++ };
4376 operands.push_back(imageOperand);
4377 }
4378#endif
4379 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
4380 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4381 operands.push_back(imageOperand);
4382 }
4383
John Kessenich56bab042015-09-16 10:54:31 -06004384 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004385 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004386 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004387 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004388#ifdef AMD_EXTENSIONS
4389 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
4390#else
Rex Xu5eafa472016-02-19 22:24:03 +08004391 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004392#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004393 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004394 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004395 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4396
Jeff Bolz36831c92018-09-05 10:11:41 -05004397 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004398 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004399 mask = mask | spv::ImageOperandsSampleMask;
4400 }
Rex Xu129799a2017-07-05 17:23:28 +08004401#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004402 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004403 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4404 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4405
Jeff Bolz36831c92018-09-05 10:11:41 -05004406 mask = mask | spv::ImageOperandsLodMask;
4407 }
4408#endif
4409 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4410 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4411 if (mask) {
4412 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004413 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004414 }
4415 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004416 spv::IdImmediate imageOperand = { true, *opIt++ };
4417 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004418 }
4419#ifdef AMD_EXTENSIONS
4420 if (mask & spv::ImageOperandsLodMask) {
4421 spv::IdImmediate imageOperand = { true, *opIt++ };
4422 operands.push_back(imageOperand);
4423 }
Rex Xu129799a2017-07-05 17:23:28 +08004424#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004425 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4426 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4427 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004428 }
4429
4430 // Create the return type that was a special structure
4431 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004432 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004433 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4434 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4435
4436 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4437
4438 // Decode the return type
4439 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4440 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004441 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004442 // Process image atomic operations
4443
4444 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4445 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004446 // For non-MS, the sample value should be 0
4447 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4448 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004449
Jeff Bolz36831c92018-09-05 10:11:41 -05004450 spv::Id resultTypeId;
4451 // imageAtomicStore has a void return type so base the pointer type on
4452 // the type of the value operand.
4453 if (node->getOp() == glslang::EOpImageAtomicStore) {
4454 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4455 } else {
4456 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4457 }
John Kessenich56bab042015-09-16 10:54:31 -06004458 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004459
4460 std::vector<spv::Id> operands;
4461 operands.push_back(pointer);
4462 for (; opIt != arguments.end(); ++opIt)
4463 operands.push_back(*opIt);
4464
John Kessenich8c8505c2016-07-26 12:50:38 -06004465 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004466 }
4467 }
4468
amhagan05506bb2017-06-13 16:53:02 -04004469#ifdef AMD_EXTENSIONS
4470 // Check for fragment mask functions other than queries
4471 if (cracked.fragMask) {
4472 assert(sampler.ms);
4473
4474 auto opIt = arguments.begin();
4475 std::vector<spv::Id> operands;
4476
4477 // Extract the image if necessary
4478 if (builder.isSampledImage(params.sampler))
4479 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4480
4481 operands.push_back(params.sampler);
4482 ++opIt;
4483
4484 if (sampler.isSubpass()) {
4485 // add on the (0,0) coordinate
4486 spv::Id zero = builder.makeIntConstant(0);
4487 std::vector<spv::Id> comps;
4488 comps.push_back(zero);
4489 comps.push_back(zero);
4490 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4491 }
4492
4493 for (; opIt != arguments.end(); ++opIt)
4494 operands.push_back(*opIt);
4495
4496 spv::Op fragMaskOp = spv::OpNop;
4497 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4498 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4499 else if (node->getOp() == glslang::EOpFragmentFetch)
4500 fragMaskOp = spv::OpFragmentFetchAMD;
4501
4502 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4503 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4504 return builder.createOp(fragMaskOp, resultType(), operands);
4505 }
4506#endif
4507
Rex Xufc618912015-09-09 16:42:49 +08004508 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004509 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004510#ifdef NV_EXTENSIONS
4511 bool imageFootprint = node->isImageFootprint();
4512#endif
4513
Rex Xu71519fe2015-11-11 15:35:47 +08004514 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4515
John Kessenichfc51d282015-08-19 13:34:18 -06004516 // check for bias argument
4517 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004518#ifdef AMD_EXTENSIONS
4519 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4520#else
Rex Xu71519fe2015-11-11 15:35:47 +08004521 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004522#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004523 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004524#ifdef AMD_EXTENSIONS
4525 if (cracked.gather)
4526 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004527
4528 if (f16ShadowCompare)
4529 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004530#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004531 if (cracked.offset)
4532 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004533#ifdef AMD_EXTENSIONS
4534 else if (cracked.offsets)
4535 ++nonBiasArgCount;
4536#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004537 if (cracked.grad)
4538 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004539 if (cracked.lodClamp)
4540 ++nonBiasArgCount;
4541 if (sparse)
4542 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004543#ifdef NV_EXTENSIONS
4544 if (imageFootprint)
4545 //Following three extra arguments
4546 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4547 nonBiasArgCount += 3;
4548#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004549 if ((int)arguments.size() > nonBiasArgCount)
4550 bias = true;
4551 }
4552
John Kessenicha5c33d62016-06-02 23:45:21 -06004553 // See if the sampler param should really be just the SPV image part
4554 if (cracked.fetch) {
4555 // a fetch needs to have the image extracted first
4556 if (builder.isSampledImage(params.sampler))
4557 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4558 }
4559
Rex Xu225e0fc2016-11-17 17:47:59 +08004560#ifdef AMD_EXTENSIONS
4561 if (cracked.gather) {
4562 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4563 if (bias || cracked.lod ||
4564 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4565 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004566 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004567 }
4568 }
4569#endif
4570
John Kessenichfc51d282015-08-19 13:34:18 -06004571 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004572
John Kessenichfc51d282015-08-19 13:34:18 -06004573 params.coords = arguments[1];
4574 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004575 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004576
4577 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004578#ifdef AMD_EXTENSIONS
4579 if (cubeCompare || f16ShadowCompare) {
4580#else
Rex Xu48edadf2015-12-31 16:11:41 +08004581 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004582#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004583 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004584 ++extraArgs;
4585 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004586 params.Dref = arguments[2];
4587 ++extraArgs;
4588 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004589 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004590 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004591 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004592 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004593 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004594 dRefComp = builder.getNumComponents(params.coords) - 1;
4595 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004596 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4597 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004598
4599 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004600 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004601 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004602 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004603 } else if (glslangIntermediate->getStage() != EShLangFragment
4604#ifdef NV_EXTENSIONS
4605 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4606 && !(glslangIntermediate->getStage() == EShLangCompute &&
4607 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4608#endif
4609 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004610 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4611 noImplicitLod = true;
4612 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004613
4614 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004615 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004616 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004617 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004618 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004619
4620 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004621 if (cracked.grad) {
4622 params.gradX = arguments[2 + extraArgs];
4623 params.gradY = arguments[3 + extraArgs];
4624 extraArgs += 2;
4625 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004626
4627 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004628 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004629 params.offset = arguments[2 + extraArgs];
4630 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004631 } else if (cracked.offsets) {
4632 params.offsets = arguments[2 + extraArgs];
4633 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004634 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004635
4636 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004637 if (cracked.lodClamp) {
4638 params.lodClamp = arguments[2 + extraArgs];
4639 ++extraArgs;
4640 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004641 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004642 if (sparse) {
4643 params.texelOut = arguments[2 + extraArgs];
4644 ++extraArgs;
4645 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004646
John Kessenich76d4dfc2016-06-16 12:43:23 -06004647 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004648 if (cracked.gather && ! sampler.shadow) {
4649 // default component is 0, if missing, otherwise an argument
4650 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004651 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004652 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004653 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004654 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004655 }
Chao Chen3a137962018-09-19 11:41:27 -07004656#ifdef NV_EXTENSIONS
4657 spv::Id resultStruct = spv::NoResult;
4658 if (imageFootprint) {
4659 //Following three extra arguments
4660 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4661 params.granularity = arguments[2 + extraArgs];
4662 params.coarse = arguments[3 + extraArgs];
4663 resultStruct = arguments[4 + extraArgs];
4664 extraArgs += 3;
4665 }
4666#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004667 // bias
4668 if (bias) {
4669 params.bias = arguments[2 + extraArgs];
4670 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004671 }
John Kessenichfc51d282015-08-19 13:34:18 -06004672
Chao Chen3a137962018-09-19 11:41:27 -07004673#ifdef NV_EXTENSIONS
4674 if (imageFootprint) {
4675 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4676 builder.addCapability(spv::CapabilityImageFootprintNV);
4677
4678
4679 //resultStructType(OpenGL type) contains 5 elements:
4680 //struct gl_TextureFootprint2DNV {
4681 // uvec2 anchor;
4682 // uvec2 offset;
4683 // uvec2 mask;
4684 // uint lod;
4685 // uint granularity;
4686 //};
4687 //or
4688 //struct gl_TextureFootprint3DNV {
4689 // uvec3 anchor;
4690 // uvec3 offset;
4691 // uvec2 mask;
4692 // uint lod;
4693 // uint granularity;
4694 //};
4695 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4696 assert(builder.isStructType(resultStructType));
4697
4698 //resType (SPIR-V type) contains 6 elements:
4699 //Member 0 must be a Boolean type scalar(LOD),
4700 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4701 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4702 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4703 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4704 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4705 std::vector<spv::Id> members;
4706 members.push_back(resultType());
4707 for (int i = 0; i < 5; i++) {
4708 members.push_back(builder.getContainedTypeId(resultStructType, i));
4709 }
4710 spv::Id resType = builder.makeStructType(members, "ResType");
4711
4712 //call ImageFootprintNV
4713 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
4714
4715 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4716 for (int i = 0; i < 5; i++) {
4717 builder.clearAccessChain();
4718 builder.setAccessChainLValue(resultStruct);
4719
4720 //Accessing to a struct we created, no coherent flag is set
4721 spv::Builder::AccessChain::CoherentFlags flags;
4722 flags.clear();
4723
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004724 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004725 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4726 }
4727 return builder.createCompositeExtract(res, resultType(), 0);
4728 }
4729#endif
4730
John Kessenich65336482016-06-16 14:06:26 -06004731 // projective component (might not to move)
4732 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4733 // are divided by the last component of P."
4734 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4735 // unused components will appear after all used components."
4736 if (cracked.proj) {
4737 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4738 int projTargetComp;
4739 switch (sampler.dim) {
4740 case glslang::Esd1D: projTargetComp = 1; break;
4741 case glslang::Esd2D: projTargetComp = 2; break;
4742 case glslang::EsdRect: projTargetComp = 2; break;
4743 default: projTargetComp = projSourceComp; break;
4744 }
4745 // copy the projective coordinate if we have to
4746 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004747 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004748 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4749 projSourceComp);
4750 params.coords = builder.createCompositeInsert(projComp, params.coords,
4751 builder.getTypeId(params.coords), projTargetComp);
4752 }
4753 }
4754
Jeff Bolz36831c92018-09-05 10:11:41 -05004755 // nonprivate
4756 if (imageType.getQualifier().nonprivate) {
4757 params.nonprivate = true;
4758 }
4759
4760 // volatile
4761 if (imageType.getQualifier().volatil) {
4762 params.volatil = true;
4763 }
4764
St0fFa1184dd2018-04-09 21:08:14 +02004765 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004766 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004767 );
LoopDawg4425f242018-02-18 11:40:01 -07004768
4769 if (components != node->getType().getVectorSize())
4770 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4771
4772 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004773}
4774
4775spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4776{
4777 // Grab the function's pointer from the previously created function
4778 spv::Function* function = functionMap[node->getName().c_str()];
4779 if (! function)
4780 return 0;
4781
4782 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4783 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4784
4785 // See comments in makeFunctions() for details about the semantics for parameter passing.
4786 //
4787 // These imply we need a four step process:
4788 // 1. Evaluate the arguments
4789 // 2. Allocate and make copies of in, out, and inout arguments
4790 // 3. Make the call
4791 // 4. Copy back the results
4792
John Kessenichd3ed90b2018-05-04 11:43:03 -06004793 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004794 std::vector<spv::Builder::AccessChain> lValues;
4795 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004796 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004797 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004798 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004799 // build l-value
4800 builder.clearAccessChain();
4801 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004802 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004803 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004804 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004805 // save l-value
4806 lValues.push_back(builder.getAccessChain());
4807 } else {
4808 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004809 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004810 }
4811 }
4812
4813 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4814 // copy the original into that space.
4815 //
4816 // Also, build up the list of actual arguments to pass in for the call
4817 int lValueCount = 0;
4818 int rValueCount = 0;
4819 std::vector<spv::Id> spvArgs;
4820 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4821 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004822 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004823 builder.setAccessChain(lValues[lValueCount]);
4824 arg = builder.accessChainGetLValue();
4825 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004826 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004827 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004828 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004829 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4830 // need to copy the input into output space
4831 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004832 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004833 builder.clearAccessChain();
4834 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004835 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004836 }
4837 ++lValueCount;
4838 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004839 // process r-value, which involves a copy for a type mismatch
4840 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4841 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4842 builder.clearAccessChain();
4843 builder.setAccessChainLValue(argCopy);
4844 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4845 arg = builder.createLoad(argCopy);
4846 } else
4847 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004848 ++rValueCount;
4849 }
4850 spvArgs.push_back(arg);
4851 }
4852
4853 // 3. Make the call.
4854 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004855 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004856
4857 // 4. Copy back out an "out" arguments.
4858 lValueCount = 0;
4859 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004860 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004861 ++lValueCount;
4862 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004863 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4864 spv::Id copy = builder.createLoad(spvArgs[a]);
4865 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004866 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004867 }
4868 ++lValueCount;
4869 }
4870 }
4871
4872 return result;
4873}
4874
4875// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004876spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004877 spv::Id typeId, spv::Id left, spv::Id right,
4878 glslang::TBasicType typeProxy, bool reduceComparison)
4879{
John Kessenich66011cb2018-03-06 16:12:04 -07004880 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4881 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004882 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004883
4884 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004885 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004886 bool comparison = false;
4887
4888 switch (op) {
4889 case glslang::EOpAdd:
4890 case glslang::EOpAddAssign:
4891 if (isFloat)
4892 binOp = spv::OpFAdd;
4893 else
4894 binOp = spv::OpIAdd;
4895 break;
4896 case glslang::EOpSub:
4897 case glslang::EOpSubAssign:
4898 if (isFloat)
4899 binOp = spv::OpFSub;
4900 else
4901 binOp = spv::OpISub;
4902 break;
4903 case glslang::EOpMul:
4904 case glslang::EOpMulAssign:
4905 if (isFloat)
4906 binOp = spv::OpFMul;
4907 else
4908 binOp = spv::OpIMul;
4909 break;
4910 case glslang::EOpVectorTimesScalar:
4911 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004912 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004913 if (builder.isVector(right))
4914 std::swap(left, right);
4915 assert(builder.isScalar(right));
4916 needMatchingVectors = false;
4917 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01004918 } else if (isFloat)
4919 binOp = spv::OpFMul;
4920 else
John Kessenichec43d0a2015-07-04 17:17:31 -06004921 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004922 break;
4923 case glslang::EOpVectorTimesMatrix:
4924 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004925 binOp = spv::OpVectorTimesMatrix;
4926 break;
4927 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004928 binOp = spv::OpMatrixTimesVector;
4929 break;
4930 case glslang::EOpMatrixTimesScalar:
4931 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004932 binOp = spv::OpMatrixTimesScalar;
4933 break;
4934 case glslang::EOpMatrixTimesMatrix:
4935 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004936 binOp = spv::OpMatrixTimesMatrix;
4937 break;
4938 case glslang::EOpOuterProduct:
4939 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004940 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004941 break;
4942
4943 case glslang::EOpDiv:
4944 case glslang::EOpDivAssign:
4945 if (isFloat)
4946 binOp = spv::OpFDiv;
4947 else if (isUnsigned)
4948 binOp = spv::OpUDiv;
4949 else
4950 binOp = spv::OpSDiv;
4951 break;
4952 case glslang::EOpMod:
4953 case glslang::EOpModAssign:
4954 if (isFloat)
4955 binOp = spv::OpFMod;
4956 else if (isUnsigned)
4957 binOp = spv::OpUMod;
4958 else
4959 binOp = spv::OpSMod;
4960 break;
4961 case glslang::EOpRightShift:
4962 case glslang::EOpRightShiftAssign:
4963 if (isUnsigned)
4964 binOp = spv::OpShiftRightLogical;
4965 else
4966 binOp = spv::OpShiftRightArithmetic;
4967 break;
4968 case glslang::EOpLeftShift:
4969 case glslang::EOpLeftShiftAssign:
4970 binOp = spv::OpShiftLeftLogical;
4971 break;
4972 case glslang::EOpAnd:
4973 case glslang::EOpAndAssign:
4974 binOp = spv::OpBitwiseAnd;
4975 break;
4976 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004977 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004978 binOp = spv::OpLogicalAnd;
4979 break;
4980 case glslang::EOpInclusiveOr:
4981 case glslang::EOpInclusiveOrAssign:
4982 binOp = spv::OpBitwiseOr;
4983 break;
4984 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004985 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004986 binOp = spv::OpLogicalOr;
4987 break;
4988 case glslang::EOpExclusiveOr:
4989 case glslang::EOpExclusiveOrAssign:
4990 binOp = spv::OpBitwiseXor;
4991 break;
4992 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004993 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004994 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004995 break;
4996
4997 case glslang::EOpLessThan:
4998 case glslang::EOpGreaterThan:
4999 case glslang::EOpLessThanEqual:
5000 case glslang::EOpGreaterThanEqual:
5001 case glslang::EOpEqual:
5002 case glslang::EOpNotEqual:
5003 case glslang::EOpVectorEqual:
5004 case glslang::EOpVectorNotEqual:
5005 comparison = true;
5006 break;
5007 default:
5008 break;
5009 }
5010
John Kessenich7c1aa102015-10-15 13:29:11 -06005011 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005012 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005013 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005014 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5015 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005016 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005017
5018 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005019 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005020 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005021
qining25262b32016-05-06 17:25:16 -04005022 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005023 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005024 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005025 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005026 }
5027
5028 if (! comparison)
5029 return 0;
5030
John Kessenich7c1aa102015-10-15 13:29:11 -06005031 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005032
John Kessenich4583b612016-08-07 19:14:22 -06005033 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005034 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5035 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06005036 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005037 return result;
5038 }
John Kessenich140f3df2015-06-26 16:58:36 -06005039
5040 switch (op) {
5041 case glslang::EOpLessThan:
5042 if (isFloat)
5043 binOp = spv::OpFOrdLessThan;
5044 else if (isUnsigned)
5045 binOp = spv::OpULessThan;
5046 else
5047 binOp = spv::OpSLessThan;
5048 break;
5049 case glslang::EOpGreaterThan:
5050 if (isFloat)
5051 binOp = spv::OpFOrdGreaterThan;
5052 else if (isUnsigned)
5053 binOp = spv::OpUGreaterThan;
5054 else
5055 binOp = spv::OpSGreaterThan;
5056 break;
5057 case glslang::EOpLessThanEqual:
5058 if (isFloat)
5059 binOp = spv::OpFOrdLessThanEqual;
5060 else if (isUnsigned)
5061 binOp = spv::OpULessThanEqual;
5062 else
5063 binOp = spv::OpSLessThanEqual;
5064 break;
5065 case glslang::EOpGreaterThanEqual:
5066 if (isFloat)
5067 binOp = spv::OpFOrdGreaterThanEqual;
5068 else if (isUnsigned)
5069 binOp = spv::OpUGreaterThanEqual;
5070 else
5071 binOp = spv::OpSGreaterThanEqual;
5072 break;
5073 case glslang::EOpEqual:
5074 case glslang::EOpVectorEqual:
5075 if (isFloat)
5076 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005077 else if (isBool)
5078 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005079 else
5080 binOp = spv::OpIEqual;
5081 break;
5082 case glslang::EOpNotEqual:
5083 case glslang::EOpVectorNotEqual:
5084 if (isFloat)
5085 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005086 else if (isBool)
5087 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005088 else
5089 binOp = spv::OpINotEqual;
5090 break;
5091 default:
5092 break;
5093 }
5094
qining25262b32016-05-06 17:25:16 -04005095 if (binOp != spv::OpNop) {
5096 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005097 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005098 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005099 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005100 }
John Kessenich140f3df2015-06-26 16:58:36 -06005101
5102 return 0;
5103}
5104
John Kessenich04bb8a02015-12-12 12:28:14 -07005105//
5106// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5107// These can be any of:
5108//
5109// matrix * scalar
5110// scalar * matrix
5111// matrix * matrix linear algebraic
5112// matrix * vector
5113// vector * matrix
5114// matrix * matrix componentwise
5115// matrix op matrix op in {+, -, /}
5116// matrix op scalar op in {+, -, /}
5117// scalar op matrix op in {+, -, /}
5118//
John Kessenichead86222018-03-28 18:01:20 -06005119spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5120 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005121{
5122 bool firstClass = true;
5123
5124 // First, handle first-class matrix operations (* and matrix/scalar)
5125 switch (op) {
5126 case spv::OpFDiv:
5127 if (builder.isMatrix(left) && builder.isScalar(right)) {
5128 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005129 spv::Id resultType = builder.getTypeId(right);
5130 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005131 op = spv::OpMatrixTimesScalar;
5132 } else
5133 firstClass = false;
5134 break;
5135 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005136 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005137 std::swap(left, right);
5138 assert(builder.isScalar(right));
5139 break;
5140 case spv::OpVectorTimesMatrix:
5141 assert(builder.isVector(left));
5142 assert(builder.isMatrix(right));
5143 break;
5144 case spv::OpMatrixTimesVector:
5145 assert(builder.isMatrix(left));
5146 assert(builder.isVector(right));
5147 break;
5148 case spv::OpMatrixTimesMatrix:
5149 assert(builder.isMatrix(left));
5150 assert(builder.isMatrix(right));
5151 break;
5152 default:
5153 firstClass = false;
5154 break;
5155 }
5156
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005157 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5158 firstClass = true;
5159
qining25262b32016-05-06 17:25:16 -04005160 if (firstClass) {
5161 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005162 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005163 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005164 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005165 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005166
LoopDawg592860c2016-06-09 08:57:35 -06005167 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005168 // The result type of all of them is the same type as the (a) matrix operand.
5169 // The algorithm is to:
5170 // - break the matrix(es) into vectors
5171 // - smear any scalar to a vector
5172 // - do vector operations
5173 // - make a matrix out the vector results
5174 switch (op) {
5175 case spv::OpFAdd:
5176 case spv::OpFSub:
5177 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005178 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005179 case spv::OpFMul:
5180 {
5181 // one time set up...
5182 bool leftMat = builder.isMatrix(left);
5183 bool rightMat = builder.isMatrix(right);
5184 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5185 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5186 spv::Id scalarType = builder.getScalarTypeId(typeId);
5187 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5188 std::vector<spv::Id> results;
5189 spv::Id smearVec = spv::NoResult;
5190 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005191 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005192 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005193 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005194
5195 // do each vector op
5196 for (unsigned int c = 0; c < numCols; ++c) {
5197 std::vector<unsigned int> indexes;
5198 indexes.push_back(c);
5199 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5200 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005201 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005202 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005203 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005204 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005205 }
5206
5207 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005208 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005209 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005210 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005211 }
5212 default:
5213 assert(0);
5214 return spv::NoResult;
5215 }
5216}
5217
John Kessenichead86222018-03-28 18:01:20 -06005218spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
5219 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005220{
5221 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005222 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005223 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005224 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5225 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005226
5227 switch (op) {
5228 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005229 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005230 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005231 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005232 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005233 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005234 unaryOp = spv::OpSNegate;
5235 break;
5236
5237 case glslang::EOpLogicalNot:
5238 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005239 unaryOp = spv::OpLogicalNot;
5240 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005241 case glslang::EOpBitwiseNot:
5242 unaryOp = spv::OpNot;
5243 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005244
John Kessenich140f3df2015-06-26 16:58:36 -06005245 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005246 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005247 break;
5248 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005249 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005250 break;
5251 case glslang::EOpTranspose:
5252 unaryOp = spv::OpTranspose;
5253 break;
5254
5255 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005256 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005257 break;
5258 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005259 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005260 break;
5261 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005262 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005263 break;
5264 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005265 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005266 break;
5267 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005268 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005269 break;
5270 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005271 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005272 break;
5273 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005274 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005275 break;
5276 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005277 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005278 break;
5279
5280 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005281 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005282 break;
5283 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005284 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005285 break;
5286 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005287 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005288 break;
5289 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005290 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005291 break;
5292 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005293 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005294 break;
5295 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005296 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005297 break;
5298
5299 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005300 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005301 break;
5302 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005303 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005304 break;
5305
5306 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005307 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005308 break;
5309 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005310 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005311 break;
5312 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005313 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005314 break;
5315 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005316 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005317 break;
5318 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005319 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005320 break;
5321 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005322 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005323 break;
5324
5325 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005326 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005327 break;
5328 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005329 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005330 break;
5331 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005332 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005333 break;
5334 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005335 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005336 break;
5337 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005338 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005339 break;
5340 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005341 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005342 break;
5343
5344 case glslang::EOpIsNan:
5345 unaryOp = spv::OpIsNan;
5346 break;
5347 case glslang::EOpIsInf:
5348 unaryOp = spv::OpIsInf;
5349 break;
LoopDawg592860c2016-06-09 08:57:35 -06005350 case glslang::EOpIsFinite:
5351 unaryOp = spv::OpIsFinite;
5352 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005353
Rex Xucbc426e2015-12-15 16:03:10 +08005354 case glslang::EOpFloatBitsToInt:
5355 case glslang::EOpFloatBitsToUint:
5356 case glslang::EOpIntBitsToFloat:
5357 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005358 case glslang::EOpDoubleBitsToInt64:
5359 case glslang::EOpDoubleBitsToUint64:
5360 case glslang::EOpInt64BitsToDouble:
5361 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005362 case glslang::EOpFloat16BitsToInt16:
5363 case glslang::EOpFloat16BitsToUint16:
5364 case glslang::EOpInt16BitsToFloat16:
5365 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005366 unaryOp = spv::OpBitcast;
5367 break;
5368
John Kessenich140f3df2015-06-26 16:58:36 -06005369 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005370 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005371 break;
5372 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005373 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005374 break;
5375 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005376 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005377 break;
5378 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005379 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005380 break;
5381 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005382 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005383 break;
5384 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005385 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005386 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005387 case glslang::EOpPackSnorm4x8:
5388 libCall = spv::GLSLstd450PackSnorm4x8;
5389 break;
5390 case glslang::EOpUnpackSnorm4x8:
5391 libCall = spv::GLSLstd450UnpackSnorm4x8;
5392 break;
5393 case glslang::EOpPackUnorm4x8:
5394 libCall = spv::GLSLstd450PackUnorm4x8;
5395 break;
5396 case glslang::EOpUnpackUnorm4x8:
5397 libCall = spv::GLSLstd450UnpackUnorm4x8;
5398 break;
5399 case glslang::EOpPackDouble2x32:
5400 libCall = spv::GLSLstd450PackDouble2x32;
5401 break;
5402 case glslang::EOpUnpackDouble2x32:
5403 libCall = spv::GLSLstd450UnpackDouble2x32;
5404 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005405
Rex Xu8ff43de2016-04-22 16:51:45 +08005406 case glslang::EOpPackInt2x32:
5407 case glslang::EOpUnpackInt2x32:
5408 case glslang::EOpPackUint2x32:
5409 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005410 case glslang::EOpPack16:
5411 case glslang::EOpPack32:
5412 case glslang::EOpPack64:
5413 case glslang::EOpUnpack32:
5414 case glslang::EOpUnpack16:
5415 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005416 case glslang::EOpPackInt2x16:
5417 case glslang::EOpUnpackInt2x16:
5418 case glslang::EOpPackUint2x16:
5419 case glslang::EOpUnpackUint2x16:
5420 case glslang::EOpPackInt4x16:
5421 case glslang::EOpUnpackInt4x16:
5422 case glslang::EOpPackUint4x16:
5423 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005424 case glslang::EOpPackFloat2x16:
5425 case glslang::EOpUnpackFloat2x16:
5426 unaryOp = spv::OpBitcast;
5427 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005428
John Kessenich140f3df2015-06-26 16:58:36 -06005429 case glslang::EOpDPdx:
5430 unaryOp = spv::OpDPdx;
5431 break;
5432 case glslang::EOpDPdy:
5433 unaryOp = spv::OpDPdy;
5434 break;
5435 case glslang::EOpFwidth:
5436 unaryOp = spv::OpFwidth;
5437 break;
5438 case glslang::EOpDPdxFine:
5439 unaryOp = spv::OpDPdxFine;
5440 break;
5441 case glslang::EOpDPdyFine:
5442 unaryOp = spv::OpDPdyFine;
5443 break;
5444 case glslang::EOpFwidthFine:
5445 unaryOp = spv::OpFwidthFine;
5446 break;
5447 case glslang::EOpDPdxCoarse:
5448 unaryOp = spv::OpDPdxCoarse;
5449 break;
5450 case glslang::EOpDPdyCoarse:
5451 unaryOp = spv::OpDPdyCoarse;
5452 break;
5453 case glslang::EOpFwidthCoarse:
5454 unaryOp = spv::OpFwidthCoarse;
5455 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005456 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005457#ifdef AMD_EXTENSIONS
5458 if (typeProxy == glslang::EbtFloat16)
5459 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5460#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005461 libCall = spv::GLSLstd450InterpolateAtCentroid;
5462 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005463 case glslang::EOpAny:
5464 unaryOp = spv::OpAny;
5465 break;
5466 case glslang::EOpAll:
5467 unaryOp = spv::OpAll;
5468 break;
5469
5470 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005471 if (isFloat)
5472 libCall = spv::GLSLstd450FAbs;
5473 else
5474 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005475 break;
5476 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005477 if (isFloat)
5478 libCall = spv::GLSLstd450FSign;
5479 else
5480 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005481 break;
5482
John Kessenichfc51d282015-08-19 13:34:18 -06005483 case glslang::EOpAtomicCounterIncrement:
5484 case glslang::EOpAtomicCounterDecrement:
5485 case glslang::EOpAtomicCounter:
5486 {
5487 // Handle all of the atomics in one place, in createAtomicOperation()
5488 std::vector<spv::Id> operands;
5489 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005490 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005491 }
5492
John Kessenichfc51d282015-08-19 13:34:18 -06005493 case glslang::EOpBitFieldReverse:
5494 unaryOp = spv::OpBitReverse;
5495 break;
5496 case glslang::EOpBitCount:
5497 unaryOp = spv::OpBitCount;
5498 break;
5499 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005500 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005501 break;
5502 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005503 if (isUnsigned)
5504 libCall = spv::GLSLstd450FindUMsb;
5505 else
5506 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005507 break;
5508
Rex Xu574ab042016-04-14 16:53:07 +08005509 case glslang::EOpBallot:
5510 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005511 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005512 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005513 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005514#ifdef AMD_EXTENSIONS
5515 case glslang::EOpMinInvocations:
5516 case glslang::EOpMaxInvocations:
5517 case glslang::EOpAddInvocations:
5518 case glslang::EOpMinInvocationsNonUniform:
5519 case glslang::EOpMaxInvocationsNonUniform:
5520 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005521 case glslang::EOpMinInvocationsInclusiveScan:
5522 case glslang::EOpMaxInvocationsInclusiveScan:
5523 case glslang::EOpAddInvocationsInclusiveScan:
5524 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5525 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5526 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5527 case glslang::EOpMinInvocationsExclusiveScan:
5528 case glslang::EOpMaxInvocationsExclusiveScan:
5529 case glslang::EOpAddInvocationsExclusiveScan:
5530 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5531 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5532 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005533#endif
Rex Xu51596642016-09-21 18:56:12 +08005534 {
5535 std::vector<spv::Id> operands;
5536 operands.push_back(operand);
5537 return createInvocationsOperation(op, typeId, operands, typeProxy);
5538 }
John Kessenich66011cb2018-03-06 16:12:04 -07005539 case glslang::EOpSubgroupAll:
5540 case glslang::EOpSubgroupAny:
5541 case glslang::EOpSubgroupAllEqual:
5542 case glslang::EOpSubgroupBroadcastFirst:
5543 case glslang::EOpSubgroupBallot:
5544 case glslang::EOpSubgroupInverseBallot:
5545 case glslang::EOpSubgroupBallotBitCount:
5546 case glslang::EOpSubgroupBallotInclusiveBitCount:
5547 case glslang::EOpSubgroupBallotExclusiveBitCount:
5548 case glslang::EOpSubgroupBallotFindLSB:
5549 case glslang::EOpSubgroupBallotFindMSB:
5550 case glslang::EOpSubgroupAdd:
5551 case glslang::EOpSubgroupMul:
5552 case glslang::EOpSubgroupMin:
5553 case glslang::EOpSubgroupMax:
5554 case glslang::EOpSubgroupAnd:
5555 case glslang::EOpSubgroupOr:
5556 case glslang::EOpSubgroupXor:
5557 case glslang::EOpSubgroupInclusiveAdd:
5558 case glslang::EOpSubgroupInclusiveMul:
5559 case glslang::EOpSubgroupInclusiveMin:
5560 case glslang::EOpSubgroupInclusiveMax:
5561 case glslang::EOpSubgroupInclusiveAnd:
5562 case glslang::EOpSubgroupInclusiveOr:
5563 case glslang::EOpSubgroupInclusiveXor:
5564 case glslang::EOpSubgroupExclusiveAdd:
5565 case glslang::EOpSubgroupExclusiveMul:
5566 case glslang::EOpSubgroupExclusiveMin:
5567 case glslang::EOpSubgroupExclusiveMax:
5568 case glslang::EOpSubgroupExclusiveAnd:
5569 case glslang::EOpSubgroupExclusiveOr:
5570 case glslang::EOpSubgroupExclusiveXor:
5571 case glslang::EOpSubgroupQuadSwapHorizontal:
5572 case glslang::EOpSubgroupQuadSwapVertical:
5573 case glslang::EOpSubgroupQuadSwapDiagonal: {
5574 std::vector<spv::Id> operands;
5575 operands.push_back(operand);
5576 return createSubgroupOperation(op, typeId, operands, typeProxy);
5577 }
Rex Xu9d93a232016-05-05 12:30:44 +08005578#ifdef AMD_EXTENSIONS
5579 case glslang::EOpMbcnt:
5580 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5581 libCall = spv::MbcntAMD;
5582 break;
5583
5584 case glslang::EOpCubeFaceIndex:
5585 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5586 libCall = spv::CubeFaceIndexAMD;
5587 break;
5588
5589 case glslang::EOpCubeFaceCoord:
5590 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5591 libCall = spv::CubeFaceCoordAMD;
5592 break;
5593#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005594#ifdef NV_EXTENSIONS
5595 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005596 unaryOp = spv::OpGroupNonUniformPartitionNV;
5597 break;
5598#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005599 case glslang::EOpConstructReference:
5600 unaryOp = spv::OpBitcast;
5601 break;
Jeff Bolz88220d52019-05-08 10:24:46 -05005602
5603 case glslang::EOpCopyObject:
5604 unaryOp = spv::OpCopyObject;
5605 break;
5606
John Kessenich140f3df2015-06-26 16:58:36 -06005607 default:
5608 return 0;
5609 }
5610
5611 spv::Id id;
5612 if (libCall >= 0) {
5613 std::vector<spv::Id> args;
5614 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005615 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005616 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005617 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005618 }
John Kessenich140f3df2015-06-26 16:58:36 -06005619
John Kessenichead86222018-03-28 18:01:20 -06005620 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005621 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005622 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005623}
5624
John Kessenich7a53f762016-01-20 11:19:27 -07005625// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005626spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5627 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005628{
5629 // Handle unary operations vector by vector.
5630 // The result type is the same type as the original type.
5631 // The algorithm is to:
5632 // - break the matrix into vectors
5633 // - apply the operation to each vector
5634 // - make a matrix out the vector results
5635
5636 // get the types sorted out
5637 int numCols = builder.getNumColumns(operand);
5638 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005639 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5640 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005641 std::vector<spv::Id> results;
5642
5643 // do each vector op
5644 for (int c = 0; c < numCols; ++c) {
5645 std::vector<unsigned int> indexes;
5646 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005647 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5648 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005649 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005650 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005651 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005652 }
5653
5654 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005655 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005656 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005657 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005658}
5659
John Kessenichad7645f2018-06-04 19:11:25 -06005660// For converting integers where both the bitwidth and the signedness could
5661// change, but only do the width change here. The caller is still responsible
5662// for the signedness conversion.
5663spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005664{
John Kessenichad7645f2018-06-04 19:11:25 -06005665 // Get the result type width, based on the type to convert to.
5666 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005667 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005668 case glslang::EOpConvInt16ToUint8:
5669 case glslang::EOpConvIntToUint8:
5670 case glslang::EOpConvInt64ToUint8:
5671 case glslang::EOpConvUint16ToInt8:
5672 case glslang::EOpConvUintToInt8:
5673 case glslang::EOpConvUint64ToInt8:
5674 width = 8;
5675 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005676 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005677 case glslang::EOpConvIntToUint16:
5678 case glslang::EOpConvInt64ToUint16:
5679 case glslang::EOpConvUint8ToInt16:
5680 case glslang::EOpConvUintToInt16:
5681 case glslang::EOpConvUint64ToInt16:
5682 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005683 break;
5684 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005685 case glslang::EOpConvInt16ToUint:
5686 case glslang::EOpConvInt64ToUint:
5687 case glslang::EOpConvUint8ToInt:
5688 case glslang::EOpConvUint16ToInt:
5689 case glslang::EOpConvUint64ToInt:
5690 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005691 break;
5692 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005693 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005694 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005695 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005696 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005697 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005698 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005699 break;
5700
5701 default:
5702 assert(false && "Default missing");
5703 break;
5704 }
5705
John Kessenichad7645f2018-06-04 19:11:25 -06005706 // Get the conversion operation and result type,
5707 // based on the target width, but the source type.
5708 spv::Id type = spv::NoType;
5709 spv::Op convOp = spv::OpNop;
5710 switch(op) {
5711 case glslang::EOpConvInt8ToUint16:
5712 case glslang::EOpConvInt8ToUint:
5713 case glslang::EOpConvInt8ToUint64:
5714 case glslang::EOpConvInt16ToUint8:
5715 case glslang::EOpConvInt16ToUint:
5716 case glslang::EOpConvInt16ToUint64:
5717 case glslang::EOpConvIntToUint8:
5718 case glslang::EOpConvIntToUint16:
5719 case glslang::EOpConvIntToUint64:
5720 case glslang::EOpConvInt64ToUint8:
5721 case glslang::EOpConvInt64ToUint16:
5722 case glslang::EOpConvInt64ToUint:
5723 convOp = spv::OpSConvert;
5724 type = builder.makeIntType(width);
5725 break;
5726 default:
5727 convOp = spv::OpUConvert;
5728 type = builder.makeUintType(width);
5729 break;
5730 }
5731
John Kessenich66011cb2018-03-06 16:12:04 -07005732 if (vectorSize > 0)
5733 type = builder.makeVectorType(type, vectorSize);
5734
John Kessenichad7645f2018-06-04 19:11:25 -06005735 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005736}
5737
John Kessenichead86222018-03-28 18:01:20 -06005738spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5739 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005740{
5741 spv::Op convOp = spv::OpNop;
5742 spv::Id zero = 0;
5743 spv::Id one = 0;
5744
5745 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5746
5747 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005748 case glslang::EOpConvInt8ToBool:
5749 case glslang::EOpConvUint8ToBool:
5750 zero = builder.makeUint8Constant(0);
5751 zero = makeSmearedConstant(zero, vectorSize);
5752 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005753 case glslang::EOpConvInt16ToBool:
5754 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005755 zero = builder.makeUint16Constant(0);
5756 zero = makeSmearedConstant(zero, vectorSize);
5757 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5758 case glslang::EOpConvIntToBool:
5759 case glslang::EOpConvUintToBool:
5760 zero = builder.makeUintConstant(0);
5761 zero = makeSmearedConstant(zero, vectorSize);
5762 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5763 case glslang::EOpConvInt64ToBool:
5764 case glslang::EOpConvUint64ToBool:
5765 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005766 zero = makeSmearedConstant(zero, vectorSize);
5767 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5768
5769 case glslang::EOpConvFloatToBool:
5770 zero = builder.makeFloatConstant(0.0F);
5771 zero = makeSmearedConstant(zero, vectorSize);
5772 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5773
5774 case glslang::EOpConvDoubleToBool:
5775 zero = builder.makeDoubleConstant(0.0);
5776 zero = makeSmearedConstant(zero, vectorSize);
5777 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5778
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005779 case glslang::EOpConvFloat16ToBool:
5780 zero = builder.makeFloat16Constant(0.0F);
5781 zero = makeSmearedConstant(zero, vectorSize);
5782 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005783
John Kessenich140f3df2015-06-26 16:58:36 -06005784 case glslang::EOpConvBoolToFloat:
5785 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005786 zero = builder.makeFloatConstant(0.0F);
5787 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005788 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005789
John Kessenich140f3df2015-06-26 16:58:36 -06005790 case glslang::EOpConvBoolToDouble:
5791 convOp = spv::OpSelect;
5792 zero = builder.makeDoubleConstant(0.0);
5793 one = builder.makeDoubleConstant(1.0);
5794 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005795
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005796 case glslang::EOpConvBoolToFloat16:
5797 convOp = spv::OpSelect;
5798 zero = builder.makeFloat16Constant(0.0F);
5799 one = builder.makeFloat16Constant(1.0F);
5800 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005801
5802 case glslang::EOpConvBoolToInt8:
5803 zero = builder.makeInt8Constant(0);
5804 one = builder.makeInt8Constant(1);
5805 convOp = spv::OpSelect;
5806 break;
5807
5808 case glslang::EOpConvBoolToUint8:
5809 zero = builder.makeUint8Constant(0);
5810 one = builder.makeUint8Constant(1);
5811 convOp = spv::OpSelect;
5812 break;
5813
5814 case glslang::EOpConvBoolToInt16:
5815 zero = builder.makeInt16Constant(0);
5816 one = builder.makeInt16Constant(1);
5817 convOp = spv::OpSelect;
5818 break;
5819
5820 case glslang::EOpConvBoolToUint16:
5821 zero = builder.makeUint16Constant(0);
5822 one = builder.makeUint16Constant(1);
5823 convOp = spv::OpSelect;
5824 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005825
John Kessenich140f3df2015-06-26 16:58:36 -06005826 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005827 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005828 if (op == glslang::EOpConvBoolToInt64)
5829 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005830 else
5831 zero = builder.makeIntConstant(0);
5832
5833 if (op == glslang::EOpConvBoolToInt64)
5834 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005835 else
5836 one = builder.makeIntConstant(1);
5837
John Kessenich140f3df2015-06-26 16:58:36 -06005838 convOp = spv::OpSelect;
5839 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005840
John Kessenich140f3df2015-06-26 16:58:36 -06005841 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005842 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005843 if (op == glslang::EOpConvBoolToUint64)
5844 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005845 else
5846 zero = builder.makeUintConstant(0);
5847
5848 if (op == glslang::EOpConvBoolToUint64)
5849 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005850 else
5851 one = builder.makeUintConstant(1);
5852
John Kessenich140f3df2015-06-26 16:58:36 -06005853 convOp = spv::OpSelect;
5854 break;
5855
John Kessenich66011cb2018-03-06 16:12:04 -07005856 case glslang::EOpConvInt8ToFloat16:
5857 case glslang::EOpConvInt8ToFloat:
5858 case glslang::EOpConvInt8ToDouble:
5859 case glslang::EOpConvInt16ToFloat16:
5860 case glslang::EOpConvInt16ToFloat:
5861 case glslang::EOpConvInt16ToDouble:
5862 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005863 case glslang::EOpConvIntToFloat:
5864 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005865 case glslang::EOpConvInt64ToFloat:
5866 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005867 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005868 convOp = spv::OpConvertSToF;
5869 break;
5870
John Kessenich66011cb2018-03-06 16:12:04 -07005871 case glslang::EOpConvUint8ToFloat16:
5872 case glslang::EOpConvUint8ToFloat:
5873 case glslang::EOpConvUint8ToDouble:
5874 case glslang::EOpConvUint16ToFloat16:
5875 case glslang::EOpConvUint16ToFloat:
5876 case glslang::EOpConvUint16ToDouble:
5877 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005878 case glslang::EOpConvUintToFloat:
5879 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005880 case glslang::EOpConvUint64ToFloat:
5881 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005882 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005883 convOp = spv::OpConvertUToF;
5884 break;
5885
5886 case glslang::EOpConvDoubleToFloat:
5887 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005888 case glslang::EOpConvDoubleToFloat16:
5889 case glslang::EOpConvFloat16ToDouble:
5890 case glslang::EOpConvFloatToFloat16:
5891 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005892 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005893 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005894 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005895 break;
5896
John Kessenich66011cb2018-03-06 16:12:04 -07005897 case glslang::EOpConvFloat16ToInt8:
5898 case glslang::EOpConvFloatToInt8:
5899 case glslang::EOpConvDoubleToInt8:
5900 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005901 case glslang::EOpConvFloatToInt16:
5902 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005903 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005904 case glslang::EOpConvFloatToInt:
5905 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005906 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005907 case glslang::EOpConvFloatToInt64:
5908 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005909 convOp = spv::OpConvertFToS;
5910 break;
5911
John Kessenich66011cb2018-03-06 16:12:04 -07005912 case glslang::EOpConvUint8ToInt8:
5913 case glslang::EOpConvInt8ToUint8:
5914 case glslang::EOpConvUint16ToInt16:
5915 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005916 case glslang::EOpConvUintToInt:
5917 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005918 case glslang::EOpConvUint64ToInt64:
5919 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005920 if (builder.isInSpecConstCodeGenMode()) {
5921 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005922 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5923 zero = builder.makeUint8Constant(0);
5924 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005925 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005926 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5927 zero = builder.makeUint64Constant(0);
5928 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005929 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005930 }
qining189b2032016-04-12 23:16:20 -04005931 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005932 // Use OpIAdd, instead of OpBitcast to do the conversion when
5933 // generating for OpSpecConstantOp instruction.
5934 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5935 }
5936 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005937 convOp = spv::OpBitcast;
5938 break;
5939
John Kessenich66011cb2018-03-06 16:12:04 -07005940 case glslang::EOpConvFloat16ToUint8:
5941 case glslang::EOpConvFloatToUint8:
5942 case glslang::EOpConvDoubleToUint8:
5943 case glslang::EOpConvFloat16ToUint16:
5944 case glslang::EOpConvFloatToUint16:
5945 case glslang::EOpConvDoubleToUint16:
5946 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005947 case glslang::EOpConvFloatToUint:
5948 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005949 case glslang::EOpConvFloatToUint64:
5950 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005951 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005952 convOp = spv::OpConvertFToU;
5953 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005954
John Kessenich66011cb2018-03-06 16:12:04 -07005955 case glslang::EOpConvInt8ToInt16:
5956 case glslang::EOpConvInt8ToInt:
5957 case glslang::EOpConvInt8ToInt64:
5958 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005959 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005960 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005961 case glslang::EOpConvIntToInt8:
5962 case glslang::EOpConvIntToInt16:
5963 case glslang::EOpConvIntToInt64:
5964 case glslang::EOpConvInt64ToInt8:
5965 case glslang::EOpConvInt64ToInt16:
5966 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005967 convOp = spv::OpSConvert;
5968 break;
5969
John Kessenich66011cb2018-03-06 16:12:04 -07005970 case glslang::EOpConvUint8ToUint16:
5971 case glslang::EOpConvUint8ToUint:
5972 case glslang::EOpConvUint8ToUint64:
5973 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005974 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005975 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005976 case glslang::EOpConvUintToUint8:
5977 case glslang::EOpConvUintToUint16:
5978 case glslang::EOpConvUintToUint64:
5979 case glslang::EOpConvUint64ToUint8:
5980 case glslang::EOpConvUint64ToUint16:
5981 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005982 convOp = spv::OpUConvert;
5983 break;
5984
John Kessenich66011cb2018-03-06 16:12:04 -07005985 case glslang::EOpConvInt8ToUint16:
5986 case glslang::EOpConvInt8ToUint:
5987 case glslang::EOpConvInt8ToUint64:
5988 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005989 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005990 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005991 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005992 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005993 case glslang::EOpConvIntToUint64:
5994 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005995 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005996 case glslang::EOpConvInt64ToUint:
5997 case glslang::EOpConvUint8ToInt16:
5998 case glslang::EOpConvUint8ToInt:
5999 case glslang::EOpConvUint8ToInt64:
6000 case glslang::EOpConvUint16ToInt8:
6001 case glslang::EOpConvUint16ToInt:
6002 case glslang::EOpConvUint16ToInt64:
6003 case glslang::EOpConvUintToInt8:
6004 case glslang::EOpConvUintToInt16:
6005 case glslang::EOpConvUintToInt64:
6006 case glslang::EOpConvUint64ToInt8:
6007 case glslang::EOpConvUint64ToInt16:
6008 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006009 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006010 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006011
6012 if (builder.isInSpecConstCodeGenMode()) {
6013 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006014 switch(op) {
6015 case glslang::EOpConvInt16ToUint8:
6016 case glslang::EOpConvIntToUint8:
6017 case glslang::EOpConvInt64ToUint8:
6018 case glslang::EOpConvUint16ToInt8:
6019 case glslang::EOpConvUintToInt8:
6020 case glslang::EOpConvUint64ToInt8:
6021 zero = builder.makeUint8Constant(0);
6022 break;
6023 case glslang::EOpConvInt8ToUint16:
6024 case glslang::EOpConvIntToUint16:
6025 case glslang::EOpConvInt64ToUint16:
6026 case glslang::EOpConvUint8ToInt16:
6027 case glslang::EOpConvUintToInt16:
6028 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006029 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006030 break;
6031 case glslang::EOpConvInt8ToUint:
6032 case glslang::EOpConvInt16ToUint:
6033 case glslang::EOpConvInt64ToUint:
6034 case glslang::EOpConvUint8ToInt:
6035 case glslang::EOpConvUint16ToInt:
6036 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006037 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006038 break;
6039 case glslang::EOpConvInt8ToUint64:
6040 case glslang::EOpConvInt16ToUint64:
6041 case glslang::EOpConvIntToUint64:
6042 case glslang::EOpConvUint8ToInt64:
6043 case glslang::EOpConvUint16ToInt64:
6044 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006045 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006046 break;
6047 default:
6048 assert(false && "Default missing");
6049 break;
6050 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006051 zero = makeSmearedConstant(zero, vectorSize);
6052 // Use OpIAdd, instead of OpBitcast to do the conversion when
6053 // generating for OpSpecConstantOp instruction.
6054 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6055 }
6056 // For normal run-time conversion instruction, use OpBitcast.
6057 convOp = spv::OpBitcast;
6058 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006059 case glslang::EOpConvUint64ToPtr:
6060 convOp = spv::OpConvertUToPtr;
6061 break;
6062 case glslang::EOpConvPtrToUint64:
6063 convOp = spv::OpConvertPtrToU;
6064 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006065 default:
6066 break;
6067 }
6068
6069 spv::Id result = 0;
6070 if (convOp == spv::OpNop)
6071 return result;
6072
6073 if (convOp == spv::OpSelect) {
6074 zero = makeSmearedConstant(zero, vectorSize);
6075 one = makeSmearedConstant(one, vectorSize);
6076 result = builder.createTriOp(convOp, destType, operand, one, zero);
6077 } else
6078 result = builder.createUnaryOp(convOp, destType, operand);
6079
John Kessenichead86222018-03-28 18:01:20 -06006080 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006081 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006082 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006083}
6084
6085spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6086{
6087 if (vectorSize == 0)
6088 return constant;
6089
6090 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6091 std::vector<spv::Id> components;
6092 for (int c = 0; c < vectorSize; ++c)
6093 components.push_back(constant);
6094 return builder.makeCompositeConstant(vectorTypeId, components);
6095}
6096
John Kessenich426394d2015-07-23 10:22:48 -06006097// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07006098spv::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 -06006099{
6100 spv::Op opCode = spv::OpNop;
6101
6102 switch (op) {
6103 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006104 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006105 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006106 opCode = spv::OpAtomicIAdd;
6107 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006108 case glslang::EOpAtomicCounterSubtract:
6109 opCode = spv::OpAtomicISub;
6110 break;
John Kessenich426394d2015-07-23 10:22:48 -06006111 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006112 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006113 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006114 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006115 break;
6116 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006117 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006118 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006119 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006120 break;
6121 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006122 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006123 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006124 opCode = spv::OpAtomicAnd;
6125 break;
6126 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006127 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006128 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006129 opCode = spv::OpAtomicOr;
6130 break;
6131 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006132 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006133 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006134 opCode = spv::OpAtomicXor;
6135 break;
6136 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006137 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006138 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006139 opCode = spv::OpAtomicExchange;
6140 break;
6141 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006142 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006143 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006144 opCode = spv::OpAtomicCompareExchange;
6145 break;
6146 case glslang::EOpAtomicCounterIncrement:
6147 opCode = spv::OpAtomicIIncrement;
6148 break;
6149 case glslang::EOpAtomicCounterDecrement:
6150 opCode = spv::OpAtomicIDecrement;
6151 break;
6152 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006153 case glslang::EOpImageAtomicLoad:
6154 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006155 opCode = spv::OpAtomicLoad;
6156 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006157 case glslang::EOpAtomicStore:
6158 case glslang::EOpImageAtomicStore:
6159 opCode = spv::OpAtomicStore;
6160 break;
John Kessenich426394d2015-07-23 10:22:48 -06006161 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006162 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006163 break;
6164 }
6165
Rex Xue8fe8b02017-09-26 15:42:56 +08006166 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6167 builder.addCapability(spv::CapabilityInt64Atomics);
6168
John Kessenich426394d2015-07-23 10:22:48 -06006169 // Sort out the operands
6170 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006171 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006172 // - compare-exchange swaps the value and comparator
6173 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006174 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006175 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6176 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6177 spv::Id scopeId;
6178 if (glslangIntermediate->usingVulkanMemoryModel()) {
6179 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6180 } else {
6181 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6182 }
6183 // semantics default to relaxed
6184 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
6185 spv::Id semanticsId2 = semanticsId;
6186
6187 pointerId = operands[0];
6188 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6189 // no additional operands
6190 } else if (opCode == spv::OpAtomicCompareExchange) {
6191 compareId = operands[1];
6192 valueId = operands[2];
6193 if (operands.size() > 3) {
6194 scopeId = operands[3];
6195 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6196 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6197 }
6198 } else if (opCode == spv::OpAtomicLoad) {
6199 if (operands.size() > 1) {
6200 scopeId = operands[1];
6201 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6202 }
6203 } else {
6204 // atomic store or RMW
6205 valueId = operands[1];
6206 if (operands.size() > 2) {
6207 scopeId = operands[2];
6208 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6209 }
Rex Xu04db3f52015-09-16 11:44:02 +08006210 }
John Kessenich426394d2015-07-23 10:22:48 -06006211
Jeff Bolz36831c92018-09-05 10:11:41 -05006212 // Check for capabilities
6213 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
6214 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6215 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6216 }
John Kessenich426394d2015-07-23 10:22:48 -06006217
Jeff Bolz36831c92018-09-05 10:11:41 -05006218 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6219 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6220 }
John Kessenich48d6e792017-10-06 21:21:48 -06006221
Jeff Bolz36831c92018-09-05 10:11:41 -05006222 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6223 spvAtomicOperands.push_back(pointerId);
6224 spvAtomicOperands.push_back(scopeId);
6225 spvAtomicOperands.push_back(semanticsId);
6226 if (opCode == spv::OpAtomicCompareExchange) {
6227 spvAtomicOperands.push_back(semanticsId2);
6228 spvAtomicOperands.push_back(valueId);
6229 spvAtomicOperands.push_back(compareId);
6230 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6231 spvAtomicOperands.push_back(valueId);
6232 }
John Kessenich48d6e792017-10-06 21:21:48 -06006233
Jeff Bolz36831c92018-09-05 10:11:41 -05006234 if (opCode == spv::OpAtomicStore) {
6235 builder.createNoResultOp(opCode, spvAtomicOperands);
6236 return 0;
6237 } else {
6238 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6239
6240 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6241 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6242 if (op == glslang::EOpAtomicCounterDecrement)
6243 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6244
6245 return resultId;
6246 }
John Kessenich426394d2015-07-23 10:22:48 -06006247}
6248
John Kessenich91cef522016-05-05 16:45:40 -06006249// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006250spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006251{
Corentin Walleze7061422018-08-08 15:20:15 +02006252#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006253 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6254 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006255#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006256
Rex Xu51596642016-09-21 18:56:12 +08006257 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006258 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006259 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6260
chaocf200da82016-12-20 12:44:35 -08006261 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6262 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006263 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6264 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006265 } else if (op == glslang::EOpAnyInvocation ||
6266 op == glslang::EOpAllInvocations ||
6267 op == glslang::EOpAllInvocationsEqual) {
6268 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6269 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006270 } else {
6271 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006272#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006273 if (op == glslang::EOpMinInvocationsNonUniform ||
6274 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006275 op == glslang::EOpAddInvocationsNonUniform ||
6276 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6277 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6278 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6279 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6280 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6281 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006282 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006283#endif
Rex Xu51596642016-09-21 18:56:12 +08006284
Rex Xu9d93a232016-05-05 12:30:44 +08006285#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006286 switch (op) {
6287 case glslang::EOpMinInvocations:
6288 case glslang::EOpMaxInvocations:
6289 case glslang::EOpAddInvocations:
6290 case glslang::EOpMinInvocationsNonUniform:
6291 case glslang::EOpMaxInvocationsNonUniform:
6292 case glslang::EOpAddInvocationsNonUniform:
6293 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006294 break;
6295 case glslang::EOpMinInvocationsInclusiveScan:
6296 case glslang::EOpMaxInvocationsInclusiveScan:
6297 case glslang::EOpAddInvocationsInclusiveScan:
6298 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6299 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6300 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6301 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006302 break;
6303 case glslang::EOpMinInvocationsExclusiveScan:
6304 case glslang::EOpMaxInvocationsExclusiveScan:
6305 case glslang::EOpAddInvocationsExclusiveScan:
6306 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6307 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6308 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6309 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006310 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006311 default:
6312 break;
Rex Xu430ef402016-10-14 17:22:23 +08006313 }
John Kessenich149afc32018-08-14 13:31:43 -06006314 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6315 spvGroupOperands.push_back(scope);
6316 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006317 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006318 spvGroupOperands.push_back(groupOp);
6319 }
Rex Xu9d93a232016-05-05 12:30:44 +08006320#endif
Rex Xu51596642016-09-21 18:56:12 +08006321 }
6322
John Kessenich149afc32018-08-14 13:31:43 -06006323 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6324 spv::IdImmediate op = { true, *opIt };
6325 spvGroupOperands.push_back(op);
6326 }
John Kessenich91cef522016-05-05 16:45:40 -06006327
6328 switch (op) {
6329 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006330 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006331 break;
John Kessenich91cef522016-05-05 16:45:40 -06006332 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006333 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006334 break;
John Kessenich91cef522016-05-05 16:45:40 -06006335 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006336 opCode = spv::OpSubgroupAllEqualKHR;
6337 break;
Rex Xu51596642016-09-21 18:56:12 +08006338 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006339 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006340 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006341 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006342 break;
6343 case glslang::EOpReadFirstInvocation:
6344 opCode = spv::OpSubgroupFirstInvocationKHR;
6345 break;
6346 case glslang::EOpBallot:
6347 {
6348 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6349 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6350 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6351 //
6352 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6353 //
6354 spv::Id uintType = builder.makeUintType(32);
6355 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6356 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6357
6358 std::vector<spv::Id> components;
6359 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6360 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6361
6362 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6363 return builder.createUnaryOp(spv::OpBitcast, typeId,
6364 builder.createCompositeConstruct(uvec2Type, components));
6365 }
6366
Rex Xu9d93a232016-05-05 12:30:44 +08006367#ifdef AMD_EXTENSIONS
6368 case glslang::EOpMinInvocations:
6369 case glslang::EOpMaxInvocations:
6370 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006371 case glslang::EOpMinInvocationsInclusiveScan:
6372 case glslang::EOpMaxInvocationsInclusiveScan:
6373 case glslang::EOpAddInvocationsInclusiveScan:
6374 case glslang::EOpMinInvocationsExclusiveScan:
6375 case glslang::EOpMaxInvocationsExclusiveScan:
6376 case glslang::EOpAddInvocationsExclusiveScan:
6377 if (op == glslang::EOpMinInvocations ||
6378 op == glslang::EOpMinInvocationsInclusiveScan ||
6379 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006380 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006381 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006382 else {
6383 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006384 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006385 else
Rex Xu51596642016-09-21 18:56:12 +08006386 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006387 }
Rex Xu430ef402016-10-14 17:22:23 +08006388 } else if (op == glslang::EOpMaxInvocations ||
6389 op == glslang::EOpMaxInvocationsInclusiveScan ||
6390 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006391 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006392 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006393 else {
6394 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006395 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006396 else
Rex Xu51596642016-09-21 18:56:12 +08006397 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006398 }
6399 } else {
6400 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006401 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006402 else
Rex Xu51596642016-09-21 18:56:12 +08006403 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006404 }
6405
Rex Xu2bbbe062016-08-23 15:41:05 +08006406 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006407 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006408
6409 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006410 case glslang::EOpMinInvocationsNonUniform:
6411 case glslang::EOpMaxInvocationsNonUniform:
6412 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006413 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6414 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6415 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6416 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6417 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6418 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6419 if (op == glslang::EOpMinInvocationsNonUniform ||
6420 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6421 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006422 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006423 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006424 else {
6425 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006426 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006427 else
Rex Xu51596642016-09-21 18:56:12 +08006428 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006429 }
6430 }
Rex Xu430ef402016-10-14 17:22:23 +08006431 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6432 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6433 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006434 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006435 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006436 else {
6437 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006438 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006439 else
Rex Xu51596642016-09-21 18:56:12 +08006440 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006441 }
6442 }
6443 else {
6444 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006445 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006446 else
Rex Xu51596642016-09-21 18:56:12 +08006447 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006448 }
6449
Rex Xu2bbbe062016-08-23 15:41:05 +08006450 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006451 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006452
6453 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006454#endif
John Kessenich91cef522016-05-05 16:45:40 -06006455 default:
6456 logger->missingFunctionality("invocation operation");
6457 return spv::NoResult;
6458 }
Rex Xu51596642016-09-21 18:56:12 +08006459
6460 assert(opCode != spv::OpNop);
6461 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006462}
6463
Rex Xu2bbbe062016-08-23 15:41:05 +08006464// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006465spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6466 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006467{
Rex Xub7072052016-09-26 15:53:40 +08006468#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006469 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6470 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006471 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006472 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006473 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6474 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6475 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006476#else
6477 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6478 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006479 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6480 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006481#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006482
6483 // Handle group invocation operations scalar by scalar.
6484 // The result type is the same type as the original type.
6485 // The algorithm is to:
6486 // - break the vector into scalars
6487 // - apply the operation to each scalar
6488 // - make a vector out the scalar results
6489
6490 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006491 int numComponents = builder.getNumComponents(operands[0]);
6492 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006493 std::vector<spv::Id> results;
6494
6495 // do each scalar op
6496 for (int comp = 0; comp < numComponents; ++comp) {
6497 std::vector<unsigned int> indexes;
6498 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006499 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6500 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006501 if (op == spv::OpSubgroupReadInvocationKHR) {
6502 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006503 spv::IdImmediate operand = { true, operands[1] };
6504 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006505 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006506 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6507 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006508 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006509 spv::IdImmediate operand = { true, operands[1] };
6510 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006511 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006512 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6513 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006514 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006515 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006516 spvGroupOperands.push_back(scalar);
6517 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006518
Rex Xub7072052016-09-26 15:53:40 +08006519 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006520 }
6521
6522 // put the pieces together
6523 return builder.createCompositeConstruct(typeId, results);
6524}
Rex Xu2bbbe062016-08-23 15:41:05 +08006525
John Kessenich66011cb2018-03-06 16:12:04 -07006526// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006527spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6528 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006529{
6530 // Add the required capabilities.
6531 switch (op) {
6532 case glslang::EOpSubgroupElect:
6533 builder.addCapability(spv::CapabilityGroupNonUniform);
6534 break;
6535 case glslang::EOpSubgroupAll:
6536 case glslang::EOpSubgroupAny:
6537 case glslang::EOpSubgroupAllEqual:
6538 builder.addCapability(spv::CapabilityGroupNonUniform);
6539 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6540 break;
6541 case glslang::EOpSubgroupBroadcast:
6542 case glslang::EOpSubgroupBroadcastFirst:
6543 case glslang::EOpSubgroupBallot:
6544 case glslang::EOpSubgroupInverseBallot:
6545 case glslang::EOpSubgroupBallotBitExtract:
6546 case glslang::EOpSubgroupBallotBitCount:
6547 case glslang::EOpSubgroupBallotInclusiveBitCount:
6548 case glslang::EOpSubgroupBallotExclusiveBitCount:
6549 case glslang::EOpSubgroupBallotFindLSB:
6550 case glslang::EOpSubgroupBallotFindMSB:
6551 builder.addCapability(spv::CapabilityGroupNonUniform);
6552 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6553 break;
6554 case glslang::EOpSubgroupShuffle:
6555 case glslang::EOpSubgroupShuffleXor:
6556 builder.addCapability(spv::CapabilityGroupNonUniform);
6557 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6558 break;
6559 case glslang::EOpSubgroupShuffleUp:
6560 case glslang::EOpSubgroupShuffleDown:
6561 builder.addCapability(spv::CapabilityGroupNonUniform);
6562 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6563 break;
6564 case glslang::EOpSubgroupAdd:
6565 case glslang::EOpSubgroupMul:
6566 case glslang::EOpSubgroupMin:
6567 case glslang::EOpSubgroupMax:
6568 case glslang::EOpSubgroupAnd:
6569 case glslang::EOpSubgroupOr:
6570 case glslang::EOpSubgroupXor:
6571 case glslang::EOpSubgroupInclusiveAdd:
6572 case glslang::EOpSubgroupInclusiveMul:
6573 case glslang::EOpSubgroupInclusiveMin:
6574 case glslang::EOpSubgroupInclusiveMax:
6575 case glslang::EOpSubgroupInclusiveAnd:
6576 case glslang::EOpSubgroupInclusiveOr:
6577 case glslang::EOpSubgroupInclusiveXor:
6578 case glslang::EOpSubgroupExclusiveAdd:
6579 case glslang::EOpSubgroupExclusiveMul:
6580 case glslang::EOpSubgroupExclusiveMin:
6581 case glslang::EOpSubgroupExclusiveMax:
6582 case glslang::EOpSubgroupExclusiveAnd:
6583 case glslang::EOpSubgroupExclusiveOr:
6584 case glslang::EOpSubgroupExclusiveXor:
6585 builder.addCapability(spv::CapabilityGroupNonUniform);
6586 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6587 break;
6588 case glslang::EOpSubgroupClusteredAdd:
6589 case glslang::EOpSubgroupClusteredMul:
6590 case glslang::EOpSubgroupClusteredMin:
6591 case glslang::EOpSubgroupClusteredMax:
6592 case glslang::EOpSubgroupClusteredAnd:
6593 case glslang::EOpSubgroupClusteredOr:
6594 case glslang::EOpSubgroupClusteredXor:
6595 builder.addCapability(spv::CapabilityGroupNonUniform);
6596 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6597 break;
6598 case glslang::EOpSubgroupQuadBroadcast:
6599 case glslang::EOpSubgroupQuadSwapHorizontal:
6600 case glslang::EOpSubgroupQuadSwapVertical:
6601 case glslang::EOpSubgroupQuadSwapDiagonal:
6602 builder.addCapability(spv::CapabilityGroupNonUniform);
6603 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6604 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006605#ifdef NV_EXTENSIONS
6606 case glslang::EOpSubgroupPartitionedAdd:
6607 case glslang::EOpSubgroupPartitionedMul:
6608 case glslang::EOpSubgroupPartitionedMin:
6609 case glslang::EOpSubgroupPartitionedMax:
6610 case glslang::EOpSubgroupPartitionedAnd:
6611 case glslang::EOpSubgroupPartitionedOr:
6612 case glslang::EOpSubgroupPartitionedXor:
6613 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6614 case glslang::EOpSubgroupPartitionedInclusiveMul:
6615 case glslang::EOpSubgroupPartitionedInclusiveMin:
6616 case glslang::EOpSubgroupPartitionedInclusiveMax:
6617 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6618 case glslang::EOpSubgroupPartitionedInclusiveOr:
6619 case glslang::EOpSubgroupPartitionedInclusiveXor:
6620 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6621 case glslang::EOpSubgroupPartitionedExclusiveMul:
6622 case glslang::EOpSubgroupPartitionedExclusiveMin:
6623 case glslang::EOpSubgroupPartitionedExclusiveMax:
6624 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6625 case glslang::EOpSubgroupPartitionedExclusiveOr:
6626 case glslang::EOpSubgroupPartitionedExclusiveXor:
6627 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6628 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6629 break;
6630#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006631 default: assert(0 && "Unhandled subgroup operation!");
6632 }
6633
6634 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6635 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6636 const bool isBool = typeProxy == glslang::EbtBool;
6637
6638 spv::Op opCode = spv::OpNop;
6639
6640 // Figure out which opcode to use.
6641 switch (op) {
6642 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6643 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6644 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6645 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6646 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6647 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6648 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6649 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6650 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6651 case glslang::EOpSubgroupBallotBitCount:
6652 case glslang::EOpSubgroupBallotInclusiveBitCount:
6653 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6654 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6655 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6656 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6657 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6658 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6659 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6660 case glslang::EOpSubgroupAdd:
6661 case glslang::EOpSubgroupInclusiveAdd:
6662 case glslang::EOpSubgroupExclusiveAdd:
6663 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006664#ifdef NV_EXTENSIONS
6665 case glslang::EOpSubgroupPartitionedAdd:
6666 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6667 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6668#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006669 if (isFloat) {
6670 opCode = spv::OpGroupNonUniformFAdd;
6671 } else {
6672 opCode = spv::OpGroupNonUniformIAdd;
6673 }
6674 break;
6675 case glslang::EOpSubgroupMul:
6676 case glslang::EOpSubgroupInclusiveMul:
6677 case glslang::EOpSubgroupExclusiveMul:
6678 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006679#ifdef NV_EXTENSIONS
6680 case glslang::EOpSubgroupPartitionedMul:
6681 case glslang::EOpSubgroupPartitionedInclusiveMul:
6682 case glslang::EOpSubgroupPartitionedExclusiveMul:
6683#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006684 if (isFloat) {
6685 opCode = spv::OpGroupNonUniformFMul;
6686 } else {
6687 opCode = spv::OpGroupNonUniformIMul;
6688 }
6689 break;
6690 case glslang::EOpSubgroupMin:
6691 case glslang::EOpSubgroupInclusiveMin:
6692 case glslang::EOpSubgroupExclusiveMin:
6693 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006694#ifdef NV_EXTENSIONS
6695 case glslang::EOpSubgroupPartitionedMin:
6696 case glslang::EOpSubgroupPartitionedInclusiveMin:
6697 case glslang::EOpSubgroupPartitionedExclusiveMin:
6698#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006699 if (isFloat) {
6700 opCode = spv::OpGroupNonUniformFMin;
6701 } else if (isUnsigned) {
6702 opCode = spv::OpGroupNonUniformUMin;
6703 } else {
6704 opCode = spv::OpGroupNonUniformSMin;
6705 }
6706 break;
6707 case glslang::EOpSubgroupMax:
6708 case glslang::EOpSubgroupInclusiveMax:
6709 case glslang::EOpSubgroupExclusiveMax:
6710 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006711#ifdef NV_EXTENSIONS
6712 case glslang::EOpSubgroupPartitionedMax:
6713 case glslang::EOpSubgroupPartitionedInclusiveMax:
6714 case glslang::EOpSubgroupPartitionedExclusiveMax:
6715#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006716 if (isFloat) {
6717 opCode = spv::OpGroupNonUniformFMax;
6718 } else if (isUnsigned) {
6719 opCode = spv::OpGroupNonUniformUMax;
6720 } else {
6721 opCode = spv::OpGroupNonUniformSMax;
6722 }
6723 break;
6724 case glslang::EOpSubgroupAnd:
6725 case glslang::EOpSubgroupInclusiveAnd:
6726 case glslang::EOpSubgroupExclusiveAnd:
6727 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006728#ifdef NV_EXTENSIONS
6729 case glslang::EOpSubgroupPartitionedAnd:
6730 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6731 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6732#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006733 if (isBool) {
6734 opCode = spv::OpGroupNonUniformLogicalAnd;
6735 } else {
6736 opCode = spv::OpGroupNonUniformBitwiseAnd;
6737 }
6738 break;
6739 case glslang::EOpSubgroupOr:
6740 case glslang::EOpSubgroupInclusiveOr:
6741 case glslang::EOpSubgroupExclusiveOr:
6742 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006743#ifdef NV_EXTENSIONS
6744 case glslang::EOpSubgroupPartitionedOr:
6745 case glslang::EOpSubgroupPartitionedInclusiveOr:
6746 case glslang::EOpSubgroupPartitionedExclusiveOr:
6747#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006748 if (isBool) {
6749 opCode = spv::OpGroupNonUniformLogicalOr;
6750 } else {
6751 opCode = spv::OpGroupNonUniformBitwiseOr;
6752 }
6753 break;
6754 case glslang::EOpSubgroupXor:
6755 case glslang::EOpSubgroupInclusiveXor:
6756 case glslang::EOpSubgroupExclusiveXor:
6757 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006758#ifdef NV_EXTENSIONS
6759 case glslang::EOpSubgroupPartitionedXor:
6760 case glslang::EOpSubgroupPartitionedInclusiveXor:
6761 case glslang::EOpSubgroupPartitionedExclusiveXor:
6762#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006763 if (isBool) {
6764 opCode = spv::OpGroupNonUniformLogicalXor;
6765 } else {
6766 opCode = spv::OpGroupNonUniformBitwiseXor;
6767 }
6768 break;
6769 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6770 case glslang::EOpSubgroupQuadSwapHorizontal:
6771 case glslang::EOpSubgroupQuadSwapVertical:
6772 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6773 default: assert(0 && "Unhandled subgroup operation!");
6774 }
6775
John Kessenich149afc32018-08-14 13:31:43 -06006776 // get the right Group Operation
6777 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006778 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006779 default:
6780 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006781 case glslang::EOpSubgroupBallotBitCount:
6782 case glslang::EOpSubgroupAdd:
6783 case glslang::EOpSubgroupMul:
6784 case glslang::EOpSubgroupMin:
6785 case glslang::EOpSubgroupMax:
6786 case glslang::EOpSubgroupAnd:
6787 case glslang::EOpSubgroupOr:
6788 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006789 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006790 break;
6791 case glslang::EOpSubgroupBallotInclusiveBitCount:
6792 case glslang::EOpSubgroupInclusiveAdd:
6793 case glslang::EOpSubgroupInclusiveMul:
6794 case glslang::EOpSubgroupInclusiveMin:
6795 case glslang::EOpSubgroupInclusiveMax:
6796 case glslang::EOpSubgroupInclusiveAnd:
6797 case glslang::EOpSubgroupInclusiveOr:
6798 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006799 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006800 break;
6801 case glslang::EOpSubgroupBallotExclusiveBitCount:
6802 case glslang::EOpSubgroupExclusiveAdd:
6803 case glslang::EOpSubgroupExclusiveMul:
6804 case glslang::EOpSubgroupExclusiveMin:
6805 case glslang::EOpSubgroupExclusiveMax:
6806 case glslang::EOpSubgroupExclusiveAnd:
6807 case glslang::EOpSubgroupExclusiveOr:
6808 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006809 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006810 break;
6811 case glslang::EOpSubgroupClusteredAdd:
6812 case glslang::EOpSubgroupClusteredMul:
6813 case glslang::EOpSubgroupClusteredMin:
6814 case glslang::EOpSubgroupClusteredMax:
6815 case glslang::EOpSubgroupClusteredAnd:
6816 case glslang::EOpSubgroupClusteredOr:
6817 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006818 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006819 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006820#ifdef NV_EXTENSIONS
6821 case glslang::EOpSubgroupPartitionedAdd:
6822 case glslang::EOpSubgroupPartitionedMul:
6823 case glslang::EOpSubgroupPartitionedMin:
6824 case glslang::EOpSubgroupPartitionedMax:
6825 case glslang::EOpSubgroupPartitionedAnd:
6826 case glslang::EOpSubgroupPartitionedOr:
6827 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006828 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006829 break;
6830 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6831 case glslang::EOpSubgroupPartitionedInclusiveMul:
6832 case glslang::EOpSubgroupPartitionedInclusiveMin:
6833 case glslang::EOpSubgroupPartitionedInclusiveMax:
6834 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6835 case glslang::EOpSubgroupPartitionedInclusiveOr:
6836 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006837 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006838 break;
6839 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6840 case glslang::EOpSubgroupPartitionedExclusiveMul:
6841 case glslang::EOpSubgroupPartitionedExclusiveMin:
6842 case glslang::EOpSubgroupPartitionedExclusiveMax:
6843 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6844 case glslang::EOpSubgroupPartitionedExclusiveOr:
6845 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006846 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006847 break;
6848#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006849 }
6850
John Kessenich149afc32018-08-14 13:31:43 -06006851 // build the instruction
6852 std::vector<spv::IdImmediate> spvGroupOperands;
6853
6854 // Every operation begins with the Execution Scope operand.
6855 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6856 spvGroupOperands.push_back(executionScope);
6857
6858 // Next, for all operations that use a Group Operation, push that as an operand.
6859 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006860 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006861 spvGroupOperands.push_back(groupOperand);
6862 }
6863
John Kessenich66011cb2018-03-06 16:12:04 -07006864 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006865 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6866 spv::IdImmediate operand = { true, *opIt };
6867 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006868 }
6869
6870 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006871 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006872 switch (op) {
6873 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006874 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6875 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6876 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6877 }
6878 if (directionId != spv::NoResult) {
6879 spv::IdImmediate direction = { true, directionId };
6880 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006881 }
6882
6883 return builder.createOp(opCode, typeId, spvGroupOperands);
6884}
6885
John Kessenich5e4b1242015-08-06 22:53:06 -06006886spv::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 -06006887{
John Kessenich66011cb2018-03-06 16:12:04 -07006888 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6889 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006890
John Kessenich140f3df2015-06-26 16:58:36 -06006891 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006892 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006893 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006894 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006895 spv::Id typeId0 = 0;
6896 if (consumedOperands > 0)
6897 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006898 spv::Id typeId1 = 0;
6899 if (consumedOperands > 1)
6900 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006901 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006902
6903 switch (op) {
6904 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006905 if (isFloat)
6906 libCall = spv::GLSLstd450FMin;
6907 else if (isUnsigned)
6908 libCall = spv::GLSLstd450UMin;
6909 else
6910 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006911 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006912 break;
6913 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006914 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006915 break;
6916 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006917 if (isFloat)
6918 libCall = spv::GLSLstd450FMax;
6919 else if (isUnsigned)
6920 libCall = spv::GLSLstd450UMax;
6921 else
6922 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006923 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006924 break;
6925 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006926 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006927 break;
6928 case glslang::EOpDot:
6929 opCode = spv::OpDot;
6930 break;
6931 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006932 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006933 break;
6934
6935 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006936 if (isFloat)
6937 libCall = spv::GLSLstd450FClamp;
6938 else if (isUnsigned)
6939 libCall = spv::GLSLstd450UClamp;
6940 else
6941 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006942 builder.promoteScalar(precision, operands.front(), operands[1]);
6943 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006944 break;
6945 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006946 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6947 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006948 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006949 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006950 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006951 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006952 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006953 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006954 break;
6955 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006956 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006957 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006958 break;
6959 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006960 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006961 builder.promoteScalar(precision, operands[0], operands[2]);
6962 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006963 break;
6964
6965 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006966 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006967 break;
6968 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006969 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006970 break;
6971 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006972 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006973 break;
6974 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006975 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006976 break;
6977 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006978 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006979 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006980 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006981#ifdef AMD_EXTENSIONS
6982 if (typeProxy == glslang::EbtFloat16)
6983 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6984#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006985 libCall = spv::GLSLstd450InterpolateAtSample;
6986 break;
6987 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006988#ifdef AMD_EXTENSIONS
6989 if (typeProxy == glslang::EbtFloat16)
6990 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6991#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006992 libCall = spv::GLSLstd450InterpolateAtOffset;
6993 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006994 case glslang::EOpAddCarry:
6995 opCode = spv::OpIAddCarry;
6996 typeId = builder.makeStructResultType(typeId0, typeId0);
6997 consumedOperands = 2;
6998 break;
6999 case glslang::EOpSubBorrow:
7000 opCode = spv::OpISubBorrow;
7001 typeId = builder.makeStructResultType(typeId0, typeId0);
7002 consumedOperands = 2;
7003 break;
7004 case glslang::EOpUMulExtended:
7005 opCode = spv::OpUMulExtended;
7006 typeId = builder.makeStructResultType(typeId0, typeId0);
7007 consumedOperands = 2;
7008 break;
7009 case glslang::EOpIMulExtended:
7010 opCode = spv::OpSMulExtended;
7011 typeId = builder.makeStructResultType(typeId0, typeId0);
7012 consumedOperands = 2;
7013 break;
7014 case glslang::EOpBitfieldExtract:
7015 if (isUnsigned)
7016 opCode = spv::OpBitFieldUExtract;
7017 else
7018 opCode = spv::OpBitFieldSExtract;
7019 break;
7020 case glslang::EOpBitfieldInsert:
7021 opCode = spv::OpBitFieldInsert;
7022 break;
7023
7024 case glslang::EOpFma:
7025 libCall = spv::GLSLstd450Fma;
7026 break;
7027 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007028 {
7029 libCall = spv::GLSLstd450FrexpStruct;
7030 assert(builder.isPointerType(typeId1));
7031 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007032 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007033#ifdef AMD_EXTENSIONS
7034 if (width == 16)
7035 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7036 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
7037#endif
Rex Xu470026f2017-03-29 17:12:40 +08007038 if (builder.getNumComponents(operands[0]) == 1)
7039 frexpIntType = builder.makeIntegerType(width, true);
7040 else
7041 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7042 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7043 consumedOperands = 1;
7044 }
John Kessenich55e7d112015-11-15 21:33:39 -07007045 break;
7046 case glslang::EOpLdexp:
7047 libCall = spv::GLSLstd450Ldexp;
7048 break;
7049
Rex Xu574ab042016-04-14 16:53:07 +08007050 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007051 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007052
John Kessenich66011cb2018-03-06 16:12:04 -07007053 case glslang::EOpSubgroupBroadcast:
7054 case glslang::EOpSubgroupBallotBitExtract:
7055 case glslang::EOpSubgroupShuffle:
7056 case glslang::EOpSubgroupShuffleXor:
7057 case glslang::EOpSubgroupShuffleUp:
7058 case glslang::EOpSubgroupShuffleDown:
7059 case glslang::EOpSubgroupClusteredAdd:
7060 case glslang::EOpSubgroupClusteredMul:
7061 case glslang::EOpSubgroupClusteredMin:
7062 case glslang::EOpSubgroupClusteredMax:
7063 case glslang::EOpSubgroupClusteredAnd:
7064 case glslang::EOpSubgroupClusteredOr:
7065 case glslang::EOpSubgroupClusteredXor:
7066 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007067#ifdef NV_EXTENSIONS
7068 case glslang::EOpSubgroupPartitionedAdd:
7069 case glslang::EOpSubgroupPartitionedMul:
7070 case glslang::EOpSubgroupPartitionedMin:
7071 case glslang::EOpSubgroupPartitionedMax:
7072 case glslang::EOpSubgroupPartitionedAnd:
7073 case glslang::EOpSubgroupPartitionedOr:
7074 case glslang::EOpSubgroupPartitionedXor:
7075 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7076 case glslang::EOpSubgroupPartitionedInclusiveMul:
7077 case glslang::EOpSubgroupPartitionedInclusiveMin:
7078 case glslang::EOpSubgroupPartitionedInclusiveMax:
7079 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7080 case glslang::EOpSubgroupPartitionedInclusiveOr:
7081 case glslang::EOpSubgroupPartitionedInclusiveXor:
7082 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7083 case glslang::EOpSubgroupPartitionedExclusiveMul:
7084 case glslang::EOpSubgroupPartitionedExclusiveMin:
7085 case glslang::EOpSubgroupPartitionedExclusiveMax:
7086 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7087 case glslang::EOpSubgroupPartitionedExclusiveOr:
7088 case glslang::EOpSubgroupPartitionedExclusiveXor:
7089#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007090 return createSubgroupOperation(op, typeId, operands, typeProxy);
7091
Rex Xu9d93a232016-05-05 12:30:44 +08007092#ifdef AMD_EXTENSIONS
7093 case glslang::EOpSwizzleInvocations:
7094 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7095 libCall = spv::SwizzleInvocationsAMD;
7096 break;
7097 case glslang::EOpSwizzleInvocationsMasked:
7098 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7099 libCall = spv::SwizzleInvocationsMaskedAMD;
7100 break;
7101 case glslang::EOpWriteInvocation:
7102 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7103 libCall = spv::WriteInvocationAMD;
7104 break;
7105
7106 case glslang::EOpMin3:
7107 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7108 if (isFloat)
7109 libCall = spv::FMin3AMD;
7110 else {
7111 if (isUnsigned)
7112 libCall = spv::UMin3AMD;
7113 else
7114 libCall = spv::SMin3AMD;
7115 }
7116 break;
7117 case glslang::EOpMax3:
7118 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7119 if (isFloat)
7120 libCall = spv::FMax3AMD;
7121 else {
7122 if (isUnsigned)
7123 libCall = spv::UMax3AMD;
7124 else
7125 libCall = spv::SMax3AMD;
7126 }
7127 break;
7128 case glslang::EOpMid3:
7129 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7130 if (isFloat)
7131 libCall = spv::FMid3AMD;
7132 else {
7133 if (isUnsigned)
7134 libCall = spv::UMid3AMD;
7135 else
7136 libCall = spv::SMid3AMD;
7137 }
7138 break;
7139
7140 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007141 if (typeProxy == glslang::EbtFloat16)
7142 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007143 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7144 libCall = spv::InterpolateAtVertexAMD;
7145 break;
7146#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007147 case glslang::EOpBarrier:
7148 {
7149 // This is for the extended controlBarrier function, with four operands.
7150 // The unextended barrier() goes through createNoArgOperation.
7151 assert(operands.size() == 4);
7152 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7153 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7154 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7155 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7156 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7157 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7158 }
7159 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7160 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7161 }
7162 return 0;
7163 }
7164 break;
7165 case glslang::EOpMemoryBarrier:
7166 {
7167 // This is for the extended memoryBarrier function, with three operands.
7168 // The unextended memoryBarrier() goes through createNoArgOperation.
7169 assert(operands.size() == 3);
7170 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7171 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7172 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7173 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7174 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7175 }
7176 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7177 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7178 }
7179 return 0;
7180 }
7181 break;
Chao Chen3c366992018-09-19 11:41:59 -07007182
7183#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007184 case glslang::EOpReportIntersectionNV:
7185 {
7186 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007187 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007188 }
7189 break;
7190 case glslang::EOpTraceNV:
7191 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007192 builder.createNoResultOp(spv::OpTraceNV, operands);
7193 return 0;
7194 }
7195 break;
7196 case glslang::EOpExecuteCallableNV:
7197 {
7198 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007199 return 0;
7200 }
7201 break;
Chao Chen3c366992018-09-19 11:41:59 -07007202 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7203 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7204 return 0;
7205#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007206 case glslang::EOpCooperativeMatrixMulAdd:
7207 opCode = spv::OpCooperativeMatrixMulAddNV;
7208 break;
7209
John Kessenich140f3df2015-06-26 16:58:36 -06007210 default:
7211 return 0;
7212 }
7213
7214 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007215 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007216 // Use an extended instruction from the standard library.
7217 // Construct the call arguments, without modifying the original operands vector.
7218 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7219 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007220 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007221 } else if (opCode == spv::OpDot && !isFloat) {
7222 // int dot(int, int)
7223 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7224 const int componentCount = builder.getNumComponents(operands[0]);
7225 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7226 builder.setPrecision(mulOp, precision);
7227 id = builder.createCompositeExtract(mulOp, typeId, 0);
7228 for (int i = 1; i < componentCount; ++i) {
7229 builder.setPrecision(id, precision);
7230 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7231 }
John Kessenich2359bd02015-12-06 19:29:11 -07007232 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007233 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007234 case 0:
7235 // should all be handled by visitAggregate and createNoArgOperation
7236 assert(0);
7237 return 0;
7238 case 1:
7239 // should all be handled by createUnaryOperation
7240 assert(0);
7241 return 0;
7242 case 2:
7243 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7244 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007245 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007246 // anything 3 or over doesn't have l-value operands, so all should be consumed
7247 assert(consumedOperands == operands.size());
7248 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007249 break;
7250 }
7251 }
7252
John Kessenich55e7d112015-11-15 21:33:39 -07007253 // Decode the return types that were structures
7254 switch (op) {
7255 case glslang::EOpAddCarry:
7256 case glslang::EOpSubBorrow:
7257 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7258 id = builder.createCompositeExtract(id, typeId0, 0);
7259 break;
7260 case glslang::EOpUMulExtended:
7261 case glslang::EOpIMulExtended:
7262 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7263 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7264 break;
7265 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007266 {
7267 assert(operands.size() == 2);
7268 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7269 // "exp" is floating-point type (from HLSL intrinsic)
7270 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7271 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7272 builder.createStore(member1, operands[1]);
7273 } else
7274 // "exp" is integer type (from GLSL built-in function)
7275 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7276 id = builder.createCompositeExtract(id, typeId0, 0);
7277 }
John Kessenich55e7d112015-11-15 21:33:39 -07007278 break;
7279 default:
7280 break;
7281 }
7282
John Kessenich32cfd492016-02-02 12:37:46 -07007283 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007284}
7285
Rex Xu9d93a232016-05-05 12:30:44 +08007286// Intrinsics with no arguments (or no return value, and no precision).
7287spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007288{
Jeff Bolz36831c92018-09-05 10:11:41 -05007289 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7290 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007291
7292 switch (op) {
7293 case glslang::EOpEmitVertex:
7294 builder.createNoResultOp(spv::OpEmitVertex);
7295 return 0;
7296 case glslang::EOpEndPrimitive:
7297 builder.createNoResultOp(spv::OpEndPrimitive);
7298 return 0;
7299 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007300 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007301 if (glslangIntermediate->usingVulkanMemoryModel()) {
7302 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7303 spv::MemorySemanticsOutputMemoryKHRMask |
7304 spv::MemorySemanticsAcquireReleaseMask);
7305 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7306 } else {
7307 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7308 }
John Kessenich82979362017-12-11 04:02:24 -07007309 } else {
7310 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7311 spv::MemorySemanticsWorkgroupMemoryMask |
7312 spv::MemorySemanticsAcquireReleaseMask);
7313 }
John Kessenich140f3df2015-06-26 16:58:36 -06007314 return 0;
7315 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007316 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7317 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007318 return 0;
7319 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007320 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7321 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007322 return 0;
7323 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007324 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7325 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007326 return 0;
7327 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007328 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7329 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007330 return 0;
7331 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007332 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7333 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007334 return 0;
7335 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007336 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7337 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007338 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007339 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007340 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007341 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007342 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007343 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007344 case glslang::EOpDeviceMemoryBarrier:
7345 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7346 spv::MemorySemanticsImageMemoryMask |
7347 spv::MemorySemanticsAcquireReleaseMask);
7348 return 0;
7349 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7350 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7351 spv::MemorySemanticsImageMemoryMask |
7352 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007353 return 0;
7354 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007355 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7356 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007357 return 0;
7358 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007359 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7360 spv::MemorySemanticsWorkgroupMemoryMask |
7361 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007362 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007363 case glslang::EOpSubgroupBarrier:
7364 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7365 spv::MemorySemanticsAcquireReleaseMask);
7366 return spv::NoResult;
7367 case glslang::EOpSubgroupMemoryBarrier:
7368 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7369 spv::MemorySemanticsAcquireReleaseMask);
7370 return spv::NoResult;
7371 case glslang::EOpSubgroupMemoryBarrierBuffer:
7372 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7373 spv::MemorySemanticsAcquireReleaseMask);
7374 return spv::NoResult;
7375 case glslang::EOpSubgroupMemoryBarrierImage:
7376 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7377 spv::MemorySemanticsAcquireReleaseMask);
7378 return spv::NoResult;
7379 case glslang::EOpSubgroupMemoryBarrierShared:
7380 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7381 spv::MemorySemanticsAcquireReleaseMask);
7382 return spv::NoResult;
7383 case glslang::EOpSubgroupElect: {
7384 std::vector<spv::Id> operands;
7385 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7386 }
Rex Xu9d93a232016-05-05 12:30:44 +08007387#ifdef AMD_EXTENSIONS
7388 case glslang::EOpTime:
7389 {
7390 std::vector<spv::Id> args; // Dummy arguments
7391 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7392 return builder.setPrecision(id, precision);
7393 }
7394#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007395#ifdef NV_EXTENSIONS
7396 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007397 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007398 return 0;
7399 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007400 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007401 return 0;
7402#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007403 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007404 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007405 return 0;
7406 }
7407}
7408
7409spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7410{
John Kessenich2f273362015-07-18 22:34:27 -06007411 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007412 spv::Id id;
7413 if (symbolValues.end() != iter) {
7414 id = iter->second;
7415 return id;
7416 }
7417
7418 // it was not found, create it
7419 id = createSpvVariable(symbol);
7420 symbolValues[symbol->getId()] = id;
7421
Rex Xuc884b4a2016-06-29 15:03:44 +08007422 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007423 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7424 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7425 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007426#ifdef NV_EXTENSIONS
7427 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7428#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007429 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007430 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007431 if (symbol->getQualifier().hasIndex())
7432 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7433 if (symbol->getQualifier().hasComponent())
7434 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007435 // atomic counters use this:
7436 if (symbol->getQualifier().hasOffset())
7437 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007438 }
7439
scygan2c864272016-05-18 18:09:17 +02007440 if (symbol->getQualifier().hasLocation())
7441 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007442 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007443 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007444 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007445 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007446 }
John Kessenich140f3df2015-06-26 16:58:36 -06007447 if (symbol->getQualifier().hasSet())
7448 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007449 else if (IsDescriptorResource(symbol->getType())) {
7450 // default to 0
7451 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7452 }
John Kessenich140f3df2015-06-26 16:58:36 -06007453 if (symbol->getQualifier().hasBinding())
7454 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007455 else if (IsDescriptorResource(symbol->getType())) {
7456 // default to 0
7457 builder.addDecoration(id, spv::DecorationBinding, 0);
7458 }
John Kessenich6c292d32016-02-15 20:58:50 -07007459 if (symbol->getQualifier().hasAttachment())
7460 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007461 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007462 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007463 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007464 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007465 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7466 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7467 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7468 }
7469 if (symbol->getQualifier().hasXfbOffset())
7470 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007471 }
7472
Rex Xu1da878f2016-02-21 20:59:01 +08007473 if (symbol->getType().isImage()) {
7474 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007475 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007476 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007477 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007478 }
7479
John Kessenich140f3df2015-06-26 16:58:36 -06007480 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007481 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007482 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007483 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007484
John Kessenich5611c6d2018-04-05 11:25:02 -06007485 // nonuniform
7486 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7487
John Kessenichecba76f2017-01-06 00:34:48 -07007488#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007489 if (builtIn == spv::BuiltInSampleMask) {
7490 spv::Decoration decoration;
7491 // GL_NV_sample_mask_override_coverage extension
7492 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007493 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007494 else
7495 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007496 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007497 if (decoration != spv::DecorationMax) {
7498 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7499 }
7500 }
chaoc771d89f2017-01-13 01:10:53 -08007501 else if (builtIn == spv::BuiltInLayer) {
7502 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007503 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007504 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007505 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7506 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7507 }
John Kessenichb41bff62017-08-11 13:07:17 -06007508 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007509 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7510 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007511 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7512 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7513 }
7514 }
7515
chaoc6e5acae2016-12-20 13:28:52 -08007516 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007517 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007518 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007519 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7520 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007521 if (symbol->getQualifier().pervertexNV) {
7522 builder.addDecoration(id, spv::DecorationPerVertexNV);
7523 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7524 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7525 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007526#endif
7527
John Kessenich5d610ee2018-03-07 18:05:55 -07007528 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7529 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7530 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7531 symbol->getType().getQualifier().semanticName);
7532 }
7533
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007534 if (symbol->getBasicType() == glslang::EbtReference) {
7535 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7536 }
7537
John Kessenich140f3df2015-06-26 16:58:36 -06007538 return id;
7539}
7540
Chao Chen3c366992018-09-19 11:41:59 -07007541#ifdef NV_EXTENSIONS
7542// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7543void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7544{
7545 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007546 if (qualifier.perPrimitiveNV) {
7547 // Need to add capability/extension for fragment shader.
7548 // Mesh shader already adds this by default.
7549 if (glslangIntermediate->getStage() == EShLangFragment) {
7550 builder.addCapability(spv::CapabilityMeshShadingNV);
7551 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7552 }
Chao Chen3c366992018-09-19 11:41:59 -07007553 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007554 }
Chao Chen3c366992018-09-19 11:41:59 -07007555 if (qualifier.perViewNV)
7556 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7557 if (qualifier.perTaskNV)
7558 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7559 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007560 if (qualifier.perPrimitiveNV) {
7561 // Need to add capability/extension for fragment shader.
7562 // Mesh shader already adds this by default.
7563 if (glslangIntermediate->getStage() == EShLangFragment) {
7564 builder.addCapability(spv::CapabilityMeshShadingNV);
7565 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7566 }
Chao Chen3c366992018-09-19 11:41:59 -07007567 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007568 }
Chao Chen3c366992018-09-19 11:41:59 -07007569 if (qualifier.perViewNV)
7570 builder.addDecoration(id, spv::DecorationPerViewNV);
7571 if (qualifier.perTaskNV)
7572 builder.addDecoration(id, spv::DecorationPerTaskNV);
7573 }
7574}
7575#endif
7576
John Kessenich55e7d112015-11-15 21:33:39 -07007577// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007578// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007579//
7580// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7581//
7582// Recursively walk the nodes. The nodes form a tree whose leaves are
7583// regular constants, which themselves are trees that createSpvConstant()
7584// recursively walks. So, this function walks the "top" of the tree:
7585// - emit specialization constant-building instructions for specConstant
7586// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007587spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007588{
John Kessenich7cc0e282016-03-20 00:46:02 -06007589 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007590
qining4f4bb812016-04-03 23:55:17 -04007591 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007592 if (! node.getQualifier().specConstant) {
7593 // hand off to the non-spec-constant path
7594 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7595 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007596 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007597 nextConst, false);
7598 }
7599
7600 // We now know we have a specialization constant to build
7601
John Kessenichd94c0032016-05-30 19:29:40 -06007602 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007603 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7604 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7605 std::vector<spv::Id> dimConstId;
7606 for (int dim = 0; dim < 3; ++dim) {
7607 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7608 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007609 if (specConst) {
7610 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7611 glslangIntermediate->getLocalSizeSpecId(dim));
7612 }
qining4f4bb812016-04-03 23:55:17 -04007613 }
7614 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7615 }
7616
7617 // An AST node labelled as specialization constant should be a symbol node.
7618 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7619 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007620 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007621 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007622 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7623 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7624 // will set the builder into spec constant op instruction generating mode.
7625 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007626 result = accessChainLoad(sub_tree->getType());
7627 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007628 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007629 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007630 } else {
7631 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007632 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007633 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007634 builder.addName(result, sn->getName().c_str());
7635 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007636 }
qining4f4bb812016-04-03 23:55:17 -04007637
7638 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7639 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007640 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007641 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007642}
7643
John Kessenich140f3df2015-06-26 16:58:36 -06007644// Use 'consts' as the flattened glslang source of scalar constants to recursively
7645// build the aggregate SPIR-V constant.
7646//
7647// If there are not enough elements present in 'consts', 0 will be substituted;
7648// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7649//
qining08408382016-03-21 09:51:37 -04007650spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007651{
7652 // vector of constants for SPIR-V
7653 std::vector<spv::Id> spvConsts;
7654
7655 // Type is used for struct and array constants
7656 spv::Id typeId = convertGlslangToSpvType(glslangType);
7657
7658 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007659 glslang::TType elementType(glslangType, 0);
7660 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007661 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007662 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007663 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007664 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007665 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007666 } else if (glslangType.isCoopMat()) {
7667 glslang::TType componentType(glslangType.getBasicType());
7668 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007669 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007670 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7671 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007672 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007673 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007674 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7675 bool zero = nextConst >= consts.size();
7676 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007677 case glslang::EbtInt8:
7678 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7679 break;
7680 case glslang::EbtUint8:
7681 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7682 break;
7683 case glslang::EbtInt16:
7684 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7685 break;
7686 case glslang::EbtUint16:
7687 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7688 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007689 case glslang::EbtInt:
7690 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7691 break;
7692 case glslang::EbtUint:
7693 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7694 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007695 case glslang::EbtInt64:
7696 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7697 break;
7698 case glslang::EbtUint64:
7699 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7700 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007701 case glslang::EbtFloat:
7702 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7703 break;
7704 case glslang::EbtDouble:
7705 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7706 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007707 case glslang::EbtFloat16:
7708 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7709 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007710 case glslang::EbtBool:
7711 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7712 break;
7713 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007714 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007715 break;
7716 }
7717 ++nextConst;
7718 }
7719 } else {
7720 // we have a non-aggregate (scalar) constant
7721 bool zero = nextConst >= consts.size();
7722 spv::Id scalar = 0;
7723 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007724 case glslang::EbtInt8:
7725 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7726 break;
7727 case glslang::EbtUint8:
7728 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7729 break;
7730 case glslang::EbtInt16:
7731 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7732 break;
7733 case glslang::EbtUint16:
7734 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7735 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007736 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007737 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007738 break;
7739 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007740 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007741 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007742 case glslang::EbtInt64:
7743 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7744 break;
7745 case glslang::EbtUint64:
7746 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7747 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007748 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007749 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007750 break;
7751 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007752 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007753 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007754 case glslang::EbtFloat16:
7755 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7756 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007757 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007758 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007759 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007760 case glslang::EbtReference:
7761 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7762 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7763 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007764 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007765 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007766 break;
7767 }
7768 ++nextConst;
7769 return scalar;
7770 }
7771
7772 return builder.makeCompositeConstant(typeId, spvConsts);
7773}
7774
John Kessenich7c1aa102015-10-15 13:29:11 -06007775// Return true if the node is a constant or symbol whose reading has no
7776// non-trivial observable cost or effect.
7777bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7778{
7779 // don't know what this is
7780 if (node == nullptr)
7781 return false;
7782
7783 // a constant is safe
7784 if (node->getAsConstantUnion() != nullptr)
7785 return true;
7786
7787 // not a symbol means non-trivial
7788 if (node->getAsSymbolNode() == nullptr)
7789 return false;
7790
7791 // a symbol, depends on what's being read
7792 switch (node->getType().getQualifier().storage) {
7793 case glslang::EvqTemporary:
7794 case glslang::EvqGlobal:
7795 case glslang::EvqIn:
7796 case glslang::EvqInOut:
7797 case glslang::EvqConst:
7798 case glslang::EvqConstReadOnly:
7799 case glslang::EvqUniform:
7800 return true;
7801 default:
7802 return false;
7803 }
qining25262b32016-05-06 17:25:16 -04007804}
John Kessenich7c1aa102015-10-15 13:29:11 -06007805
7806// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007807// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007808// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007809// Return true if trivial.
7810bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7811{
7812 if (node == nullptr)
7813 return false;
7814
John Kessenich84cc15f2017-05-24 16:44:47 -06007815 // count non scalars as trivial, as well as anything coming from HLSL
7816 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007817 return true;
7818
John Kessenich7c1aa102015-10-15 13:29:11 -06007819 // symbols and constants are trivial
7820 if (isTrivialLeaf(node))
7821 return true;
7822
7823 // otherwise, it needs to be a simple operation or one or two leaf nodes
7824
7825 // not a simple operation
7826 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7827 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7828 if (binaryNode == nullptr && unaryNode == nullptr)
7829 return false;
7830
7831 // not on leaf nodes
7832 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7833 return false;
7834
7835 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7836 return false;
7837 }
7838
7839 switch (node->getAsOperator()->getOp()) {
7840 case glslang::EOpLogicalNot:
7841 case glslang::EOpConvIntToBool:
7842 case glslang::EOpConvUintToBool:
7843 case glslang::EOpConvFloatToBool:
7844 case glslang::EOpConvDoubleToBool:
7845 case glslang::EOpEqual:
7846 case glslang::EOpNotEqual:
7847 case glslang::EOpLessThan:
7848 case glslang::EOpGreaterThan:
7849 case glslang::EOpLessThanEqual:
7850 case glslang::EOpGreaterThanEqual:
7851 case glslang::EOpIndexDirect:
7852 case glslang::EOpIndexDirectStruct:
7853 case glslang::EOpLogicalXor:
7854 case glslang::EOpAny:
7855 case glslang::EOpAll:
7856 return true;
7857 default:
7858 return false;
7859 }
7860}
7861
7862// Emit short-circuiting code, where 'right' is never evaluated unless
7863// the left side is true (for &&) or false (for ||).
7864spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7865{
7866 spv::Id boolTypeId = builder.makeBoolType();
7867
7868 // emit left operand
7869 builder.clearAccessChain();
7870 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007871 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007872
7873 // Operands to accumulate OpPhi operands
7874 std::vector<spv::Id> phiOperands;
7875 // accumulate left operand's phi information
7876 phiOperands.push_back(leftId);
7877 phiOperands.push_back(builder.getBuildPoint()->getId());
7878
7879 // Make the two kinds of operation symmetric with a "!"
7880 // || => emit "if (! left) result = right"
7881 // && => emit "if ( left) result = right"
7882 //
7883 // TODO: this runtime "not" for || could be avoided by adding functionality
7884 // to 'builder' to have an "else" without an "then"
7885 if (op == glslang::EOpLogicalOr)
7886 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7887
7888 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007889 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007890
7891 // emit right operand as the "then" part of the "if"
7892 builder.clearAccessChain();
7893 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007894 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007895
7896 // accumulate left operand's phi information
7897 phiOperands.push_back(rightId);
7898 phiOperands.push_back(builder.getBuildPoint()->getId());
7899
7900 // finish the "if"
7901 ifBuilder.makeEndIf();
7902
7903 // phi together the two results
7904 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7905}
7906
Frank Henigman541f7bb2018-01-16 00:18:26 -05007907#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007908// Return type Id of the imported set of extended instructions corresponds to the name.
7909// Import this set if it has not been imported yet.
7910spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7911{
7912 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7913 return extBuiltinMap[name];
7914 else {
Rex Xu51596642016-09-21 18:56:12 +08007915 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007916 spv::Id extBuiltins = builder.import(name);
7917 extBuiltinMap[name] = extBuiltins;
7918 return extBuiltins;
7919 }
7920}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007921#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007922
John Kessenich140f3df2015-06-26 16:58:36 -06007923}; // end anonymous namespace
7924
7925namespace glslang {
7926
John Kessenich68d78fd2015-07-12 19:28:10 -06007927void GetSpirvVersion(std::string& version)
7928{
John Kessenich9e55f632015-07-15 10:03:39 -06007929 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007930 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007931 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007932 version = buf;
7933}
7934
John Kessenicha372a3e2017-11-02 22:32:14 -06007935// For low-order part of the generator's magic number. Bump up
7936// when there is a change in the style (e.g., if SSA form changes,
7937// or a different instruction sequence to do something gets used).
7938int GetSpirvGeneratorVersion()
7939{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007940 // return 1; // start
7941 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007942 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007943 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007944 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007945 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7946 // versions 4 and 6 each generate OpArrayLength as it has long been done
7947 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007948}
7949
John Kessenich140f3df2015-06-26 16:58:36 -06007950// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007951void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007952{
7953 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007954 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007955 if (out.fail())
7956 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007957 for (int i = 0; i < (int)spirv.size(); ++i) {
7958 unsigned int word = spirv[i];
7959 out.write((const char*)&word, 4);
7960 }
7961 out.close();
7962}
7963
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007964// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007965void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007966{
7967 std::ofstream out;
7968 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007969 if (out.fail())
7970 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007971 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007972 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007973 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007974 if (varName != nullptr) {
7975 out << "\t #pragma once" << std::endl;
7976 out << "const uint32_t " << varName << "[] = {" << std::endl;
7977 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007978 const int WORDS_PER_LINE = 8;
7979 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7980 out << "\t";
7981 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7982 const unsigned int word = spirv[i + j];
7983 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7984 if (i + j + 1 < (int)spirv.size()) {
7985 out << ",";
7986 }
7987 }
7988 out << std::endl;
7989 }
Flavio15017db2017-02-15 14:29:33 -08007990 if (varName != nullptr) {
7991 out << "};";
7992 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007993 out.close();
7994}
7995
John Kessenich140f3df2015-06-26 16:58:36 -06007996//
7997// Set up the glslang traversal
7998//
John Kessenich4e11b612018-08-30 16:56:59 -06007999void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008000{
Lei Zhang17535f72016-05-04 15:55:59 -04008001 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008002 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008003}
8004
John Kessenich4e11b612018-08-30 16:56:59 -06008005void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008006 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008007{
John Kessenich140f3df2015-06-26 16:58:36 -06008008 TIntermNode* root = intermediate.getTreeRoot();
8009
8010 if (root == 0)
8011 return;
8012
John Kessenich4e11b612018-08-30 16:56:59 -06008013 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008014 if (options == nullptr)
8015 options = &defaultOptions;
8016
John Kessenich4e11b612018-08-30 16:56:59 -06008017 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008018
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008019 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008020 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008021 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008022 it.dumpSpv(spirv);
8023
GregFfb03a552018-03-29 11:49:14 -06008024#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008025 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8026 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06008027 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06008028 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06008029
John Kessenich4e11b612018-08-30 16:56:59 -06008030 if (options->validate)
8031 SpirvToolsValidate(intermediate, spirv, logger);
8032
John Kessenich717c80a2018-08-23 15:17:10 -06008033 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008034 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008035
GregFcd1f1692017-09-21 18:40:22 -06008036#endif
8037
John Kessenich4e11b612018-08-30 16:56:59 -06008038 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008039}
8040
8041}; // end namespace glslang