blob: 7eba1b6a250c744081c3dc805d36b2d31c6e8b5f [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
John Kessenichb23d2322018-12-14 10:47:35 -07003// Copyright (C) 2015-2018 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080051#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080052 #include "GLSL.ext.NV.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
qining4c912612016-04-01 10:35:16 -040071namespace {
72class SpecConstantOpModeGuard {
73public:
74 SpecConstantOpModeGuard(spv::Builder* builder)
75 : builder_(builder) {
76 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040077 }
78 ~SpecConstantOpModeGuard() {
79 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
80 : builder_->setToNormalCodeGenMode();
81 }
qining40887662016-04-03 22:20:42 -040082 void turnOnSpecConstantOpMode() {
83 builder_->setToSpecConstCodeGenMode();
84 }
qining4c912612016-04-01 10:35:16 -040085
86private:
87 spv::Builder* builder_;
88 bool previous_flag_;
89};
John Kessenichead86222018-03-28 18:01:20 -060090
91struct OpDecorations {
92 spv::Decoration precision;
93 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -060094 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -060095};
96
97} // namespace
qining4c912612016-04-01 10:35:16 -040098
John Kessenich140f3df2015-06-26 16:58:36 -060099//
100// The main holder of information for translating glslang to SPIR-V.
101//
102// Derives from the AST walking base class.
103//
104class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
105public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700106 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
107 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700108 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600109
110 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
111 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
112 void visitConstantUnion(glslang::TIntermConstantUnion*);
113 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
114 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
115 void visitSymbol(glslang::TIntermSymbol* symbol);
116 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
117 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
118 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
119
John Kessenichfca82622016-11-26 13:23:20 -0700120 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700121 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600122
123protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700124 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
125 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
126
Rex Xu17ff3432016-10-14 17:41:45 +0800127 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800128 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600129 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500130 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
131 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
132 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
133 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100134 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700135 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700136 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
137 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700138 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600139 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600140 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich140f3df2015-06-26 16:58:36 -0600141 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
142 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600143 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
144 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
145 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600146 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600147 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600148 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600149 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600150 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
151 glslang::TLayoutPacking, const glslang::TQualifier&);
152 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
153 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700154 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700155 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800156 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600157 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700158 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700159 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
160 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700161 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
162 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100163 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600164
John Kessenich6fccb3c2016-09-19 16:01:41 -0600165 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600166 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600167 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600168 void makeFunctions(const glslang::TIntermSequence&);
169 void makeGlobalInitializers(const glslang::TIntermSequence&);
170 void visitFunctions(const glslang::TIntermSequence&);
171 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800172 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600173 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
174 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600175 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
176
John Kessenichead86222018-03-28 18:01:20 -0600177 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
178 glslang::TBasicType typeProxy, bool reduceComparison = true);
179 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
180 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
181 glslang::TBasicType typeProxy);
182 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
183 glslang::TBasicType typeProxy);
184 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
185 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600186 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600187 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800188 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800189 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800190 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700191 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600192 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800193 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600194 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700195#ifdef NV_EXTENSIONS
196 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
197#endif
qining08408382016-03-21 09:51:37 -0400198 spv::Id createSpvConstant(const glslang::TIntermTyped&);
199 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600200 bool isTrivialLeaf(const glslang::TIntermTyped* node);
201 bool isTrivial(const glslang::TIntermTyped* node);
202 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500203#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800204 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500205#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700206 void addPre13Extension(const char* ext)
207 {
208 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
209 builder.addExtension(ext);
210 }
John Kessenich140f3df2015-06-26 16:58:36 -0600211
John Kessenich121853f2017-05-31 17:11:16 -0600212 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600213 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600214 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700215 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600216 int sequenceDepth;
217
Lei Zhang17535f72016-05-04 15:55:59 -0400218 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400219
John Kessenich140f3df2015-06-26 16:58:36 -0600220 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
221 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700222 bool inEntryPoint;
223 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700224 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700225 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600226 const glslang::TIntermediate* glslangIntermediate;
227 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800228 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600229
John Kessenich2f273362015-07-18 22:34:27 -0600230 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600231 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600232 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700233 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700234 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
235 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600236 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700237 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600238 // Map pointee types for EbtReference to their forward pointers
239 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich140f3df2015-06-26 16:58:36 -0600240};
241
242//
243// Helper functions for translating glslang representations to SPIR-V enumerants.
244//
245
246// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700247spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600248{
John Kessenich66e2faf2016-03-12 18:34:36 -0700249 switch (source) {
250 case glslang::EShSourceGlsl:
251 switch (profile) {
252 case ENoProfile:
253 case ECoreProfile:
254 case ECompatibilityProfile:
255 return spv::SourceLanguageGLSL;
256 case EEsProfile:
257 return spv::SourceLanguageESSL;
258 default:
259 return spv::SourceLanguageUnknown;
260 }
261 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600262 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600263 default:
264 return spv::SourceLanguageUnknown;
265 }
266}
267
268// Translate glslang language (stage) to SPIR-V execution model.
269spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
270{
271 switch (stage) {
272 case EShLangVertex: return spv::ExecutionModelVertex;
273 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
274 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
275 case EShLangGeometry: return spv::ExecutionModelGeometry;
276 case EShLangFragment: return spv::ExecutionModelFragment;
277 case EShLangCompute: return spv::ExecutionModelGLCompute;
Chao Chen3c366992018-09-19 11:41:59 -0700278#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -0700279 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
280 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
281 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
282 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
283 case EShLangMissNV: return spv::ExecutionModelMissNV;
284 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700285 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
286 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
287#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600288 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700289 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600290 return spv::ExecutionModelFragment;
291 }
292}
293
John Kessenich140f3df2015-06-26 16:58:36 -0600294// Translate glslang sampler type to SPIR-V dimensionality.
295spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
296{
297 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700298 case glslang::Esd1D: return spv::Dim1D;
299 case glslang::Esd2D: return spv::Dim2D;
300 case glslang::Esd3D: return spv::Dim3D;
301 case glslang::EsdCube: return spv::DimCube;
302 case glslang::EsdRect: return spv::DimRect;
303 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700304 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600305 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700306 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600307 return spv::Dim2D;
308 }
309}
310
John Kessenichf6640762016-08-01 19:44:00 -0600311// Translate glslang precision to SPIR-V precision decorations.
312spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600313{
John Kessenichf6640762016-08-01 19:44:00 -0600314 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700315 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600316 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600317 default:
318 return spv::NoPrecision;
319 }
320}
321
John Kessenichf6640762016-08-01 19:44:00 -0600322// Translate glslang type to SPIR-V precision decorations.
323spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
324{
325 return TranslatePrecisionDecoration(type.getQualifier().precision);
326}
327
John Kessenich140f3df2015-06-26 16:58:36 -0600328// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600329spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600330{
331 if (type.getBasicType() == glslang::EbtBlock) {
332 switch (type.getQualifier().storage) {
333 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600334 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600335 case glslang::EvqVaryingIn: return spv::DecorationBlock;
336 case glslang::EvqVaryingOut: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700337#ifdef NV_EXTENSIONS
338 case glslang::EvqPayloadNV: return spv::DecorationBlock;
339 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
340 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700341 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
342 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700343#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600344 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700345 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600346 break;
347 }
348 }
349
John Kessenich4016e382016-07-15 11:53:56 -0600350 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600351}
352
Rex Xu1da878f2016-02-21 20:59:01 +0800353// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500354void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800355{
Jeff Bolz36831c92018-09-05 10:11:41 -0500356 if (!useVulkanMemoryModel) {
357 if (qualifier.coherent)
358 memory.push_back(spv::DecorationCoherent);
359 if (qualifier.volatil) {
360 memory.push_back(spv::DecorationVolatile);
361 memory.push_back(spv::DecorationCoherent);
362 }
John Kessenich14b85d32018-06-04 15:36:03 -0600363 }
Rex Xu1da878f2016-02-21 20:59:01 +0800364 if (qualifier.restrict)
365 memory.push_back(spv::DecorationRestrict);
366 if (qualifier.readonly)
367 memory.push_back(spv::DecorationNonWritable);
368 if (qualifier.writeonly)
369 memory.push_back(spv::DecorationNonReadable);
370}
371
John Kessenich140f3df2015-06-26 16:58:36 -0600372// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700373spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600374{
375 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700376 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600377 case glslang::ElmRowMajor:
378 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700379 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600380 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700381 default:
382 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600383 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600384 }
385 } else {
386 switch (type.getBasicType()) {
387 default:
John Kessenich4016e382016-07-15 11:53:56 -0600388 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600389 break;
390 case glslang::EbtBlock:
391 switch (type.getQualifier().storage) {
392 case glslang::EvqUniform:
393 case glslang::EvqBuffer:
394 switch (type.getQualifier().layoutPacking) {
395 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600396 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
397 default:
John Kessenich4016e382016-07-15 11:53:56 -0600398 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600399 }
400 case glslang::EvqVaryingIn:
401 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700402 if (type.getQualifier().isTaskMemory()) {
403 switch (type.getQualifier().layoutPacking) {
404 case glslang::ElpShared: return spv::DecorationGLSLShared;
405 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
406 default: break;
407 }
408 } else {
409 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
410 }
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
Chao Chenb50c02e2018-09-19 11:42:24 -0700412#ifdef NV_EXTENSIONS
413 case glslang::EvqPayloadNV:
414 case glslang::EvqPayloadInNV:
415 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700416 case glslang::EvqCallableDataNV:
417 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700418 return spv::DecorationMax;
419#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600420 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700421 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600422 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600423 }
424 }
425 }
426}
427
428// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600429// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700430// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800431spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600432{
Rex Xubbceed72016-05-21 09:40:44 +0800433 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700434 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600435 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800436 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700437 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700438 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600439 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800440#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800441 else if (qualifier.explicitInterp) {
442 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800443 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800444 }
Rex Xu9d93a232016-05-05 12:30:44 +0800445#endif
Rex Xubbceed72016-05-21 09:40:44 +0800446 else
John Kessenich4016e382016-07-15 11:53:56 -0600447 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800448}
449
450// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600451// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800452// should be applied.
453spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
454{
455 if (qualifier.patch)
456 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700457 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600458 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700459 else if (qualifier.sample) {
460 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600461 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700462 } else
John Kessenich4016e382016-07-15 11:53:56 -0600463 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600464}
465
John Kessenich92187592016-02-01 13:45:25 -0700466// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700467spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600468{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700469 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600470 return spv::DecorationInvariant;
471 else
John Kessenich4016e382016-07-15 11:53:56 -0600472 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600473}
474
qining9220dbb2016-05-04 17:34:38 -0400475// If glslang type is noContraction, return SPIR-V NoContraction decoration.
476spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
477{
478 if (qualifier.noContraction)
479 return spv::DecorationNoContraction;
480 else
John Kessenich4016e382016-07-15 11:53:56 -0600481 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400482}
483
John Kessenich5611c6d2018-04-05 11:25:02 -0600484// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
485spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
486{
487 if (qualifier.isNonUniform()) {
488 builder.addExtension("SPV_EXT_descriptor_indexing");
489 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
490 return spv::DecorationNonUniformEXT;
491 } else
492 return spv::DecorationMax;
493}
494
Jeff Bolz36831c92018-09-05 10:11:41 -0500495spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
496{
497 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
498 return spv::MemoryAccessMaskNone;
499 }
500 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
501 if (coherentFlags.volatil ||
502 coherentFlags.coherent ||
503 coherentFlags.devicecoherent ||
504 coherentFlags.queuefamilycoherent ||
505 coherentFlags.workgroupcoherent ||
506 coherentFlags.subgroupcoherent) {
507 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
508 spv::MemoryAccessMakePointerVisibleKHRMask;
509 }
510 if (coherentFlags.nonprivate) {
511 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
512 }
513 if (coherentFlags.volatil) {
514 mask = mask | spv::MemoryAccessVolatileMask;
515 }
516 if (mask != spv::MemoryAccessMaskNone) {
517 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
518 }
519 return mask;
520}
521
522spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
523{
524 if (!glslangIntermediate->usingVulkanMemoryModel()) {
525 return spv::ImageOperandsMaskNone;
526 }
527 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
528 if (coherentFlags.volatil ||
529 coherentFlags.coherent ||
530 coherentFlags.devicecoherent ||
531 coherentFlags.queuefamilycoherent ||
532 coherentFlags.workgroupcoherent ||
533 coherentFlags.subgroupcoherent) {
534 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
535 spv::ImageOperandsMakeTexelVisibleKHRMask;
536 }
537 if (coherentFlags.nonprivate) {
538 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
539 }
540 if (coherentFlags.volatil) {
541 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
542 }
543 if (mask != spv::ImageOperandsMaskNone) {
544 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
545 }
546 return mask;
547}
548
549spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
550{
551 spv::Builder::AccessChain::CoherentFlags flags;
552 flags.coherent = type.getQualifier().coherent;
553 flags.devicecoherent = type.getQualifier().devicecoherent;
554 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
555 // shared variables are implicitly workgroupcoherent in GLSL.
556 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
557 type.getQualifier().storage == glslang::EvqShared;
558 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600559 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500560 // *coherent variables are implicitly nonprivate in GLSL
561 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500562 flags.subgroupcoherent ||
563 flags.workgroupcoherent ||
564 flags.queuefamilycoherent ||
565 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600566 flags.coherent ||
567 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500568 flags.isImage = type.getBasicType() == glslang::EbtSampler;
569 return flags;
570}
571
572spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
573{
574 spv::Scope scope;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600575 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500576 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
577 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
578 } else if (coherentFlags.devicecoherent) {
579 scope = spv::ScopeDevice;
580 } else if (coherentFlags.queuefamilycoherent) {
581 scope = spv::ScopeQueueFamilyKHR;
582 } else if (coherentFlags.workgroupcoherent) {
583 scope = spv::ScopeWorkgroup;
584 } else if (coherentFlags.subgroupcoherent) {
585 scope = spv::ScopeSubgroup;
586 } else {
587 scope = spv::ScopeMax;
588 }
589 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
590 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
591 }
592 return scope;
593}
594
David Netoa901ffe2016-06-08 14:11:40 +0100595// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
596// associated capabilities when required. For some built-in variables, a capability
597// is generated only when using the variable in an executable instruction, but not when
598// just declaring a struct member variable with it. This is true for PointSize,
599// ClipDistance, and CullDistance.
600spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600601{
602 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700603 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600604 // Defer adding the capability until the built-in is actually used.
605 if (! memberDeclaration) {
606 switch (glslangIntermediate->getStage()) {
607 case EShLangGeometry:
608 builder.addCapability(spv::CapabilityGeometryPointSize);
609 break;
610 case EShLangTessControl:
611 case EShLangTessEvaluation:
612 builder.addCapability(spv::CapabilityTessellationPointSize);
613 break;
614 default:
615 break;
616 }
John Kessenich92187592016-02-01 13:45:25 -0700617 }
618 return spv::BuiltInPointSize;
619
John Kessenichebb50532016-05-16 19:22:05 -0600620 // These *Distance capabilities logically belong here, but if the member is declared and
621 // then never used, consumers of SPIR-V prefer the capability not be declared.
622 // They are now generated when used, rather than here when declared.
623 // Potentially, the specification should be more clear what the minimum
624 // use needed is to trigger the capability.
625 //
John Kessenich92187592016-02-01 13:45:25 -0700626 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100627 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800628 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700629 return spv::BuiltInClipDistance;
630
631 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100632 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800633 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700634 return spv::BuiltInCullDistance;
635
636 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600637 builder.addCapability(spv::CapabilityMultiViewport);
638 if (glslangIntermediate->getStage() == EShLangVertex ||
639 glslangIntermediate->getStage() == EShLangTessControl ||
640 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800641
John Kessenichba6a3c22017-09-13 13:22:50 -0600642 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
643 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800644 }
John Kessenich92187592016-02-01 13:45:25 -0700645 return spv::BuiltInViewportIndex;
646
John Kessenich5e801132016-02-15 11:09:46 -0700647 case glslang::EbvSampleId:
648 builder.addCapability(spv::CapabilitySampleRateShading);
649 return spv::BuiltInSampleId;
650
651 case glslang::EbvSamplePosition:
652 builder.addCapability(spv::CapabilitySampleRateShading);
653 return spv::BuiltInSamplePosition;
654
655 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700656 return spv::BuiltInSampleMask;
657
John Kessenich78a45572016-07-08 14:05:15 -0600658 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700659#ifdef NV_EXTENSIONS
660 if (glslangIntermediate->getStage() == EShLangMeshNV) {
661 return spv::BuiltInLayer;
662 }
663#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600664 builder.addCapability(spv::CapabilityGeometry);
665 if (glslangIntermediate->getStage() == EShLangVertex ||
666 glslangIntermediate->getStage() == EShLangTessControl ||
667 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800668
John Kessenichba6a3c22017-09-13 13:22:50 -0600669 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
670 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800671 }
John Kessenich78a45572016-07-08 14:05:15 -0600672 return spv::BuiltInLayer;
673
John Kessenich140f3df2015-06-26 16:58:36 -0600674 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600675 case glslang::EbvVertexId: return spv::BuiltInVertexId;
676 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700677 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
678 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800679
John Kessenichda581a22015-10-14 14:10:30 -0600680 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700681 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800682 builder.addCapability(spv::CapabilityDrawParameters);
683 return spv::BuiltInBaseVertex;
684
John Kessenichda581a22015-10-14 14:10:30 -0600685 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700686 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800687 builder.addCapability(spv::CapabilityDrawParameters);
688 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200689
John Kessenichda581a22015-10-14 14:10:30 -0600690 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700691 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800692 builder.addCapability(spv::CapabilityDrawParameters);
693 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200694
695 case glslang::EbvPrimitiveId:
696 if (glslangIntermediate->getStage() == EShLangFragment)
697 builder.addCapability(spv::CapabilityGeometry);
698 return spv::BuiltInPrimitiveId;
699
Rex Xu37cdcee2017-06-29 17:46:34 +0800700 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800701 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
702 builder.addCapability(spv::CapabilityStencilExportEXT);
703 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800704
John Kessenich140f3df2015-06-26 16:58:36 -0600705 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600706 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
707 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
708 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
709 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
710 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
711 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
712 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600713 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
714 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
715 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
716 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
717 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
718 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
719 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
720 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800721
Rex Xu574ab042016-04-14 16:53:07 +0800722 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800723 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800724 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
725 return spv::BuiltInSubgroupSize;
726
Rex Xu574ab042016-04-14 16:53:07 +0800727 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800728 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800729 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
730 return spv::BuiltInSubgroupLocalInvocationId;
731
Rex Xu574ab042016-04-14 16:53:07 +0800732 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800733 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
734 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
735 return spv::BuiltInSubgroupEqMaskKHR;
736
Rex Xu574ab042016-04-14 16:53:07 +0800737 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800738 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
739 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
740 return spv::BuiltInSubgroupGeMaskKHR;
741
Rex Xu574ab042016-04-14 16:53:07 +0800742 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800743 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
744 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
745 return spv::BuiltInSubgroupGtMaskKHR;
746
Rex Xu574ab042016-04-14 16:53:07 +0800747 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800748 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
749 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
750 return spv::BuiltInSubgroupLeMaskKHR;
751
Rex Xu574ab042016-04-14 16:53:07 +0800752 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800753 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
754 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
755 return spv::BuiltInSubgroupLtMaskKHR;
756
John Kessenich66011cb2018-03-06 16:12:04 -0700757 case glslang::EbvNumSubgroups:
758 builder.addCapability(spv::CapabilityGroupNonUniform);
759 return spv::BuiltInNumSubgroups;
760
761 case glslang::EbvSubgroupID:
762 builder.addCapability(spv::CapabilityGroupNonUniform);
763 return spv::BuiltInSubgroupId;
764
765 case glslang::EbvSubgroupSize2:
766 builder.addCapability(spv::CapabilityGroupNonUniform);
767 return spv::BuiltInSubgroupSize;
768
769 case glslang::EbvSubgroupInvocation2:
770 builder.addCapability(spv::CapabilityGroupNonUniform);
771 return spv::BuiltInSubgroupLocalInvocationId;
772
773 case glslang::EbvSubgroupEqMask2:
774 builder.addCapability(spv::CapabilityGroupNonUniform);
775 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
776 return spv::BuiltInSubgroupEqMask;
777
778 case glslang::EbvSubgroupGeMask2:
779 builder.addCapability(spv::CapabilityGroupNonUniform);
780 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
781 return spv::BuiltInSubgroupGeMask;
782
783 case glslang::EbvSubgroupGtMask2:
784 builder.addCapability(spv::CapabilityGroupNonUniform);
785 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
786 return spv::BuiltInSubgroupGtMask;
787
788 case glslang::EbvSubgroupLeMask2:
789 builder.addCapability(spv::CapabilityGroupNonUniform);
790 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
791 return spv::BuiltInSubgroupLeMask;
792
793 case glslang::EbvSubgroupLtMask2:
794 builder.addCapability(spv::CapabilityGroupNonUniform);
795 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
796 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800797#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800798 case glslang::EbvBaryCoordNoPersp:
799 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
800 return spv::BuiltInBaryCoordNoPerspAMD;
801
802 case glslang::EbvBaryCoordNoPerspCentroid:
803 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
804 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
805
806 case glslang::EbvBaryCoordNoPerspSample:
807 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
808 return spv::BuiltInBaryCoordNoPerspSampleAMD;
809
810 case glslang::EbvBaryCoordSmooth:
811 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
812 return spv::BuiltInBaryCoordSmoothAMD;
813
814 case glslang::EbvBaryCoordSmoothCentroid:
815 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
816 return spv::BuiltInBaryCoordSmoothCentroidAMD;
817
818 case glslang::EbvBaryCoordSmoothSample:
819 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
820 return spv::BuiltInBaryCoordSmoothSampleAMD;
821
822 case glslang::EbvBaryCoordPullModel:
823 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
824 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800825#endif
chaoc771d89f2017-01-13 01:10:53 -0800826
John Kessenich6c8aaac2017-02-27 01:20:51 -0700827 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700828 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700829 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700830 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700831
832 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700833 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700834 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700835 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700836
Daniel Koch5154db52018-11-26 10:01:58 -0500837 case glslang::EbvFragSizeEXT:
838 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
839 builder.addCapability(spv::CapabilityFragmentDensityEXT);
840 return spv::BuiltInFragSizeEXT;
841
842 case glslang::EbvFragInvocationCountEXT:
843 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
844 builder.addCapability(spv::CapabilityFragmentDensityEXT);
845 return spv::BuiltInFragInvocationCountEXT;
846
chaoc771d89f2017-01-13 01:10:53 -0800847#ifdef NV_EXTENSIONS
848 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800849 if (!memberDeclaration) {
850 builder.addExtension(spv::E_SPV_NV_viewport_array2);
851 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
852 }
chaoc771d89f2017-01-13 01:10:53 -0800853 return spv::BuiltInViewportMaskNV;
854 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800855 if (!memberDeclaration) {
856 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
857 builder.addCapability(spv::CapabilityShaderStereoViewNV);
858 }
chaoc771d89f2017-01-13 01:10:53 -0800859 return spv::BuiltInSecondaryPositionNV;
860 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800861 if (!memberDeclaration) {
862 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
863 builder.addCapability(spv::CapabilityShaderStereoViewNV);
864 }
chaoc771d89f2017-01-13 01:10:53 -0800865 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800866 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800867 if (!memberDeclaration) {
868 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
869 builder.addCapability(spv::CapabilityPerViewAttributesNV);
870 }
chaocdf3956c2017-02-14 14:52:34 -0800871 return spv::BuiltInPositionPerViewNV;
872 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800873 if (!memberDeclaration) {
874 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
875 builder.addCapability(spv::CapabilityPerViewAttributesNV);
876 }
chaocdf3956c2017-02-14 14:52:34 -0800877 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700878 case glslang::EbvFragFullyCoveredNV:
879 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
880 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
881 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700882 case glslang::EbvFragmentSizeNV:
883 builder.addExtension(spv::E_SPV_NV_shading_rate);
884 builder.addCapability(spv::CapabilityShadingRateNV);
885 return spv::BuiltInFragmentSizeNV;
886 case glslang::EbvInvocationsPerPixelNV:
887 builder.addExtension(spv::E_SPV_NV_shading_rate);
888 builder.addCapability(spv::CapabilityShadingRateNV);
889 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700890
Daniel Koch593a4e02019-05-27 16:46:31 -0400891 // ray tracing
Chao Chenb50c02e2018-09-19 11:42:24 -0700892 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700893 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700894 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700895 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700896 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700897 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700898 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700899 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700900 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700901 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700902 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700903 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700904 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700905 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700906 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700907 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700908 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700909 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700910 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700911 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700912 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700913 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700914 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700915 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700916 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700917 return spv::BuiltInWorldToObjectNV;
918 case glslang::EbvIncomingRayFlagsNV:
919 return spv::BuiltInIncomingRayFlagsNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400920
921 // barycentrics
Chao Chen9eada4b2018-09-19 11:39:56 -0700922 case glslang::EbvBaryCoordNV:
923 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
924 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
925 return spv::BuiltInBaryCoordNV;
926 case glslang::EbvBaryCoordNoPerspNV:
927 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
928 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
929 return spv::BuiltInBaryCoordNoPerspNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400930
931 // mesh shaders
932 case glslang::EbvTaskCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700933 return spv::BuiltInTaskCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400934 case glslang::EbvPrimitiveCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700935 return spv::BuiltInPrimitiveCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400936 case glslang::EbvPrimitiveIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700937 return spv::BuiltInPrimitiveIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400938 case glslang::EbvClipDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700939 return spv::BuiltInClipDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400940 case glslang::EbvCullDistancePerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700941 return spv::BuiltInCullDistancePerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400942 case glslang::EbvLayerPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -0700943 return spv::BuiltInLayerPerViewNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400944 case glslang::EbvMeshViewCountNV:
Chao Chen3c366992018-09-19 11:41:59 -0700945 return spv::BuiltInMeshViewCountNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400946 case glslang::EbvMeshViewIndicesNV:
Chao Chen3c366992018-09-19 11:41:59 -0700947 return spv::BuiltInMeshViewIndicesNV;
Daniel Koch593a4e02019-05-27 16:46:31 -0400948#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800949 default:
950 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600951 }
952}
953
Rex Xufc618912015-09-09 16:42:49 +0800954// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700955spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800956{
957 assert(type.getBasicType() == glslang::EbtSampler);
958
John Kessenich5d0fa972016-02-15 11:57:00 -0700959 // Check for capabilities
960 switch (type.getQualifier().layoutFormat) {
961 case glslang::ElfRg32f:
962 case glslang::ElfRg16f:
963 case glslang::ElfR11fG11fB10f:
964 case glslang::ElfR16f:
965 case glslang::ElfRgba16:
966 case glslang::ElfRgb10A2:
967 case glslang::ElfRg16:
968 case glslang::ElfRg8:
969 case glslang::ElfR16:
970 case glslang::ElfR8:
971 case glslang::ElfRgba16Snorm:
972 case glslang::ElfRg16Snorm:
973 case glslang::ElfRg8Snorm:
974 case glslang::ElfR16Snorm:
975 case glslang::ElfR8Snorm:
976
977 case glslang::ElfRg32i:
978 case glslang::ElfRg16i:
979 case glslang::ElfRg8i:
980 case glslang::ElfR16i:
981 case glslang::ElfR8i:
982
983 case glslang::ElfRgb10a2ui:
984 case glslang::ElfRg32ui:
985 case glslang::ElfRg16ui:
986 case glslang::ElfRg8ui:
987 case glslang::ElfR16ui:
988 case glslang::ElfR8ui:
989 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
990 break;
991
992 default:
993 break;
994 }
995
996 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800997 switch (type.getQualifier().layoutFormat) {
998 case glslang::ElfNone: return spv::ImageFormatUnknown;
999 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
1000 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
1001 case glslang::ElfR32f: return spv::ImageFormatR32f;
1002 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
1003 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1004 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1005 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1006 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1007 case glslang::ElfR16f: return spv::ImageFormatR16f;
1008 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1009 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1010 case glslang::ElfRg16: return spv::ImageFormatRg16;
1011 case glslang::ElfRg8: return spv::ImageFormatRg8;
1012 case glslang::ElfR16: return spv::ImageFormatR16;
1013 case glslang::ElfR8: return spv::ImageFormatR8;
1014 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1015 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1016 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1017 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1018 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1019 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1020 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1021 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1022 case glslang::ElfR32i: return spv::ImageFormatR32i;
1023 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1024 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1025 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1026 case glslang::ElfR16i: return spv::ImageFormatR16i;
1027 case glslang::ElfR8i: return spv::ImageFormatR8i;
1028 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1029 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1030 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1031 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1032 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1033 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1034 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1035 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1036 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1037 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001038 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001039 }
1040}
1041
John Kesseniche18fd202018-01-30 11:01:39 -07001042spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001043{
John Kesseniche18fd202018-01-30 11:01:39 -07001044 if (selectionNode.getFlatten())
1045 return spv::SelectionControlFlattenMask;
1046 if (selectionNode.getDontFlatten())
1047 return spv::SelectionControlDontFlattenMask;
1048 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001049}
1050
John Kesseniche18fd202018-01-30 11:01:39 -07001051spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001052{
John Kesseniche18fd202018-01-30 11:01:39 -07001053 if (switchNode.getFlatten())
1054 return spv::SelectionControlFlattenMask;
1055 if (switchNode.getDontFlatten())
1056 return spv::SelectionControlDontFlattenMask;
1057 return spv::SelectionControlMaskNone;
1058}
1059
John Kessenicha2858d92018-01-31 08:11:18 -07001060// return a non-0 dependency if the dependency argument must be set
1061spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001062 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001063{
1064 spv::LoopControlMask control = spv::LoopControlMaskNone;
1065
1066 if (loopNode.getDontUnroll())
1067 control = control | spv::LoopControlDontUnrollMask;
1068 if (loopNode.getUnroll())
1069 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001070 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001071 control = control | spv::LoopControlDependencyInfiniteMask;
1072 else if (loopNode.getLoopDependency() > 0) {
1073 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001074 operands.push_back((unsigned int)loopNode.getLoopDependency());
1075 }
1076 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1077 if (loopNode.getMinIterations() > 0) {
1078 control = control | spv::LoopControlMinIterationsMask;
1079 operands.push_back(loopNode.getMinIterations());
1080 }
1081 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1082 control = control | spv::LoopControlMaxIterationsMask;
1083 operands.push_back(loopNode.getMaxIterations());
1084 }
1085 if (loopNode.getIterationMultiple() > 1) {
1086 control = control | spv::LoopControlIterationMultipleMask;
1087 operands.push_back(loopNode.getIterationMultiple());
1088 }
1089 if (loopNode.getPeelCount() > 0) {
1090 control = control | spv::LoopControlPeelCountMask;
1091 operands.push_back(loopNode.getPeelCount());
1092 }
1093 if (loopNode.getPartialCount() > 0) {
1094 control = control | spv::LoopControlPartialCountMask;
1095 operands.push_back(loopNode.getPartialCount());
1096 }
John Kessenicha2858d92018-01-31 08:11:18 -07001097 }
John Kesseniche18fd202018-01-30 11:01:39 -07001098
1099 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001100}
1101
John Kessenicha5c5fb62017-05-05 05:09:58 -06001102// Translate glslang type to SPIR-V storage class.
1103spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1104{
1105 if (type.getQualifier().isPipeInput())
1106 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001107 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001108 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001109
1110 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1111 type.getQualifier().storage == glslang::EvqUniform) {
1112 if (type.getBasicType() == glslang::EbtAtomicUint)
1113 return spv::StorageClassAtomicCounter;
1114 if (type.containsOpaque())
1115 return spv::StorageClassUniformConstant;
1116 }
1117
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001118#ifdef NV_EXTENSIONS
1119 if (type.getQualifier().isUniformOrBuffer() &&
1120 type.getQualifier().layoutShaderRecordNV) {
1121 return spv::StorageClassShaderRecordBufferNV;
1122 }
1123#endif
1124
John Kessenichbed4e4f2017-09-08 02:38:07 -06001125 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001126 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001127 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001128 }
1129
1130 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001131 if (type.getQualifier().layoutPushConstant)
1132 return spv::StorageClassPushConstant;
1133 if (type.getBasicType() == glslang::EbtBlock)
1134 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001135 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001136 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001137
1138 switch (type.getQualifier().storage) {
1139 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1140 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1141 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1142 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001143#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001144 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1145 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1146 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1147 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1148 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001149#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001150 default:
1151 assert(0);
1152 break;
1153 }
1154
1155 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001156}
1157
John Kessenich5611c6d2018-04-05 11:25:02 -06001158// Add capabilities pertaining to how an array is indexed.
1159void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1160 const glslang::TType& indexType)
1161{
1162 if (indexType.getQualifier().isNonUniform()) {
1163 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001164 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001165 if (baseType.getBasicType() == glslang::EbtSampler) {
1166 if (baseType.getQualifier().hasAttachment())
1167 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1168 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1169 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1170 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1171 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1172 else if (baseType.isImage())
1173 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1174 else if (baseType.isTexture())
1175 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1176 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1177 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1178 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1179 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1180 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1181 }
1182 } else {
1183 // assume a dynamically uniform index
1184 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001185 if (baseType.getQualifier().hasAttachment()) {
1186 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001187 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001188 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1189 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001190 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001191 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1192 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001193 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001194 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001195 }
1196 }
1197}
1198
qining25262b32016-05-06 17:25:16 -04001199// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001200// descriptor set.
1201bool IsDescriptorResource(const glslang::TType& type)
1202{
John Kessenichf7497e22016-03-08 21:36:22 -07001203 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001204 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001205 return type.getQualifier().isUniformOrBuffer() &&
1206#ifdef NV_EXTENSIONS
1207 ! type.getQualifier().layoutShaderRecordNV &&
1208#endif
1209 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001210
1211 // non block...
1212 // basically samplerXXX/subpass/sampler/texture are all included
1213 // if they are the global-scope-class, not the function parameter
1214 // (or local, if they ever exist) class.
1215 if (type.getBasicType() == glslang::EbtSampler)
1216 return type.getQualifier().isUniformOrBuffer();
1217
1218 // None of the above.
1219 return false;
1220}
1221
John Kesseniche0b6cad2015-12-24 10:30:13 -07001222void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1223{
1224 if (child.layoutMatrix == glslang::ElmNone)
1225 child.layoutMatrix = parent.layoutMatrix;
1226
1227 if (parent.invariant)
1228 child.invariant = true;
1229 if (parent.nopersp)
1230 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001231#ifdef AMD_EXTENSIONS
1232 if (parent.explicitInterp)
1233 child.explicitInterp = true;
1234#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001235 if (parent.flat)
1236 child.flat = true;
1237 if (parent.centroid)
1238 child.centroid = true;
1239 if (parent.patch)
1240 child.patch = true;
1241 if (parent.sample)
1242 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001243 if (parent.coherent)
1244 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001245 if (parent.devicecoherent)
1246 child.devicecoherent = true;
1247 if (parent.queuefamilycoherent)
1248 child.queuefamilycoherent = true;
1249 if (parent.workgroupcoherent)
1250 child.workgroupcoherent = true;
1251 if (parent.subgroupcoherent)
1252 child.subgroupcoherent = true;
1253 if (parent.nonprivate)
1254 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001255 if (parent.volatil)
1256 child.volatil = true;
1257 if (parent.restrict)
1258 child.restrict = true;
1259 if (parent.readonly)
1260 child.readonly = true;
1261 if (parent.writeonly)
1262 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001263#ifdef NV_EXTENSIONS
1264 if (parent.perPrimitiveNV)
1265 child.perPrimitiveNV = true;
1266 if (parent.perViewNV)
1267 child.perViewNV = true;
1268 if (parent.perTaskNV)
1269 child.perTaskNV = true;
1270#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001271}
1272
John Kessenichf2b7f332016-09-01 17:05:23 -06001273bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001274{
John Kessenich7b9fa252016-01-21 18:56:57 -07001275 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001276 // - struct members might inherit from a struct declaration
1277 // (note that non-block structs don't explicitly inherit,
1278 // only implicitly, meaning no decoration involved)
1279 // - affect decorations on the struct members
1280 // (note smooth does not, and expecting something like volatile
1281 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001282 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001283 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001284}
1285
John Kessenich140f3df2015-06-26 16:58:36 -06001286//
1287// Implement the TGlslangToSpvTraverser class.
1288//
1289
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001290TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001291 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1292 : TIntermTraverser(true, false, true),
1293 options(options),
1294 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001295 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001296 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001297 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001298 glslangIntermediate(glslangIntermediate)
1299{
1300 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1301
1302 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001303 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1304 glslangIntermediate->getVersion());
1305
John Kessenich121853f2017-05-31 17:11:16 -06001306 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001307 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001308 builder.setSourceFile(glslangIntermediate->getSourceFile());
1309
1310 // Set the source shader's text. If for SPV version 1.0, include
1311 // a preamble in comments stating the OpModuleProcessed instructions.
1312 // Otherwise, emit those as actual instructions.
1313 std::string text;
1314 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1315 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001316 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001317 text.append("// OpModuleProcessed ");
1318 text.append(processes[p]);
1319 text.append("\n");
1320 } else
1321 builder.addModuleProcessed(processes[p]);
1322 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001323 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001324 text.append("#line 1\n");
1325 text.append(glslangIntermediate->getSourceText());
1326 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001327 // Pass name and text for all included files
1328 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1329 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1330 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001331 }
John Kessenich140f3df2015-06-26 16:58:36 -06001332 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001333
1334 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1335 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1336
1337 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1338 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1339 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1340 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1341 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001342 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001343 memoryModel = spv::MemoryModelVulkanKHR;
1344 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001345 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001346 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001347 builder.setMemoryModel(addressingModel, memoryModel);
1348
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001349 if (glslangIntermediate->usingVariablePointers()) {
1350 builder.addCapability(spv::CapabilityVariablePointers);
1351 }
1352
John Kessenicheee9d532016-09-19 18:09:30 -06001353 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1354 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001355
1356 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001357 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1358 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001359 builder.addSourceExtension(it->c_str());
1360
1361 // Add the top-level modes for this shader.
1362
John Kessenich92187592016-02-01 13:45:25 -07001363 if (glslangIntermediate->getXfbMode()) {
1364 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001365 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001366 }
John Kessenich140f3df2015-06-26 16:58:36 -06001367
1368 unsigned int mode;
1369 switch (glslangIntermediate->getStage()) {
1370 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001371 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001372 break;
1373
steve-lunarge7412492017-03-23 11:56:07 -06001374 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001375 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001376 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001377
steve-lunarge7412492017-03-23 11:56:07 -06001378 glslang::TLayoutGeometry primitive;
1379
1380 if (glslangIntermediate->getStage() == EShLangTessControl) {
1381 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1382 primitive = glslangIntermediate->getOutputPrimitive();
1383 } else {
1384 primitive = glslangIntermediate->getInputPrimitive();
1385 }
1386
1387 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001388 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1389 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1390 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001391 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001392 }
John Kessenich4016e382016-07-15 11:53:56 -06001393 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001394 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1395
John Kesseniche6903322015-10-13 16:29:02 -06001396 switch (glslangIntermediate->getVertexSpacing()) {
1397 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1398 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1399 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001400 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001401 }
John Kessenich4016e382016-07-15 11:53:56 -06001402 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001403 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1404
1405 switch (glslangIntermediate->getVertexOrder()) {
1406 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1407 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001408 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001409 }
John Kessenich4016e382016-07-15 11:53:56 -06001410 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001411 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1412
1413 if (glslangIntermediate->getPointMode())
1414 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001415 break;
1416
1417 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001418 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001419 switch (glslangIntermediate->getInputPrimitive()) {
1420 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1421 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1422 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001423 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001424 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001425 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001426 }
John Kessenich4016e382016-07-15 11:53:56 -06001427 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001428 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001429
John Kessenich140f3df2015-06-26 16:58:36 -06001430 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1431
1432 switch (glslangIntermediate->getOutputPrimitive()) {
1433 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1434 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1435 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001436 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001437 }
John Kessenich4016e382016-07-15 11:53:56 -06001438 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001439 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1440 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1441 break;
1442
1443 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001444 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001445 if (glslangIntermediate->getPixelCenterInteger())
1446 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001447
John Kessenich140f3df2015-06-26 16:58:36 -06001448 if (glslangIntermediate->getOriginUpperLeft())
1449 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001450 else
1451 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001452
1453 if (glslangIntermediate->getEarlyFragmentTests())
1454 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1455
chaocc1204522017-06-30 17:14:30 -07001456 if (glslangIntermediate->getPostDepthCoverage()) {
1457 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1458 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1459 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1460 }
1461
John Kesseniche6903322015-10-13 16:29:02 -06001462 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001463 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1464 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001465 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001466 }
John Kessenich4016e382016-07-15 11:53:56 -06001467 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001468 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1469
1470 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1471 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05001472
1473 switch (glslangIntermediate->getInterlockOrdering()) {
1474 case glslang::EioPixelInterlockOrdered: mode = spv::ExecutionModePixelInterlockOrderedEXT; break;
1475 case glslang::EioPixelInterlockUnordered: mode = spv::ExecutionModePixelInterlockUnorderedEXT; break;
1476 case glslang::EioSampleInterlockOrdered: mode = spv::ExecutionModeSampleInterlockOrderedEXT; break;
1477 case glslang::EioSampleInterlockUnordered: mode = spv::ExecutionModeSampleInterlockUnorderedEXT; break;
1478 case glslang::EioShadingRateInterlockOrdered: mode = spv::ExecutionModeShadingRateInterlockOrderedEXT; break;
1479 case glslang::EioShadingRateInterlockUnordered: mode = spv::ExecutionModeShadingRateInterlockUnorderedEXT; break;
1480 default: mode = spv::ExecutionModeMax; break;
1481 }
1482 if (mode != spv::ExecutionModeMax) {
1483 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1484 if (mode == spv::ExecutionModeShadingRateInterlockOrderedEXT ||
1485 mode == spv::ExecutionModeShadingRateInterlockUnorderedEXT) {
1486 builder.addCapability(spv::CapabilityFragmentShaderShadingRateInterlockEXT);
1487 } else if (mode == spv::ExecutionModePixelInterlockOrderedEXT ||
1488 mode == spv::ExecutionModePixelInterlockUnorderedEXT) {
1489 builder.addCapability(spv::CapabilityFragmentShaderPixelInterlockEXT);
1490 } else {
1491 builder.addCapability(spv::CapabilityFragmentShaderSampleInterlockEXT);
1492 }
1493 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
1494 }
1495
John Kessenich140f3df2015-06-26 16:58:36 -06001496 break;
1497
1498 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001499 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001500 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1501 glslangIntermediate->getLocalSize(1),
1502 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001503#ifdef NV_EXTENSIONS
1504 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1505 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1506 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1507 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1508 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1509 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1510 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1511 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1512 }
1513#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001514 break;
1515
Chao Chen3c366992018-09-19 11:41:59 -07001516#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001517 case EShLangRayGenNV:
1518 case EShLangIntersectNV:
1519 case EShLangAnyHitNV:
1520 case EShLangClosestHitNV:
1521 case EShLangMissNV:
1522 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001523 builder.addCapability(spv::CapabilityRayTracingNV);
1524 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001525 break;
Chao Chen3c366992018-09-19 11:41:59 -07001526 case EShLangTaskNV:
1527 case EShLangMeshNV:
1528 builder.addCapability(spv::CapabilityMeshShadingNV);
1529 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1530 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1531 glslangIntermediate->getLocalSize(1),
1532 glslangIntermediate->getLocalSize(2));
1533 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1534 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1535 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1536
1537 switch (glslangIntermediate->getOutputPrimitive()) {
1538 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1539 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1540 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1541 default: mode = spv::ExecutionModeMax; break;
1542 }
1543 if (mode != spv::ExecutionModeMax)
1544 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1545 }
1546 break;
1547#endif
1548
John Kessenich140f3df2015-06-26 16:58:36 -06001549 default:
1550 break;
1551 }
John Kessenich140f3df2015-06-26 16:58:36 -06001552}
1553
John Kessenichfca82622016-11-26 13:23:20 -07001554// Finish creating SPV, after the traversal is complete.
1555void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001556{
John Kessenichf04c51b2018-08-03 15:56:12 -06001557 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001558 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001559 builder.setBuildPoint(shaderEntry->getLastBlock());
1560 builder.leaveFunction();
1561 }
1562
John Kessenich7ba63412015-12-20 17:37:07 -07001563 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001564 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1565 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001566
John Kessenichf04c51b2018-08-03 15:56:12 -06001567 // Add capabilities, extensions, remove unneeded decorations, etc.,
1568 // based on the resulting SPIR-V.
1569 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001570}
1571
John Kessenichfca82622016-11-26 13:23:20 -07001572// Write the SPV into 'out'.
1573void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001574{
John Kessenichfca82622016-11-26 13:23:20 -07001575 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001576}
1577
1578//
1579// Implement the traversal functions.
1580//
1581// Return true from interior nodes to have the external traversal
1582// continue on to children. Return false if children were
1583// already processed.
1584//
1585
1586//
qining25262b32016-05-06 17:25:16 -04001587// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001588// - uniform/input reads
1589// - output writes
1590// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1591// - something simple that degenerates into the last bullet
1592//
1593void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1594{
qining75d1d802016-04-06 14:42:01 -04001595 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1596 if (symbol->getType().getQualifier().isSpecConstant())
1597 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1598
John Kessenich140f3df2015-06-26 16:58:36 -06001599 // getSymbolId() will set up all the IO decorations on the first call.
1600 // Formal function parameters were mapped during makeFunctions().
1601 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001602
1603 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1604 if (builder.isPointer(id)) {
John Kessenich7c7731e2019-01-04 16:47:06 +07001605 // Consider adding to the OpEntryPoint interface list.
1606 // Only looking at structures if they have at least one member.
1607 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1608 spv::StorageClass sc = builder.getStorageClass(id);
1609 // Before SPIR-V 1.4, we only want to include Input and Output.
1610 // Starting with SPIR-V 1.4, we want all globals.
1611 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1612 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001613 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001614 }
John Kessenich5f77d862017-09-19 11:09:59 -06001615 }
John Kessenich7ba63412015-12-20 17:37:07 -07001616 }
1617
1618 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001619 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001620 // Prepare to generate code for the access
1621
1622 // L-value chains will be computed left to right. We're on the symbol now,
1623 // which is the left-most part of the access chain, so now is "clear" time,
1624 // followed by setting the base.
1625 builder.clearAccessChain();
1626
1627 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001628 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001629 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001630 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001631 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001632 // These are also pure R-values.
1633 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001634 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001635 builder.setAccessChainRValue(id);
1636 else
1637 builder.setAccessChainLValue(id);
1638 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001639
1640 // Process linkage-only nodes for any special additional interface work.
1641 if (linkageOnly) {
1642 if (glslangIntermediate->getHlslFunctionality1()) {
1643 // Map implicit counter buffers to their originating buffers, which should have been
1644 // seen by now, given earlier pruning of unused counters, and preservation of order
1645 // of declaration.
1646 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1647 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1648 // Save possible originating buffers for counter buffers, keyed by
1649 // making the potential counter-buffer name.
1650 std::string keyName = symbol->getName().c_str();
1651 keyName = glslangIntermediate->addCounterBufferName(keyName);
1652 counterOriginator[keyName] = symbol;
1653 } else {
1654 // Handle a counter buffer, by finding the saved originating buffer.
1655 std::string keyName = symbol->getName().c_str();
1656 auto it = counterOriginator.find(keyName);
1657 if (it != counterOriginator.end()) {
1658 id = getSymbolId(it->second);
1659 if (id != spv::NoResult) {
1660 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001661 if (counterId != spv::NoResult) {
1662 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001663 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001664 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001665 }
1666 }
1667 }
1668 }
1669 }
1670 }
John Kessenich140f3df2015-06-26 16:58:36 -06001671}
1672
1673bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1674{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001675 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001676
qining40887662016-04-03 22:20:42 -04001677 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1678 if (node->getType().getQualifier().isSpecConstant())
1679 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1680
John Kessenich140f3df2015-06-26 16:58:36 -06001681 // First, handle special cases
1682 switch (node->getOp()) {
1683 case glslang::EOpAssign:
1684 case glslang::EOpAddAssign:
1685 case glslang::EOpSubAssign:
1686 case glslang::EOpMulAssign:
1687 case glslang::EOpVectorTimesMatrixAssign:
1688 case glslang::EOpVectorTimesScalarAssign:
1689 case glslang::EOpMatrixTimesScalarAssign:
1690 case glslang::EOpMatrixTimesMatrixAssign:
1691 case glslang::EOpDivAssign:
1692 case glslang::EOpModAssign:
1693 case glslang::EOpAndAssign:
1694 case glslang::EOpInclusiveOrAssign:
1695 case glslang::EOpExclusiveOrAssign:
1696 case glslang::EOpLeftShiftAssign:
1697 case glslang::EOpRightShiftAssign:
1698 // A bin-op assign "a += b" means the same thing as "a = a + b"
1699 // where a is evaluated before b. For a simple assignment, GLSL
1700 // says to evaluate the left before the right. So, always, left
1701 // node then right node.
1702 {
1703 // get the left l-value, save it away
1704 builder.clearAccessChain();
1705 node->getLeft()->traverse(this);
1706 spv::Builder::AccessChain lValue = builder.getAccessChain();
1707
1708 // evaluate the right
1709 builder.clearAccessChain();
1710 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001711 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001712
1713 if (node->getOp() != glslang::EOpAssign) {
1714 // the left is also an r-value
1715 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001716 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001717
1718 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001719 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001720 TranslateNoContractionDecoration(node->getType().getQualifier()),
1721 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001722 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001723 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1724 node->getType().getBasicType());
1725
1726 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001727 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001728 }
1729
1730 // store the result
1731 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001732 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001733
1734 // assignments are expressions having an rValue after they are evaluated...
1735 builder.clearAccessChain();
1736 builder.setAccessChainRValue(rValue);
1737 }
1738 return false;
1739 case glslang::EOpIndexDirect:
1740 case glslang::EOpIndexDirectStruct:
1741 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001742 // Structure, array, matrix, or vector indirection with statically known index.
John Kessenich140f3df2015-06-26 16:58:36 -06001743 // Get the left part of the access chain.
1744 node->getLeft()->traverse(this);
1745
1746 // Add the next element in the chain
1747
David Netoa901ffe2016-06-08 14:11:40 +01001748 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001749 if (! node->getLeft()->getType().isArray() &&
1750 node->getLeft()->getType().isVector() &&
1751 node->getOp() == glslang::EOpIndexDirect) {
1752 // This is essentially a hard-coded vector swizzle of size 1,
1753 // so short circuit the access-chain stuff with a swizzle.
1754 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001755 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001756 int dummySize;
1757 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1758 TranslateCoherent(node->getLeft()->getType()),
1759 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001760 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001761
1762 // Load through a block reference is performed with a dot operator that
1763 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1764 // do a load and reset the access chain.
1765 if (node->getLeft()->getBasicType() == glslang::EbtReference &&
1766 !node->getLeft()->getType().isArray() &&
1767 node->getOp() == glslang::EOpIndexDirectStruct)
1768 {
1769 spv::Id left = accessChainLoad(node->getLeft()->getType());
1770 builder.clearAccessChain();
1771 builder.setAccessChainLValue(left);
1772 }
1773
David Netoa901ffe2016-06-08 14:11:40 +01001774 int spvIndex = glslangIndex;
1775 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1776 node->getOp() == glslang::EOpIndexDirectStruct)
1777 {
1778 // This may be, e.g., an anonymous block-member selection, which generally need
1779 // index remapping due to hidden members in anonymous blocks.
1780 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1781 assert(remapper.size() > 0);
1782 spvIndex = remapper[glslangIndex];
1783 }
John Kessenichebb50532016-05-16 19:22:05 -06001784
David Netoa901ffe2016-06-08 14:11:40 +01001785 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001786 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001787
1788 // Add capabilities here for accessing PointSize and clip/cull distance.
1789 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001790 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001791 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001792 }
1793 }
1794 return false;
1795 case glslang::EOpIndexIndirect:
1796 {
John Kessenich61a5ce12019-02-07 08:04:12 -07001797 // Array, matrix, or vector indirection with variable index.
1798 // Will use native SPIR-V access-chain for and array indirection;
John Kessenich140f3df2015-06-26 16:58:36 -06001799 // matrices are arrays of vectors, so will also work for a matrix.
1800 // Will use the access chain's 'component' for variable index into a vector.
1801
1802 // This adapter is building access chains left to right.
1803 // Set up the access chain to the left.
1804 node->getLeft()->traverse(this);
1805
1806 // save it so that computing the right side doesn't trash it
1807 spv::Builder::AccessChain partial = builder.getAccessChain();
1808
1809 // compute the next index in the chain
1810 builder.clearAccessChain();
1811 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001812 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001813
John Kessenich5611c6d2018-04-05 11:25:02 -06001814 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1815
John Kessenich140f3df2015-06-26 16:58:36 -06001816 // restore the saved access chain
1817 builder.setAccessChain(partial);
1818
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001819 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1820 int dummySize;
1821 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1822 TranslateCoherent(node->getLeft()->getType()),
1823 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1824 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001825 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001826 }
1827 return false;
1828 case glslang::EOpVectorSwizzle:
1829 {
1830 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001831 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001832 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001833 int dummySize;
1834 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1835 TranslateCoherent(node->getLeft()->getType()),
1836 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001837 }
1838 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001839 case glslang::EOpMatrixSwizzle:
1840 logger->missingFunctionality("matrix swizzle");
1841 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001842 case glslang::EOpLogicalOr:
1843 case glslang::EOpLogicalAnd:
1844 {
1845
1846 // These may require short circuiting, but can sometimes be done as straight
1847 // binary operations. The right operand must be short circuited if it has
1848 // side effects, and should probably be if it is complex.
1849 if (isTrivial(node->getRight()->getAsTyped()))
1850 break; // handle below as a normal binary operation
1851 // otherwise, we need to do dynamic short circuiting on the right operand
1852 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1853 builder.clearAccessChain();
1854 builder.setAccessChainRValue(result);
1855 }
1856 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001857 default:
1858 break;
1859 }
1860
1861 // Assume generic binary op...
1862
John Kessenich32cfd492016-02-02 12:37:46 -07001863 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001864 builder.clearAccessChain();
1865 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001866 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001867
John Kessenich32cfd492016-02-02 12:37:46 -07001868 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001869 builder.clearAccessChain();
1870 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001871 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001872
John Kessenich32cfd492016-02-02 12:37:46 -07001873 // get result
John Kessenichead86222018-03-28 18:01:20 -06001874 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001875 TranslateNoContractionDecoration(node->getType().getQualifier()),
1876 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001877 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001878 convertGlslangToSpvType(node->getType()), left, right,
1879 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001880
John Kessenich50e57562015-12-21 21:21:11 -07001881 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001882 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001883 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001884 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001885 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001886 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001887 return false;
1888 }
John Kessenich140f3df2015-06-26 16:58:36 -06001889}
1890
1891bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1892{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001893 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001894
qining40887662016-04-03 22:20:42 -04001895 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1896 if (node->getType().getQualifier().isSpecConstant())
1897 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1898
John Kessenichfc51d282015-08-19 13:34:18 -06001899 spv::Id result = spv::NoResult;
1900
1901 // try texturing first
1902 result = createImageTextureFunctionCall(node);
1903 if (result != spv::NoResult) {
1904 builder.clearAccessChain();
1905 builder.setAccessChainRValue(result);
1906
1907 return false; // done with this node
1908 }
1909
1910 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001911
1912 if (node->getOp() == glslang::EOpArrayLength) {
1913 // Quite special; won't want to evaluate the operand.
1914
John Kessenich5611c6d2018-04-05 11:25:02 -06001915 // Currently, the front-end does not allow .length() on an array until it is sized,
1916 // except for the last block membeor of an SSBO.
1917 // TODO: If this changes, link-time sized arrays might show up here, and need their
1918 // size extracted.
1919
John Kessenichc9a80832015-09-12 12:17:44 -06001920 // Normal .length() would have been constant folded by the front-end.
1921 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001922 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001923
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001924 spv::Id length;
1925 if (node->getOperand()->getType().isCoopMat()) {
1926 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1927
1928 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
1929 assert(builder.isCooperativeMatrixType(typeId));
1930
1931 length = builder.createCooperativeMatrixLength(typeId);
1932 } else {
1933 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1934 block->traverse(this);
1935 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1936 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
1937 }
John Kessenichc9a80832015-09-12 12:17:44 -06001938
John Kessenich8c869672018-11-28 07:01:37 -07001939 // GLSL semantics say the result of .length() is an int, while SPIR-V says
1940 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
1941 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001942 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
1943 if (builder.isInSpecConstCodeGenMode()) {
1944 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
1945 } else {
1946 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
1947 }
1948 }
John Kessenich8c869672018-11-28 07:01:37 -07001949
John Kessenichc9a80832015-09-12 12:17:44 -06001950 builder.clearAccessChain();
1951 builder.setAccessChainRValue(length);
1952
1953 return false;
1954 }
1955
John Kessenichfc51d282015-08-19 13:34:18 -06001956 // Start by evaluating the operand
1957
John Kessenich8c8505c2016-07-26 12:50:38 -06001958 // Does it need a swizzle inversion? If so, evaluation is inverted;
1959 // operate first on the swizzle base, then apply the swizzle.
1960 spv::Id invertedType = spv::NoType;
1961 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1962 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1963 invertedType = getInvertedSwizzleType(*node->getOperand());
1964
John Kessenich140f3df2015-06-26 16:58:36 -06001965 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001966 if (invertedType != spv::NoType)
1967 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1968 else
1969 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001970
Rex Xufc618912015-09-09 16:42:49 +08001971 spv::Id operand = spv::NoResult;
1972
1973 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1974 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001975 node->getOp() == glslang::EOpAtomicCounter ||
1976 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001977 operand = builder.accessChainGetLValue(); // Special case l-value operands
1978 else
John Kessenich32cfd492016-02-02 12:37:46 -07001979 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001980
John Kessenichead86222018-03-28 18:01:20 -06001981 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001982 TranslateNoContractionDecoration(node->getType().getQualifier()),
1983 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001984
1985 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001986 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001987 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001988
1989 // if not, then possibly an operation
1990 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001991 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001992
1993 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001994 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001995 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001996 builder.addDecoration(result, decorations.nonUniform);
1997 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001998
John Kessenich140f3df2015-06-26 16:58:36 -06001999 builder.clearAccessChain();
2000 builder.setAccessChainRValue(result);
2001
2002 return false; // done with this node
2003 }
2004
2005 // it must be a special case, check...
2006 switch (node->getOp()) {
2007 case glslang::EOpPostIncrement:
2008 case glslang::EOpPostDecrement:
2009 case glslang::EOpPreIncrement:
2010 case glslang::EOpPreDecrement:
2011 {
2012 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08002013 spv::Id one = 0;
2014 if (node->getBasicType() == glslang::EbtFloat)
2015 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08002016 else if (node->getBasicType() == glslang::EbtDouble)
2017 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002018 else if (node->getBasicType() == glslang::EbtFloat16)
2019 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07002020 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
2021 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08002022 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
2023 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07002024 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
2025 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08002026 else
2027 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06002028 glslang::TOperator op;
2029 if (node->getOp() == glslang::EOpPreIncrement ||
2030 node->getOp() == glslang::EOpPostIncrement)
2031 op = glslang::EOpAdd;
2032 else
2033 op = glslang::EOpSub;
2034
John Kessenichead86222018-03-28 18:01:20 -06002035 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002036 convertGlslangToSpvType(node->getType()), operand, one,
2037 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002038 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002039
2040 // The result of operation is always stored, but conditionally the
2041 // consumed result. The consumed result is always an r-value.
2042 builder.accessChainStore(result);
2043 builder.clearAccessChain();
2044 if (node->getOp() == glslang::EOpPreIncrement ||
2045 node->getOp() == glslang::EOpPreDecrement)
2046 builder.setAccessChainRValue(result);
2047 else
2048 builder.setAccessChainRValue(operand);
2049 }
2050
2051 return false;
2052
2053 case glslang::EOpEmitStreamVertex:
2054 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2055 return false;
2056 case glslang::EOpEndStreamPrimitive:
2057 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2058 return false;
2059
2060 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002061 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002062 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002063 }
John Kessenich140f3df2015-06-26 16:58:36 -06002064}
2065
2066bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2067{
qining27e04a02016-04-14 16:40:20 -04002068 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2069 if (node->getType().getQualifier().isSpecConstant())
2070 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2071
John Kessenichfc51d282015-08-19 13:34:18 -06002072 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002073 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2074 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002075
2076 // try texturing
2077 result = createImageTextureFunctionCall(node);
2078 if (result != spv::NoResult) {
2079 builder.clearAccessChain();
2080 builder.setAccessChainRValue(result);
2081
2082 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05002083 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08002084#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05002085 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08002086#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05002087 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002088 // "imageStore" is a special case, which has no result
2089 return false;
2090 }
John Kessenichfc51d282015-08-19 13:34:18 -06002091
John Kessenich140f3df2015-06-26 16:58:36 -06002092 glslang::TOperator binOp = glslang::EOpNull;
2093 bool reduceComparison = true;
2094 bool isMatrix = false;
2095 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002096 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002097
2098 assert(node->getOp());
2099
John Kessenichf6640762016-08-01 19:44:00 -06002100 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002101
2102 switch (node->getOp()) {
2103 case glslang::EOpSequence:
2104 {
2105 if (preVisit)
2106 ++sequenceDepth;
2107 else
2108 --sequenceDepth;
2109
2110 if (sequenceDepth == 1) {
2111 // If this is the parent node of all the functions, we want to see them
2112 // early, so all call points have actual SPIR-V functions to reference.
2113 // In all cases, still let the traverser visit the children for us.
2114 makeFunctions(node->getAsAggregate()->getSequence());
2115
John Kessenich6fccb3c2016-09-19 16:01:41 -06002116 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002117 // anything else gets there, so visit out of order, doing them all now.
2118 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2119
John Kessenich6a60c2f2016-12-08 21:01:59 -07002120 // 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 -06002121 // so do them manually.
2122 visitFunctions(node->getAsAggregate()->getSequence());
2123
2124 return false;
2125 }
2126
2127 return true;
2128 }
2129 case glslang::EOpLinkerObjects:
2130 {
2131 if (visit == glslang::EvPreVisit)
2132 linkageOnly = true;
2133 else
2134 linkageOnly = false;
2135
2136 return true;
2137 }
2138 case glslang::EOpComma:
2139 {
2140 // processing from left to right naturally leaves the right-most
2141 // lying around in the access chain
2142 glslang::TIntermSequence& glslangOperands = node->getSequence();
2143 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2144 glslangOperands[i]->traverse(this);
2145
2146 return false;
2147 }
2148 case glslang::EOpFunction:
2149 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002150 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002151 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002152 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002153 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002154 } else {
2155 handleFunctionEntry(node);
2156 }
2157 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002158 if (inEntryPoint)
2159 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002160 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002161 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002162 }
2163
2164 return true;
2165 case glslang::EOpParameters:
2166 // Parameters will have been consumed by EOpFunction processing, but not
2167 // the body, so we still visited the function node's children, making this
2168 // child redundant.
2169 return false;
2170 case glslang::EOpFunctionCall:
2171 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002172 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002173 if (node->isUserDefined())
2174 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002175 // 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 -07002176 if (result) {
2177 builder.clearAccessChain();
2178 builder.setAccessChainRValue(result);
2179 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002180 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002181
2182 return false;
2183 }
2184 case glslang::EOpConstructMat2x2:
2185 case glslang::EOpConstructMat2x3:
2186 case glslang::EOpConstructMat2x4:
2187 case glslang::EOpConstructMat3x2:
2188 case glslang::EOpConstructMat3x3:
2189 case glslang::EOpConstructMat3x4:
2190 case glslang::EOpConstructMat4x2:
2191 case glslang::EOpConstructMat4x3:
2192 case glslang::EOpConstructMat4x4:
2193 case glslang::EOpConstructDMat2x2:
2194 case glslang::EOpConstructDMat2x3:
2195 case glslang::EOpConstructDMat2x4:
2196 case glslang::EOpConstructDMat3x2:
2197 case glslang::EOpConstructDMat3x3:
2198 case glslang::EOpConstructDMat3x4:
2199 case glslang::EOpConstructDMat4x2:
2200 case glslang::EOpConstructDMat4x3:
2201 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002202 case glslang::EOpConstructIMat2x2:
2203 case glslang::EOpConstructIMat2x3:
2204 case glslang::EOpConstructIMat2x4:
2205 case glslang::EOpConstructIMat3x2:
2206 case glslang::EOpConstructIMat3x3:
2207 case glslang::EOpConstructIMat3x4:
2208 case glslang::EOpConstructIMat4x2:
2209 case glslang::EOpConstructIMat4x3:
2210 case glslang::EOpConstructIMat4x4:
2211 case glslang::EOpConstructUMat2x2:
2212 case glslang::EOpConstructUMat2x3:
2213 case glslang::EOpConstructUMat2x4:
2214 case glslang::EOpConstructUMat3x2:
2215 case glslang::EOpConstructUMat3x3:
2216 case glslang::EOpConstructUMat3x4:
2217 case glslang::EOpConstructUMat4x2:
2218 case glslang::EOpConstructUMat4x3:
2219 case glslang::EOpConstructUMat4x4:
2220 case glslang::EOpConstructBMat2x2:
2221 case glslang::EOpConstructBMat2x3:
2222 case glslang::EOpConstructBMat2x4:
2223 case glslang::EOpConstructBMat3x2:
2224 case glslang::EOpConstructBMat3x3:
2225 case glslang::EOpConstructBMat3x4:
2226 case glslang::EOpConstructBMat4x2:
2227 case glslang::EOpConstructBMat4x3:
2228 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002229 case glslang::EOpConstructF16Mat2x2:
2230 case glslang::EOpConstructF16Mat2x3:
2231 case glslang::EOpConstructF16Mat2x4:
2232 case glslang::EOpConstructF16Mat3x2:
2233 case glslang::EOpConstructF16Mat3x3:
2234 case glslang::EOpConstructF16Mat3x4:
2235 case glslang::EOpConstructF16Mat4x2:
2236 case glslang::EOpConstructF16Mat4x3:
2237 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002238 isMatrix = true;
2239 // fall through
2240 case glslang::EOpConstructFloat:
2241 case glslang::EOpConstructVec2:
2242 case glslang::EOpConstructVec3:
2243 case glslang::EOpConstructVec4:
2244 case glslang::EOpConstructDouble:
2245 case glslang::EOpConstructDVec2:
2246 case glslang::EOpConstructDVec3:
2247 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002248 case glslang::EOpConstructFloat16:
2249 case glslang::EOpConstructF16Vec2:
2250 case glslang::EOpConstructF16Vec3:
2251 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002252 case glslang::EOpConstructBool:
2253 case glslang::EOpConstructBVec2:
2254 case glslang::EOpConstructBVec3:
2255 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002256 case glslang::EOpConstructInt8:
2257 case glslang::EOpConstructI8Vec2:
2258 case glslang::EOpConstructI8Vec3:
2259 case glslang::EOpConstructI8Vec4:
2260 case glslang::EOpConstructUint8:
2261 case glslang::EOpConstructU8Vec2:
2262 case glslang::EOpConstructU8Vec3:
2263 case glslang::EOpConstructU8Vec4:
2264 case glslang::EOpConstructInt16:
2265 case glslang::EOpConstructI16Vec2:
2266 case glslang::EOpConstructI16Vec3:
2267 case glslang::EOpConstructI16Vec4:
2268 case glslang::EOpConstructUint16:
2269 case glslang::EOpConstructU16Vec2:
2270 case glslang::EOpConstructU16Vec3:
2271 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002272 case glslang::EOpConstructInt:
2273 case glslang::EOpConstructIVec2:
2274 case glslang::EOpConstructIVec3:
2275 case glslang::EOpConstructIVec4:
2276 case glslang::EOpConstructUint:
2277 case glslang::EOpConstructUVec2:
2278 case glslang::EOpConstructUVec3:
2279 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002280 case glslang::EOpConstructInt64:
2281 case glslang::EOpConstructI64Vec2:
2282 case glslang::EOpConstructI64Vec3:
2283 case glslang::EOpConstructI64Vec4:
2284 case glslang::EOpConstructUint64:
2285 case glslang::EOpConstructU64Vec2:
2286 case glslang::EOpConstructU64Vec3:
2287 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002288 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002289 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002290 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002291 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002292 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002293 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002294 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002295 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002296 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002297 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002298 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002299 else if (node->getOp() == glslang::EOpConstructStruct ||
2300 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2301 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002302 std::vector<spv::Id> constituents;
2303 for (int c = 0; c < (int)arguments.size(); ++c)
2304 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002305 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002306 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002307 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002308 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002309 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002310
2311 builder.clearAccessChain();
2312 builder.setAccessChainRValue(constructed);
2313
2314 return false;
2315 }
2316
2317 // These six are component-wise compares with component-wise results.
2318 // Forward on to createBinaryOperation(), requesting a vector result.
2319 case glslang::EOpLessThan:
2320 case glslang::EOpGreaterThan:
2321 case glslang::EOpLessThanEqual:
2322 case glslang::EOpGreaterThanEqual:
2323 case glslang::EOpVectorEqual:
2324 case glslang::EOpVectorNotEqual:
2325 {
2326 // Map the operation to a binary
2327 binOp = node->getOp();
2328 reduceComparison = false;
2329 switch (node->getOp()) {
2330 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2331 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2332 default: binOp = node->getOp(); break;
2333 }
2334
2335 break;
2336 }
2337 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002338 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002339 binOp = glslang::EOpMul;
2340 break;
2341 case glslang::EOpOuterProduct:
2342 // two vectors multiplied to make a matrix
2343 binOp = glslang::EOpOuterProduct;
2344 break;
2345 case glslang::EOpDot:
2346 {
qining25262b32016-05-06 17:25:16 -04002347 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002348 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002349 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002350 binOp = glslang::EOpMul;
2351 break;
2352 }
2353 case glslang::EOpMod:
2354 // when an aggregate, this is the floating-point mod built-in function,
2355 // which can be emitted by the one in createBinaryOperation()
2356 binOp = glslang::EOpMod;
2357 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002358 case glslang::EOpEmitVertex:
2359 case glslang::EOpEndPrimitive:
2360 case glslang::EOpBarrier:
2361 case glslang::EOpMemoryBarrier:
2362 case glslang::EOpMemoryBarrierAtomicCounter:
2363 case glslang::EOpMemoryBarrierBuffer:
2364 case glslang::EOpMemoryBarrierImage:
2365 case glslang::EOpMemoryBarrierShared:
2366 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002367 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002368 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002369 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002370 case glslang::EOpWorkgroupMemoryBarrier:
2371 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002372 case glslang::EOpSubgroupBarrier:
2373 case glslang::EOpSubgroupMemoryBarrier:
2374 case glslang::EOpSubgroupMemoryBarrierBuffer:
2375 case glslang::EOpSubgroupMemoryBarrierImage:
2376 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002377 noReturnValue = true;
2378 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2379 break;
2380
Jeff Bolz36831c92018-09-05 10:11:41 -05002381 case glslang::EOpAtomicStore:
2382 noReturnValue = true;
2383 // fallthrough
2384 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002385 case glslang::EOpAtomicAdd:
2386 case glslang::EOpAtomicMin:
2387 case glslang::EOpAtomicMax:
2388 case glslang::EOpAtomicAnd:
2389 case glslang::EOpAtomicOr:
2390 case glslang::EOpAtomicXor:
2391 case glslang::EOpAtomicExchange:
2392 case glslang::EOpAtomicCompSwap:
2393 atomic = true;
2394 break;
2395
John Kessenich0d0c6d32017-07-23 16:08:26 -06002396 case glslang::EOpAtomicCounterAdd:
2397 case glslang::EOpAtomicCounterSubtract:
2398 case glslang::EOpAtomicCounterMin:
2399 case glslang::EOpAtomicCounterMax:
2400 case glslang::EOpAtomicCounterAnd:
2401 case glslang::EOpAtomicCounterOr:
2402 case glslang::EOpAtomicCounterXor:
2403 case glslang::EOpAtomicCounterExchange:
2404 case glslang::EOpAtomicCounterCompSwap:
2405 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2406 builder.addCapability(spv::CapabilityAtomicStorageOps);
2407 atomic = true;
2408 break;
2409
Chao Chen3c366992018-09-19 11:41:59 -07002410#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002411 case glslang::EOpIgnoreIntersectionNV:
2412 case glslang::EOpTerminateRayNV:
2413 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002414 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002415 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2416 noReturnValue = true;
2417 break;
2418#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002419 case glslang::EOpCooperativeMatrixLoad:
2420 case glslang::EOpCooperativeMatrixStore:
2421 noReturnValue = true;
2422 break;
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05002423 case glslang::EOpBeginInvocationInterlock:
2424 case glslang::EOpEndInvocationInterlock:
2425 builder.addExtension(spv::E_SPV_EXT_fragment_shader_interlock);
2426 noReturnValue = true;
2427 break;
Chao Chen3c366992018-09-19 11:41:59 -07002428
John Kessenich140f3df2015-06-26 16:58:36 -06002429 default:
2430 break;
2431 }
2432
2433 //
2434 // See if it maps to a regular operation.
2435 //
John Kessenich140f3df2015-06-26 16:58:36 -06002436 if (binOp != glslang::EOpNull) {
2437 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2438 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2439 assert(left && right);
2440
2441 builder.clearAccessChain();
2442 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002443 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002444
2445 builder.clearAccessChain();
2446 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002447 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002448
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002449 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002450 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002451 TranslateNoContractionDecoration(node->getType().getQualifier()),
2452 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002453 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002454 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002455 left->getType().getBasicType(), reduceComparison);
2456
2457 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002458 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002459 builder.clearAccessChain();
2460 builder.setAccessChainRValue(result);
2461
2462 return false;
2463 }
2464
John Kessenich426394d2015-07-23 10:22:48 -06002465 //
2466 // Create the list of operands.
2467 //
John Kessenich140f3df2015-06-26 16:58:36 -06002468 glslang::TIntermSequence& glslangOperands = node->getSequence();
2469 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002470 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002471 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002472 // special case l-value operands; there are just a few
2473 bool lvalue = false;
2474 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002475 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002476 case glslang::EOpModf:
2477 if (arg == 1)
2478 lvalue = true;
2479 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002480 case glslang::EOpInterpolateAtSample:
2481 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002482#ifdef AMD_EXTENSIONS
2483 case glslang::EOpInterpolateAtVertex:
2484#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002485 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002486 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002487
2488 // Does it need a swizzle inversion? If so, evaluation is inverted;
2489 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002490 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002491 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2492 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2493 }
Rex Xu7a26c172015-12-08 17:12:09 +08002494 break;
Rex Xud4782c12015-09-06 16:30:11 +08002495 case glslang::EOpAtomicAdd:
2496 case glslang::EOpAtomicMin:
2497 case glslang::EOpAtomicMax:
2498 case glslang::EOpAtomicAnd:
2499 case glslang::EOpAtomicOr:
2500 case glslang::EOpAtomicXor:
2501 case glslang::EOpAtomicExchange:
2502 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002503 case glslang::EOpAtomicLoad:
2504 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002505 case glslang::EOpAtomicCounterAdd:
2506 case glslang::EOpAtomicCounterSubtract:
2507 case glslang::EOpAtomicCounterMin:
2508 case glslang::EOpAtomicCounterMax:
2509 case glslang::EOpAtomicCounterAnd:
2510 case glslang::EOpAtomicCounterOr:
2511 case glslang::EOpAtomicCounterXor:
2512 case glslang::EOpAtomicCounterExchange:
2513 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002514 if (arg == 0)
2515 lvalue = true;
2516 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002517 case glslang::EOpAddCarry:
2518 case glslang::EOpSubBorrow:
2519 if (arg == 2)
2520 lvalue = true;
2521 break;
2522 case glslang::EOpUMulExtended:
2523 case glslang::EOpIMulExtended:
2524 if (arg >= 2)
2525 lvalue = true;
2526 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002527 case glslang::EOpCooperativeMatrixLoad:
2528 if (arg == 0 || arg == 1)
2529 lvalue = true;
2530 break;
2531 case glslang::EOpCooperativeMatrixStore:
2532 if (arg == 1)
2533 lvalue = true;
2534 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002535 default:
2536 break;
2537 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002538 builder.clearAccessChain();
2539 if (invertedType != spv::NoType && arg == 0)
2540 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2541 else
2542 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002543
2544 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2545 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2546
2547 if (arg == 1) {
2548 // fold "element" parameter into the access chain
2549 spv::Builder::AccessChain save = builder.getAccessChain();
2550 builder.clearAccessChain();
2551 glslangOperands[2]->traverse(this);
2552
2553 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2554
2555 builder.setAccessChain(save);
2556
2557 // Point to the first element of the array.
2558 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002559 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002560
2561 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2562 unsigned int alignment = builder.getAccessChain().alignment;
2563
2564 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2565 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2566 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2567 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2568 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2569 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2570 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2571 }
2572
2573 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2574
2575 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2576 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2577 }
2578
2579 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2580 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2581 }
2582 } else if (arg == 2) {
2583 continue;
2584 }
2585 }
2586
John Kessenich140f3df2015-06-26 16:58:36 -06002587 if (lvalue)
2588 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002589 else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002590 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002591 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002592 }
John Kessenich140f3df2015-06-26 16:58:36 -06002593 }
John Kessenich426394d2015-07-23 10:22:48 -06002594
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002595 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002596 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2597 std::vector<spv::IdImmediate> idImmOps;
2598
2599 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2600 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2601 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2602 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2603 // get the pointee type
2604 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2605 assert(builder.isCooperativeMatrixType(typeId));
2606 // do the op
2607 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2608 // store the result to the pointer (out param 'm')
2609 builder.createStore(result, operands[0]);
2610 result = 0;
2611 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2612 std::vector<spv::IdImmediate> idImmOps;
2613
2614 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2615 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2616 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2617 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2618 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2619
2620 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2621 result = 0;
2622 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002623 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002624 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002625 } else {
2626 // Pass through to generic operations.
2627 switch (glslangOperands.size()) {
2628 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002629 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002630 break;
2631 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002632 {
2633 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002634 TranslateNoContractionDecoration(node->getType().getQualifier()),
2635 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002636 result = createUnaryOperation(
2637 node->getOp(), decorations,
2638 resultType(), operands.front(),
2639 glslangOperands[0]->getAsTyped()->getBasicType());
2640 }
John Kessenich426394d2015-07-23 10:22:48 -06002641 break;
2642 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002643 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002644 break;
2645 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002646 if (invertedType)
2647 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002648 }
2649
2650 if (noReturnValue)
2651 return false;
2652
2653 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002654 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002655 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002656 } else {
2657 builder.clearAccessChain();
2658 builder.setAccessChainRValue(result);
2659 return false;
2660 }
2661}
2662
John Kessenich433e9ff2017-01-26 20:31:11 -07002663// This path handles both if-then-else and ?:
2664// The if-then-else has a node type of void, while
2665// ?: has either a void or a non-void node type
2666//
2667// Leaving the result, when not void:
2668// GLSL only has r-values as the result of a :?, but
2669// if we have an l-value, that can be more efficient if it will
2670// become the base of a complex r-value expression, because the
2671// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002672bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2673{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002674 // see if OpSelect can handle it
2675 const auto isOpSelectable = [&]() {
2676 if (node->getBasicType() == glslang::EbtVoid)
2677 return false;
2678 // OpSelect can do all other types starting with SPV 1.4
2679 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2680 // pre-1.4, only scalars and vectors can be handled
2681 if ((!node->getType().isScalar() && !node->getType().isVector()))
2682 return false;
2683 }
2684 return true;
2685 };
2686
John Kessenich4bee5312018-02-20 21:29:05 -07002687 // See if it simple and safe, or required, to execute both sides.
2688 // Crucially, side effects must be either semantically required or avoided,
2689 // and there are performance trade-offs.
2690 // Return true if required or a good idea (and safe) to execute both sides,
2691 // false otherwise.
2692 const auto bothSidesPolicy = [&]() -> bool {
2693 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002694 if (node->getTrueBlock() == nullptr ||
2695 node->getFalseBlock() == nullptr)
2696 return false;
2697
John Kessenich4bee5312018-02-20 21:29:05 -07002698 // required? (unless we write additional code to look for side effects
2699 // and make performance trade-offs if none are present)
2700 if (!node->getShortCircuit())
2701 return true;
2702
2703 // if not required to execute both, decide based on performance/practicality...
2704
John Kessenich0c1e71a2019-01-10 18:23:06 +07002705 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002706 return false;
2707
John Kessenich433e9ff2017-01-26 20:31:11 -07002708 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2709 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2710
2711 // return true if a single operand to ? : is okay for OpSelect
2712 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002713 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002714 };
2715
2716 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2717 operandOkay(node->getFalseBlock()->getAsTyped());
2718 };
2719
John Kessenich4bee5312018-02-20 21:29:05 -07002720 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2721 // emit the condition before doing anything with selection
2722 node->getCondition()->traverse(this);
2723 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2724
2725 // Find a way of executing both sides and selecting the right result.
2726 const auto executeBothSides = [&]() -> void {
2727 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002728 node->getTrueBlock()->traverse(this);
2729 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2730 node->getFalseBlock()->traverse(this);
2731 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2732
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002733 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002734
John Kessenich4bee5312018-02-20 21:29:05 -07002735 // done if void
2736 if (node->getBasicType() == glslang::EbtVoid)
2737 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002738
John Kessenich4bee5312018-02-20 21:29:05 -07002739 // emit code to select between trueValue and falseValue
2740
2741 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002742 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002743 // Emit OpSelect for this selection.
2744
2745 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002746 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2747 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002748 condition = builder.smearScalar(spv::NoPrecision, condition,
2749 builder.makeVectorType(builder.makeBoolType(),
2750 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002751 }
John Kessenich4bee5312018-02-20 21:29:05 -07002752
2753 // OpSelect
2754 result = builder.createTriOp(spv::OpSelect,
2755 convertGlslangToSpvType(node->getType()), condition,
2756 trueValue, falseValue);
2757
2758 builder.clearAccessChain();
2759 builder.setAccessChainRValue(result);
2760 } else {
2761 // We need control flow to select the result.
2762 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2763 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2764
2765 // Selection control:
2766 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2767
2768 // make an "if" based on the value created by the condition
2769 spv::Builder::If ifBuilder(condition, control, builder);
2770
2771 // emit the "then" statement
2772 builder.createStore(trueValue, result);
2773 ifBuilder.makeBeginElse();
2774 // emit the "else" statement
2775 builder.createStore(falseValue, result);
2776
2777 // finish off the control flow
2778 ifBuilder.makeEndIf();
2779
2780 builder.clearAccessChain();
2781 builder.setAccessChainLValue(result);
2782 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002783 };
2784
John Kessenich4bee5312018-02-20 21:29:05 -07002785 // Execute the one side needed, as per the condition
2786 const auto executeOneSide = [&]() {
2787 // Always emit control flow.
2788 if (node->getBasicType() != glslang::EbtVoid)
2789 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002790
John Kessenich4bee5312018-02-20 21:29:05 -07002791 // Selection control:
2792 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2793
2794 // make an "if" based on the value created by the condition
2795 spv::Builder::If ifBuilder(condition, control, builder);
2796
2797 // emit the "then" statement
2798 if (node->getTrueBlock() != nullptr) {
2799 node->getTrueBlock()->traverse(this);
2800 if (result != spv::NoResult)
2801 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2802 }
2803
2804 if (node->getFalseBlock() != nullptr) {
2805 ifBuilder.makeBeginElse();
2806 // emit the "else" statement
2807 node->getFalseBlock()->traverse(this);
2808 if (result != spv::NoResult)
2809 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2810 }
2811
2812 // finish off the control flow
2813 ifBuilder.makeEndIf();
2814
2815 if (result != spv::NoResult) {
2816 builder.clearAccessChain();
2817 builder.setAccessChainLValue(result);
2818 }
2819 };
2820
2821 // Try for OpSelect (or a requirement to execute both sides)
2822 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002823 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2824 if (node->getType().getQualifier().isSpecConstant())
2825 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002826 executeBothSides();
2827 } else
2828 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002829
2830 return false;
2831}
2832
2833bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2834{
2835 // emit and get the condition before doing anything with switch
2836 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002837 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002838
Rex Xu57e65922017-07-04 23:23:40 +08002839 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002840 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002841
John Kessenich140f3df2015-06-26 16:58:36 -06002842 // browse the children to sort out code segments
2843 int defaultSegment = -1;
2844 std::vector<TIntermNode*> codeSegments;
2845 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2846 std::vector<int> caseValues;
2847 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2848 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2849 TIntermNode* child = *c;
2850 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002851 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002852 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002853 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002854 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2855 } else
2856 codeSegments.push_back(child);
2857 }
2858
qining25262b32016-05-06 17:25:16 -04002859 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002860 // statements between the last case and the end of the switch statement
2861 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2862 (int)codeSegments.size() == defaultSegment)
2863 codeSegments.push_back(nullptr);
2864
2865 // make the switch statement
2866 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002867 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002868
2869 // emit all the code in the segments
2870 breakForLoop.push(false);
2871 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2872 builder.nextSwitchSegment(segmentBlocks, s);
2873 if (codeSegments[s])
2874 codeSegments[s]->traverse(this);
2875 else
2876 builder.addSwitchBreak();
2877 }
2878 breakForLoop.pop();
2879
2880 builder.endSwitch(segmentBlocks);
2881
2882 return false;
2883}
2884
2885void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2886{
2887 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002888 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002889
2890 builder.clearAccessChain();
2891 builder.setAccessChainRValue(constant);
2892}
2893
2894bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2895{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002896 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002897 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002898
2899 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07002900 std::vector<unsigned int> operands;
2901 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06002902
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002903 // Spec requires back edges to target header blocks, and every header block
2904 // must dominate its merge block. Make a header block first to ensure these
2905 // conditions are met. By definition, it will contain OpLoopMerge, followed
2906 // by a block-ending branch. But we don't want to put any other body/test
2907 // instructions in it, since the body/test may have arbitrary instructions,
2908 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002909 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002910 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07002911 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002912 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002913 spv::Block& test = builder.makeNewBlock();
2914 builder.createBranch(&test);
2915
2916 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002917 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002918 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002919 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2920
2921 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002922 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002923 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002924 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002925 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002926 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002927
2928 builder.setBuildPoint(&blocks.continue_target);
2929 if (node->getTerminal())
2930 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002931 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002932 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002933 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002934 builder.createBranch(&blocks.body);
2935
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002936 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002937 builder.setBuildPoint(&blocks.body);
2938 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002939 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002940 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002941 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002942
2943 builder.setBuildPoint(&blocks.continue_target);
2944 if (node->getTerminal())
2945 node->getTerminal()->traverse(this);
2946 if (node->getTest()) {
2947 node->getTest()->traverse(this);
2948 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002949 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002950 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002951 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002952 // TODO: unless there was a break/return/discard instruction
2953 // somewhere in the body, this is an infinite loop, so we should
2954 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002955 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002956 }
John Kessenich140f3df2015-06-26 16:58:36 -06002957 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002958 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002959 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002960 return false;
2961}
2962
2963bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2964{
2965 if (node->getExpression())
2966 node->getExpression()->traverse(this);
2967
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002968 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002969
John Kessenich140f3df2015-06-26 16:58:36 -06002970 switch (node->getFlowOp()) {
2971 case glslang::EOpKill:
2972 builder.makeDiscard();
2973 break;
2974 case glslang::EOpBreak:
2975 if (breakForLoop.top())
2976 builder.createLoopExit();
2977 else
2978 builder.addSwitchBreak();
2979 break;
2980 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002981 builder.createLoopContinue();
2982 break;
2983 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002984 if (node->getExpression()) {
2985 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2986 spv::Id returnId = accessChainLoad(glslangReturnType);
2987 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2988 builder.clearAccessChain();
2989 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2990 builder.setAccessChainLValue(copyId);
2991 multiTypeStore(glslangReturnType, returnId);
2992 returnId = builder.createLoad(copyId);
2993 }
2994 builder.makeReturn(false, returnId);
2995 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002996 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002997
2998 builder.clearAccessChain();
2999 break;
3000
3001 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003002 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003003 break;
3004 }
3005
3006 return false;
3007}
3008
3009spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
3010{
qining25262b32016-05-06 17:25:16 -04003011 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06003012 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07003013 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06003014 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05003015 spv::Id result = createSpvConstant(*node);
3016 if (result != spv::NoResult)
3017 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06003018 }
3019
3020 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06003021 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06003022 spv::Id spvType = convertGlslangToSpvType(node->getType());
3023
Rex Xucabbb782017-03-24 13:41:14 +08003024 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
3025 node->getType().containsBasicType(glslang::EbtInt16) ||
3026 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08003027 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06003028 switch (storageClass) {
3029 case spv::StorageClassInput:
3030 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07003031 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003032 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06003033 break;
3034 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07003035 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003036 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06003037 break;
3038 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003039 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003040 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3041 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003042 else
3043 builder.addCapability(spv::CapabilityStorageUniform16);
3044 break;
3045 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003046 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003047 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3048 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3049 break;
3050 default:
3051 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003052 }
3053 }
Rex Xuf89ad982017-04-07 23:22:33 +08003054
John Kessenich312dcfb2018-07-03 13:19:51 -06003055 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3056 node->getType().containsBasicType(glslang::EbtUint8);
3057 if (contains8BitType) {
3058 if (storageClass == spv::StorageClassPushConstant) {
3059 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3060 builder.addCapability(spv::CapabilityStoragePushConstant8);
3061 } else if (storageClass == spv::StorageClassUniform) {
3062 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3063 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003064 } else if (storageClass == spv::StorageClassStorageBuffer) {
3065 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3066 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
John Kessenich312dcfb2018-07-03 13:19:51 -06003067 }
3068 }
3069
John Kessenich140f3df2015-06-26 16:58:36 -06003070 const char* name = node->getName().c_str();
3071 if (glslang::IsAnonymous(name))
3072 name = "";
3073
3074 return builder.createVariable(storageClass, spvType, name);
3075}
3076
3077// Return type Id of the sampled type.
3078spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3079{
3080 switch (sampler.type) {
3081 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003082#ifdef AMD_EXTENSIONS
3083 case glslang::EbtFloat16:
3084 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3085 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3086 return builder.makeFloatType(16);
3087#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003088 case glslang::EbtInt: return builder.makeIntType(32);
3089 case glslang::EbtUint: return builder.makeUintType(32);
3090 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003091 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003092 return builder.makeFloatType(32);
3093 }
3094}
3095
John Kessenich8c8505c2016-07-26 12:50:38 -06003096// If node is a swizzle operation, return the type that should be used if
3097// the swizzle base is first consumed by another operation, before the swizzle
3098// is applied.
3099spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3100{
John Kessenichecba76f2017-01-06 00:34:48 -07003101 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003102 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3103 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3104 else
3105 return spv::NoType;
3106}
3107
3108// When inverting a swizzle with a parent op, this function
3109// will apply the swizzle operation to a completed parent operation.
3110spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3111{
3112 std::vector<unsigned> swizzle;
3113 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3114 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3115}
3116
John Kessenich8c8505c2016-07-26 12:50:38 -06003117// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3118void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3119{
3120 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3121 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3122 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3123}
3124
John Kessenich3ac051e2015-12-20 11:29:16 -07003125// Convert from a glslang type to an SPV type, by calling into a
3126// recursive version of this function. This establishes the inherited
3127// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003128spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003129{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003130 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003131}
3132
3133// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003134// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003135// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003136spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003137 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3138 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003139{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003140 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003141
3142 switch (type.getBasicType()) {
3143 case glslang::EbtVoid:
3144 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003145 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003146 break;
3147 case glslang::EbtFloat:
3148 spvType = builder.makeFloatType(32);
3149 break;
3150 case glslang::EbtDouble:
3151 spvType = builder.makeFloatType(64);
3152 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003153 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003154 spvType = builder.makeFloatType(16);
3155 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003156 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003157 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3158 // a 32-bit int where non-0 means true.
3159 if (explicitLayout != glslang::ElpNone)
3160 spvType = builder.makeUintType(32);
3161 else
3162 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003163 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003164 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003165 spvType = builder.makeIntType(8);
3166 break;
3167 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003168 spvType = builder.makeUintType(8);
3169 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003170 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003171 spvType = builder.makeIntType(16);
3172 break;
3173 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003174 spvType = builder.makeUintType(16);
3175 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003176 case glslang::EbtInt:
3177 spvType = builder.makeIntType(32);
3178 break;
3179 case glslang::EbtUint:
3180 spvType = builder.makeUintType(32);
3181 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003182 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003183 spvType = builder.makeIntType(64);
3184 break;
3185 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003186 spvType = builder.makeUintType(64);
3187 break;
John Kessenich426394d2015-07-23 10:22:48 -06003188 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003189 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003190 spvType = builder.makeUintType(32);
3191 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003192#ifdef NV_EXTENSIONS
3193 case glslang::EbtAccStructNV:
3194 spvType = builder.makeAccelerationStructureNVType();
3195 break;
3196#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003197 case glslang::EbtSampler:
3198 {
3199 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003200 if (sampler.sampler) {
3201 // pure sampler
3202 spvType = builder.makeSamplerType();
3203 } else {
3204 // an image is present, make its type
3205 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3206 sampler.image ? 2 : 1, TranslateImageFormat(type));
3207 if (sampler.combined) {
3208 // already has both image and sampler, make the combined type
3209 spvType = builder.makeSampledImageType(spvType);
3210 }
John Kessenich55e7d112015-11-15 21:33:39 -07003211 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003212 }
John Kessenich140f3df2015-06-26 16:58:36 -06003213 break;
3214 case glslang::EbtStruct:
3215 case glslang::EbtBlock:
3216 {
3217 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003218 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003219
3220 // Try to share structs for different layouts, but not yet for other
3221 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003222 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003223 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003224 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003225 break;
3226
3227 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003228 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003229 memberRemapper[glslangMembers].resize(glslangMembers->size());
3230 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003231 }
3232 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003233 case glslang::EbtReference:
3234 {
3235 // Make the forward pointer, then recurse to convert the structure type, then
3236 // patch up the forward pointer with a real pointer type.
3237 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3238 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3239 forwardPointers[type.getReferentType()] = forwardId;
3240 }
3241 spvType = forwardPointers[type.getReferentType()];
3242 if (!forwardReferenceOnly) {
3243 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3244 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3245 forwardPointers[type.getReferentType()],
3246 referentType);
3247 }
3248 }
3249 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003250 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003251 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003252 break;
3253 }
3254
3255 if (type.isMatrix())
3256 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3257 else {
3258 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3259 if (type.getVectorSize() > 1)
3260 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3261 }
3262
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003263 if (type.isCoopMat()) {
3264 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3265 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3266 if (type.getBasicType() == glslang::EbtFloat16)
3267 builder.addCapability(spv::CapabilityFloat16);
3268
3269 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3270 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3271 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3272
3273 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3274 }
3275
John Kessenich140f3df2015-06-26 16:58:36 -06003276 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003277 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3278
John Kessenichc9a80832015-09-12 12:17:44 -06003279 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003280 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003281 // We need to decorate array strides for types needing explicit layout, except blocks.
3282 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003283 // Use a dummy glslang type for querying internal strides of
3284 // arrays of arrays, but using just a one-dimensional array.
3285 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003286 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3287 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003288
3289 // Will compute the higher-order strides here, rather than making a whole
3290 // pile of types and doing repetitive recursion on their contents.
3291 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3292 }
John Kessenichf8842e52016-01-04 19:22:56 -07003293
3294 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003295 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003296 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003297 if (stride > 0)
3298 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003299 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003300 }
3301 } else {
3302 // single-dimensional array, and don't yet have stride
3303
John Kessenichf8842e52016-01-04 19:22:56 -07003304 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003305 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3306 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003307 }
John Kessenich31ed4832015-09-09 17:51:38 -06003308
John Kessenichead86222018-03-28 18:01:20 -06003309 // Do the outer dimension, which might not be known for a runtime-sized array.
3310 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3311 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003312 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003313 else {
3314 if (!lastBufferBlockMember) {
3315 builder.addExtension("SPV_EXT_descriptor_indexing");
3316 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3317 }
John Kessenichead86222018-03-28 18:01:20 -06003318 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003319 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003320 if (stride > 0)
3321 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003322 }
3323
3324 return spvType;
3325}
3326
John Kessenich0e737842017-03-24 18:38:16 -06003327// TODO: this functionality should exist at a higher level, in creating the AST
3328//
3329// Identify interface members that don't have their required extension turned on.
3330//
3331bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3332{
Chao Chen3c366992018-09-19 11:41:59 -07003333#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003334 auto& extensions = glslangIntermediate->getRequestedExtensions();
3335
Rex Xubcf291a2017-03-29 23:01:36 +08003336 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3337 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3338 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003339 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3340 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3341 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003342
3343 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3344 if (member.getFieldName() == "gl_ViewportMask" &&
3345 extensions.find("GL_NV_viewport_array2") == extensions.end())
3346 return true;
3347 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3348 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3349 return true;
3350 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3351 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3352 return true;
3353 }
3354#endif
John Kessenich0e737842017-03-24 18:38:16 -06003355
3356 return false;
3357};
3358
John Kessenich6090df02016-06-30 21:18:02 -06003359// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3360// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3361// Mutually recursive with convertGlslangToSpvType().
3362spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3363 const glslang::TTypeList* glslangMembers,
3364 glslang::TLayoutPacking explicitLayout,
3365 const glslang::TQualifier& qualifier)
3366{
3367 // Create a vector of struct types for SPIR-V to consume
3368 std::vector<spv::Id> spvMembers;
3369 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 -06003370 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003371 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3372 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3373 if (glslangMember.hiddenMember()) {
3374 ++memberDelta;
3375 if (type.getBasicType() == glslang::EbtBlock)
3376 memberRemapper[glslangMembers][i] = -1;
3377 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003378 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003379 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003380 if (filterMember(glslangMember))
3381 continue;
3382 }
John Kessenich6090df02016-06-30 21:18:02 -06003383 // modify just this child's view of the qualifier
3384 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3385 InheritQualifiers(memberQualifier, qualifier);
3386
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003387 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003388 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003389 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003390
3391 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003392 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3393 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003394
3395 // Make forward pointers for any pointer members, and create a list of members to
3396 // convert to spirv types after creating the struct.
3397 if (glslangMember.getBasicType() == glslang::EbtReference) {
3398 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3399 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3400 }
3401 spvMembers.push_back(
3402 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3403 } else {
3404 spvMembers.push_back(
3405 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3406 }
John Kessenich6090df02016-06-30 21:18:02 -06003407 }
3408 }
3409
3410 // Make the SPIR-V type
3411 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003412 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003413 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3414
3415 // Decorate it
3416 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3417
John Kessenichd72f4882019-01-16 14:55:37 +07003418 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003419 auto it = deferredForwardPointers[i];
3420 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3421 }
3422
John Kessenich6090df02016-06-30 21:18:02 -06003423 return spvType;
3424}
3425
3426void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3427 const glslang::TTypeList* glslangMembers,
3428 glslang::TLayoutPacking explicitLayout,
3429 const glslang::TQualifier& qualifier,
3430 spv::Id spvType)
3431{
3432 // Name and decorate the non-hidden members
3433 int offset = -1;
3434 int locationOffset = 0; // for use within the members of this struct
3435 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3436 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3437 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003438 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003439 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003440 if (filterMember(glslangMember))
3441 continue;
3442 }
John Kessenich6090df02016-06-30 21:18:02 -06003443
3444 // modify just this child's view of the qualifier
3445 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3446 InheritQualifiers(memberQualifier, qualifier);
3447
3448 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003449 if (member < 0)
3450 continue;
3451
3452 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3453 builder.addMemberDecoration(spvType, member,
3454 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3455 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3456 // Add interpolation and auxiliary storage decorations only to
3457 // top-level members of Input and Output storage classes
3458 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3459 type.getQualifier().storage == glslang::EvqVaryingOut) {
3460 if (type.getBasicType() == glslang::EbtBlock ||
3461 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3462 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3463 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003464#ifdef NV_EXTENSIONS
3465 addMeshNVDecoration(spvType, member, memberQualifier);
3466#endif
John Kessenich6090df02016-06-30 21:18:02 -06003467 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003468 }
3469 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003470
John Kessenich5d610ee2018-03-07 18:05:55 -07003471 if (type.getBasicType() == glslang::EbtBlock &&
3472 qualifier.storage == glslang::EvqBuffer) {
3473 // Add memory decorations only to top-level members of shader storage block
3474 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003475 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003476 for (unsigned int i = 0; i < memory.size(); ++i)
3477 builder.addMemberDecoration(spvType, member, memory[i]);
3478 }
John Kessenich6090df02016-06-30 21:18:02 -06003479
John Kessenich5d610ee2018-03-07 18:05:55 -07003480 // Location assignment was already completed correctly by the front end,
3481 // just track whether a member needs to be decorated.
3482 // Ignore member locations if the container is an array, as that's
3483 // ill-specified and decisions have been made to not allow this.
3484 if (! type.isArray() && memberQualifier.hasLocation())
3485 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003486
John Kessenich5d610ee2018-03-07 18:05:55 -07003487 if (qualifier.hasLocation()) // track for upcoming inheritance
3488 locationOffset += glslangIntermediate->computeTypeLocationSize(
3489 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003490
John Kessenich5d610ee2018-03-07 18:05:55 -07003491 // component, XFB, others
3492 if (glslangMember.getQualifier().hasComponent())
3493 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3494 glslangMember.getQualifier().layoutComponent);
3495 if (glslangMember.getQualifier().hasXfbOffset())
3496 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3497 glslangMember.getQualifier().layoutXfbOffset);
3498 else if (explicitLayout != glslang::ElpNone) {
3499 // figure out what to do with offset, which is accumulating
3500 int nextOffset;
3501 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3502 if (offset >= 0)
3503 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3504 offset = nextOffset;
3505 }
John Kessenich6090df02016-06-30 21:18:02 -06003506
John Kessenich5d610ee2018-03-07 18:05:55 -07003507 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3508 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3509 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003510
John Kessenich5d610ee2018-03-07 18:05:55 -07003511 // built-in variable decorations
3512 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3513 if (builtIn != spv::BuiltInMax)
3514 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003515
John Kessenich5611c6d2018-04-05 11:25:02 -06003516 // nonuniform
3517 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3518
John Kessenichead86222018-03-28 18:01:20 -06003519 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3520 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3521 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3522 memberQualifier.semanticName);
3523 }
3524
chaoc771d89f2017-01-13 01:10:53 -08003525#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003526 if (builtIn == spv::BuiltInLayer) {
3527 // SPV_NV_viewport_array2 extension
3528 if (glslangMember.getQualifier().layoutViewportRelative){
3529 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3530 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3531 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003532 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003533 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3534 builder.addMemberDecoration(spvType, member,
3535 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3536 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3537 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3538 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003539 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003540 }
3541 if (glslangMember.getQualifier().layoutPassthrough) {
3542 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3543 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3544 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3545 }
chaoc771d89f2017-01-13 01:10:53 -08003546#endif
John Kessenich6090df02016-06-30 21:18:02 -06003547 }
3548
3549 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003550 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3551 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003552}
3553
John Kessenich6c292d32016-02-15 20:58:50 -07003554// Turn the expression forming the array size into an id.
3555// This is not quite trivial, because of specialization constants.
3556// Sometimes, a raw constant is turned into an Id, and sometimes
3557// a specialization constant expression is.
3558spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3559{
3560 // First, see if this is sized with a node, meaning a specialization constant:
3561 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3562 if (specNode != nullptr) {
3563 builder.clearAccessChain();
3564 specNode->traverse(this);
3565 return accessChainLoad(specNode->getAsTyped()->getType());
3566 }
qining25262b32016-05-06 17:25:16 -04003567
John Kessenich6c292d32016-02-15 20:58:50 -07003568 // Otherwise, need a compile-time (front end) size, get it:
3569 int size = arraySizes.getDimSize(dim);
3570 assert(size > 0);
3571 return builder.makeUintConstant(size);
3572}
3573
John Kessenich103bef92016-02-08 21:38:15 -07003574// Wrap the builder's accessChainLoad to:
3575// - localize handling of RelaxedPrecision
3576// - use the SPIR-V inferred type instead of another conversion of the glslang type
3577// (avoids unnecessary work and possible type punning for structures)
3578// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003579spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3580{
John Kessenich103bef92016-02-08 21:38:15 -07003581 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003582
3583 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3584 coherentFlags |= TranslateCoherent(type);
3585
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003586 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003587 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003588
John Kessenich5611c6d2018-04-05 11:25:02 -06003589 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003590 TranslateNonUniformDecoration(type.getQualifier()),
3591 nominalTypeId,
3592 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003593 TranslateMemoryScope(coherentFlags),
3594 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003595
3596 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003597 if (type.getBasicType() == glslang::EbtBool) {
3598 if (builder.isScalarType(nominalTypeId)) {
3599 // Conversion for bool
3600 spv::Id boolType = builder.makeBoolType();
3601 if (nominalTypeId != boolType)
3602 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3603 } else if (builder.isVectorType(nominalTypeId)) {
3604 // Conversion for bvec
3605 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3606 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3607 if (nominalTypeId != bvecType)
3608 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3609 }
3610 }
John Kessenich103bef92016-02-08 21:38:15 -07003611
3612 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003613}
3614
Rex Xu27253232016-02-23 17:51:09 +08003615// Wrap the builder's accessChainStore to:
3616// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003617//
3618// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003619void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3620{
3621 // Need to convert to abstract types when necessary
3622 if (type.getBasicType() == glslang::EbtBool) {
3623 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3624
3625 if (builder.isScalarType(nominalTypeId)) {
3626 // Conversion for bool
3627 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003628 if (nominalTypeId != boolType) {
3629 // keep these outside arguments, for determinant order-of-evaluation
3630 spv::Id one = builder.makeUintConstant(1);
3631 spv::Id zero = builder.makeUintConstant(0);
3632 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3633 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003634 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003635 } else if (builder.isVectorType(nominalTypeId)) {
3636 // Conversion for bvec
3637 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3638 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003639 if (nominalTypeId != bvecType) {
3640 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003641 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3642 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3643 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003644 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003645 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3646 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003647 }
3648 }
3649
Jeff Bolz36831c92018-09-05 10:11:41 -05003650 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3651 coherentFlags |= TranslateCoherent(type);
3652
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003653 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003654 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003655
Jeff Bolz36831c92018-09-05 10:11:41 -05003656 builder.accessChainStore(rvalue,
3657 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003658 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003659}
3660
John Kessenich4bf71552016-09-02 11:20:21 -06003661// For storing when types match at the glslang level, but not might match at the
3662// SPIR-V level.
3663//
3664// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003665// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003666// as in a member-decorated way.
3667//
3668// NOTE: This function can handle any store request; if it's not special it
3669// simplifies to a simple OpStore.
3670//
3671// Implicitly uses the existing builder.accessChain as the storage target.
3672void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3673{
John Kessenichb3e24e42016-09-11 12:33:43 -06003674 // we only do the complex path here if it's an aggregate
3675 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003676 accessChainStore(type, rValue);
3677 return;
3678 }
3679
John Kessenichb3e24e42016-09-11 12:33:43 -06003680 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003681 spv::Id rType = builder.getTypeId(rValue);
3682 spv::Id lValue = builder.accessChainGetLValue();
3683 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3684 if (lType == rType) {
3685 accessChainStore(type, rValue);
3686 return;
3687 }
3688
John Kessenichb3e24e42016-09-11 12:33:43 -06003689 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003690 // where the two types were the same type in GLSL. This requires member
3691 // by member copy, recursively.
3692
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003693 // SPIR-V 1.4 added an instruction to do help do this.
3694 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3695 // However, bool in uniform space is changed to int, so
3696 // OpCopyLogical does not work for that.
3697 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3698 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3699 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3700 if (lBool == rBool) {
3701 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3702 accessChainStore(type, logicalCopy);
3703 return;
3704 }
3705 }
3706
John Kessenichb3e24e42016-09-11 12:33:43 -06003707 // If an array, copy element by element.
3708 if (type.isArray()) {
3709 glslang::TType glslangElementType(type, 0);
3710 spv::Id elementRType = builder.getContainedTypeId(rType);
3711 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3712 // get the source member
3713 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003714
John Kessenichb3e24e42016-09-11 12:33:43 -06003715 // set up the target storage
3716 builder.clearAccessChain();
3717 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003718 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003719
John Kessenichb3e24e42016-09-11 12:33:43 -06003720 // store the member
3721 multiTypeStore(glslangElementType, elementRValue);
3722 }
3723 } else {
3724 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003725
John Kessenichb3e24e42016-09-11 12:33:43 -06003726 // loop over structure members
3727 const glslang::TTypeList& members = *type.getStruct();
3728 for (int m = 0; m < (int)members.size(); ++m) {
3729 const glslang::TType& glslangMemberType = *members[m].type;
3730
3731 // get the source member
3732 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3733 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3734
3735 // set up the target storage
3736 builder.clearAccessChain();
3737 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003738 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003739
3740 // store the member
3741 multiTypeStore(glslangMemberType, memberRValue);
3742 }
John Kessenich4bf71552016-09-02 11:20:21 -06003743 }
3744}
3745
John Kessenichf85e8062015-12-19 13:57:10 -07003746// Decide whether or not this type should be
3747// decorated with offsets and strides, and if so
3748// whether std140 or std430 rules should be applied.
3749glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003750{
John Kessenichf85e8062015-12-19 13:57:10 -07003751 // has to be a block
3752 if (type.getBasicType() != glslang::EbtBlock)
3753 return glslang::ElpNone;
3754
Chao Chen3c366992018-09-19 11:41:59 -07003755 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003756 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003757 type.getQualifier().storage != glslang::EvqBuffer &&
3758 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003759 return glslang::ElpNone;
3760
3761 // return the layout to use
3762 switch (type.getQualifier().layoutPacking) {
3763 case glslang::ElpStd140:
3764 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003765 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003766 return type.getQualifier().layoutPacking;
3767 default:
3768 return glslang::ElpNone;
3769 }
John Kessenich31ed4832015-09-09 17:51:38 -06003770}
3771
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003772// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003773int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003774{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003775 int size;
John Kessenich49987892015-12-29 17:11:44 -07003776 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003777 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003778
3779 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003780}
3781
John Kessenich49987892015-12-29 17:11:44 -07003782// 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 -07003783// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003784int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003785{
John Kessenich49987892015-12-29 17:11:44 -07003786 glslang::TType elementType;
3787 elementType.shallowCopy(matrixType);
3788 elementType.clearArraySizes();
3789
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003790 int size;
John Kessenich49987892015-12-29 17:11:44 -07003791 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003792 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003793
3794 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003795}
3796
John Kessenich5e4b1242015-08-06 22:53:06 -06003797// Given a member type of a struct, realign the current offset for it, and compute
3798// the next (not yet aligned) offset for the next member, which will get aligned
3799// on the next call.
3800// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3801// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3802// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003803void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003804 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003805{
3806 // this will get a positive value when deemed necessary
3807 nextOffset = -1;
3808
John Kessenich5e4b1242015-08-06 22:53:06 -06003809 // override anything in currentOffset with user-set offset
3810 if (memberType.getQualifier().hasOffset())
3811 currentOffset = memberType.getQualifier().layoutOffset;
3812
3813 // It could be that current linker usage in glslang updated all the layoutOffset,
3814 // in which case the following code does not matter. But, that's not quite right
3815 // once cross-compilation unit GLSL validation is done, as the original user
3816 // settings are needed in layoutOffset, and then the following will come into play.
3817
John Kessenichf85e8062015-12-19 13:57:10 -07003818 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003819 if (! memberType.getQualifier().hasOffset())
3820 currentOffset = -1;
3821
3822 return;
3823 }
3824
John Kessenichf85e8062015-12-19 13:57:10 -07003825 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003826 if (currentOffset < 0)
3827 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003828
John Kessenich5e4b1242015-08-06 22:53:06 -06003829 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3830 // but possibly not yet correctly aligned.
3831
3832 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003833 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003834 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003835
3836 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003837 // TODO: make this consistent in early phases of code:
3838 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3839 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3840 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003841 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003842 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003843 int dummySize;
3844 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3845 if (componentAlignment <= 4)
3846 memberAlignment = componentAlignment;
3847 }
3848
3849 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003850 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003851
3852 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003853 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003854 glslang::RoundToPow2(currentOffset, 16);
3855
John Kessenich5e4b1242015-08-06 22:53:06 -06003856 nextOffset = currentOffset + memberSize;
3857}
3858
David Netoa901ffe2016-06-08 14:11:40 +01003859void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003860{
David Netoa901ffe2016-06-08 14:11:40 +01003861 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3862 switch (glslangBuiltIn)
3863 {
3864 case glslang::EbvClipDistance:
3865 case glslang::EbvCullDistance:
3866 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003867#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003868 case glslang::EbvViewportMaskNV:
3869 case glslang::EbvSecondaryPositionNV:
3870 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003871 case glslang::EbvPositionPerViewNV:
3872 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003873 case glslang::EbvTaskCountNV:
3874 case glslang::EbvPrimitiveCountNV:
3875 case glslang::EbvPrimitiveIndicesNV:
3876 case glslang::EbvClipDistancePerViewNV:
3877 case glslang::EbvCullDistancePerViewNV:
3878 case glslang::EbvLayerPerViewNV:
3879 case glslang::EbvMeshViewCountNV:
3880 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003881#endif
David Netoa901ffe2016-06-08 14:11:40 +01003882 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3883 // Alternately, we could just call this for any glslang built-in, since the
3884 // capability already guards against duplicates.
3885 TranslateBuiltInDecoration(glslangBuiltIn, false);
3886 break;
3887 default:
3888 // Capabilities were already generated when the struct was declared.
3889 break;
3890 }
John Kessenichebb50532016-05-16 19:22:05 -06003891}
3892
John Kessenich6fccb3c2016-09-19 16:01:41 -06003893bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003894{
John Kessenicheee9d532016-09-19 18:09:30 -06003895 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003896}
3897
John Kessenichd41993d2017-09-10 15:21:05 -06003898// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003899// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3900// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003901bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003902{
John Kessenich6a14f782017-12-04 02:48:10 -07003903 assert(qualifier == glslang::EvqIn ||
3904 qualifier == glslang::EvqOut ||
3905 qualifier == glslang::EvqInOut ||
3906 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003907 return qualifier != glslang::EvqConstReadOnly;
3908}
3909
3910// Is parameter pass-by-original?
3911bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3912 bool implicitThisParam)
3913{
3914 if (implicitThisParam) // implicit this
3915 return true;
3916 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003917 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003918 return paramType.containsOpaque() || // sampler, etc.
3919 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3920}
3921
John Kessenich140f3df2015-06-26 16:58:36 -06003922// Make all the functions, skeletally, without actually visiting their bodies.
3923void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3924{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003925 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003926 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3927 if (paramPrecision != spv::NoPrecision)
3928 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003929 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003930 if (type.getBasicType() == glslang::EbtReference) {
3931 // Original and non-writable params pass the pointer directly and
3932 // use restrict/aliased, others are stored to a pointer in Function
3933 // memory and use RestrictPointer/AliasedPointer.
3934 if (originalParam(type.getQualifier().storage, type, false) ||
3935 !writableParam(type.getQualifier().storage)) {
3936 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
3937 } else {
3938 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
3939 }
3940 }
John Kessenichfad62972017-07-18 02:35:46 -06003941 };
3942
John Kessenich140f3df2015-06-26 16:58:36 -06003943 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3944 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003945 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003946 continue;
3947
3948 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003949 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003950 //
qining25262b32016-05-06 17:25:16 -04003951 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003952 // function. What it is an address of varies:
3953 //
John Kessenich4bf71552016-09-02 11:20:21 -06003954 // - "in" parameters not marked as "const" can be written to without modifying the calling
3955 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003956 //
3957 // - "const in" parameters can just be the r-value, as no writes need occur.
3958 //
John Kessenich4bf71552016-09-02 11:20:21 -06003959 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3960 // 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 -06003961
3962 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003963 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003964 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3965
John Kessenichfad62972017-07-18 02:35:46 -06003966 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3967 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003968
John Kessenichfad62972017-07-18 02:35:46 -06003969 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003970 for (int p = 0; p < (int)parameters.size(); ++p) {
3971 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3972 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003973 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003974 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003975 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003976 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3977 else
John Kessenich4bf71552016-09-02 11:20:21 -06003978 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003979 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003980 paramTypes.push_back(typeId);
3981 }
3982
3983 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003984 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3985 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003986 glslFunction->getName().c_str(), paramTypes,
3987 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003988 if (implicitThis)
3989 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003990
3991 // Track function to emit/call later
3992 functionMap[glslFunction->getName().c_str()] = function;
3993
3994 // Set the parameter id's
3995 for (int p = 0; p < (int)parameters.size(); ++p) {
3996 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3997 // give a name too
3998 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3999 }
4000 }
4001}
4002
4003// Process all the initializers, while skipping the functions and link objects
4004void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
4005{
4006 builder.setBuildPoint(shaderEntry->getLastBlock());
4007 for (int i = 0; i < (int)initializers.size(); ++i) {
4008 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
4009 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
4010
4011 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06004012 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06004013 initializer->traverse(this);
4014 }
4015 }
4016}
4017
4018// Process all the functions, while skipping initializers.
4019void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
4020{
4021 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
4022 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07004023 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06004024 node->traverse(this);
4025 }
4026}
4027
4028void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
4029{
qining25262b32016-05-06 17:25:16 -04004030 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06004031 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06004032 currentFunction = functionMap[node->getName().c_str()];
4033 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004034 builder.setBuildPoint(functionBlock);
4035}
4036
Rex Xu04db3f52015-09-16 11:44:02 +08004037void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004038{
Rex Xufc618912015-09-09 16:42:49 +08004039 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004040
4041 glslang::TSampler sampler = {};
4042 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004043#ifdef AMD_EXTENSIONS
4044 bool f16ShadowCompare = false;
4045#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004046 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004047 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4048 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004049#ifdef AMD_EXTENSIONS
4050 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4051#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004052 }
4053
John Kessenich140f3df2015-06-26 16:58:36 -06004054 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4055 builder.clearAccessChain();
4056 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004057
4058 // Special case l-value operands
4059 bool lvalue = false;
4060 switch (node.getOp()) {
4061 case glslang::EOpImageAtomicAdd:
4062 case glslang::EOpImageAtomicMin:
4063 case glslang::EOpImageAtomicMax:
4064 case glslang::EOpImageAtomicAnd:
4065 case glslang::EOpImageAtomicOr:
4066 case glslang::EOpImageAtomicXor:
4067 case glslang::EOpImageAtomicExchange:
4068 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004069 case glslang::EOpImageAtomicLoad:
4070 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004071 if (i == 0)
4072 lvalue = true;
4073 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004074 case glslang::EOpSparseImageLoad:
4075 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4076 lvalue = true;
4077 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004078#ifdef AMD_EXTENSIONS
4079 case glslang::EOpSparseTexture:
4080 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4081 lvalue = true;
4082 break;
4083 case glslang::EOpSparseTextureClamp:
4084 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4085 lvalue = true;
4086 break;
4087 case glslang::EOpSparseTextureLod:
4088 case glslang::EOpSparseTextureOffset:
4089 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4090 lvalue = true;
4091 break;
4092#else
Rex Xu48edadf2015-12-31 16:11:41 +08004093 case glslang::EOpSparseTexture:
4094 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4095 lvalue = true;
4096 break;
4097 case glslang::EOpSparseTextureClamp:
4098 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4099 lvalue = true;
4100 break;
4101 case glslang::EOpSparseTextureLod:
4102 case glslang::EOpSparseTextureOffset:
4103 if (i == 3)
4104 lvalue = true;
4105 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004106#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004107 case glslang::EOpSparseTextureFetch:
4108 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4109 lvalue = true;
4110 break;
4111 case glslang::EOpSparseTextureFetchOffset:
4112 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4113 lvalue = true;
4114 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004115#ifdef AMD_EXTENSIONS
4116 case glslang::EOpSparseTextureLodOffset:
4117 case glslang::EOpSparseTextureGrad:
4118 case glslang::EOpSparseTextureOffsetClamp:
4119 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4120 lvalue = true;
4121 break;
4122 case glslang::EOpSparseTextureGradOffset:
4123 case glslang::EOpSparseTextureGradClamp:
4124 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4125 lvalue = true;
4126 break;
4127 case glslang::EOpSparseTextureGradOffsetClamp:
4128 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4129 lvalue = true;
4130 break;
4131#else
Rex Xu48edadf2015-12-31 16:11:41 +08004132 case glslang::EOpSparseTextureLodOffset:
4133 case glslang::EOpSparseTextureGrad:
4134 case glslang::EOpSparseTextureOffsetClamp:
4135 if (i == 4)
4136 lvalue = true;
4137 break;
4138 case glslang::EOpSparseTextureGradOffset:
4139 case glslang::EOpSparseTextureGradClamp:
4140 if (i == 5)
4141 lvalue = true;
4142 break;
4143 case glslang::EOpSparseTextureGradOffsetClamp:
4144 if (i == 6)
4145 lvalue = true;
4146 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004147#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004148 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004149 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4150 lvalue = true;
4151 break;
4152 case glslang::EOpSparseTextureGatherOffset:
4153 case glslang::EOpSparseTextureGatherOffsets:
4154 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4155 lvalue = true;
4156 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004157#ifdef AMD_EXTENSIONS
4158 case glslang::EOpSparseTextureGatherLod:
4159 if (i == 3)
4160 lvalue = true;
4161 break;
4162 case glslang::EOpSparseTextureGatherLodOffset:
4163 case glslang::EOpSparseTextureGatherLodOffsets:
4164 if (i == 4)
4165 lvalue = true;
4166 break;
Rex Xu129799a2017-07-05 17:23:28 +08004167 case glslang::EOpSparseImageLoadLod:
4168 if (i == 3)
4169 lvalue = true;
4170 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004171#endif
Chao Chen3a137962018-09-19 11:41:27 -07004172#ifdef NV_EXTENSIONS
4173 case glslang::EOpImageSampleFootprintNV:
4174 if (i == 4)
4175 lvalue = true;
4176 break;
4177 case glslang::EOpImageSampleFootprintClampNV:
4178 case glslang::EOpImageSampleFootprintLodNV:
4179 if (i == 5)
4180 lvalue = true;
4181 break;
4182 case glslang::EOpImageSampleFootprintGradNV:
4183 if (i == 6)
4184 lvalue = true;
4185 break;
4186 case glslang::EOpImageSampleFootprintGradClampNV:
4187 if (i == 7)
4188 lvalue = true;
4189 break;
4190#endif
Rex Xufc618912015-09-09 16:42:49 +08004191 default:
4192 break;
4193 }
4194
Rex Xu6b86d492015-09-16 17:48:22 +08004195 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08004196 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08004197 else
John Kessenich32cfd492016-02-02 12:37:46 -07004198 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004199 }
4200}
4201
John Kessenichfc51d282015-08-19 13:34:18 -06004202void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004203{
John Kessenichfc51d282015-08-19 13:34:18 -06004204 builder.clearAccessChain();
4205 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004206 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004207}
John Kessenich140f3df2015-06-26 16:58:36 -06004208
John Kessenichfc51d282015-08-19 13:34:18 -06004209spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4210{
John Kesseniche485c7a2017-05-31 18:50:53 -06004211 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004212 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004213
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004214 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004215
John Kessenichfc51d282015-08-19 13:34:18 -06004216 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004217
John Kessenichf43c7392019-03-31 10:51:57 -06004218 const glslang::TType &imageType = node->getAsAggregate()
4219 ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4220 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
Jeff Bolz36831c92018-09-05 10:11:41 -05004221 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004222#ifdef AMD_EXTENSIONS
4223 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
John Kessenichf43c7392019-03-31 10:51:57 -06004224 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4225 : false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004226#endif
4227
John Kessenichf43c7392019-03-31 10:51:57 -06004228 const auto signExtensionMask = [&]() {
4229 if (builder.getSpvVersion() >= spv::Spv_1_4) {
4230 if (sampler.type == glslang::EbtUint)
4231 return spv::ImageOperandsZeroExtendMask;
4232 else if (sampler.type == glslang::EbtInt)
4233 return spv::ImageOperandsSignExtendMask;
4234 }
4235 return spv::ImageOperandsMaskNone;
4236 };
4237
John Kessenichfc51d282015-08-19 13:34:18 -06004238 std::vector<spv::Id> arguments;
4239 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08004240 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06004241 else
4242 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004243 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004244
4245 spv::Builder::TextureParameters params = { };
4246 params.sampler = arguments[0];
4247
Rex Xu04db3f52015-09-16 11:44:02 +08004248 glslang::TCrackedTextureOp cracked;
4249 node->crackTexture(sampler, cracked);
4250
amhagan05506bb2017-06-13 16:53:02 -04004251 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004252
John Kessenichfc51d282015-08-19 13:34:18 -06004253 // Check for queries
4254 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004255 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4256 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004257 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004258
John Kessenichfc51d282015-08-19 13:34:18 -06004259 switch (node->getOp()) {
4260 case glslang::EOpImageQuerySize:
4261 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004262 if (arguments.size() > 1) {
4263 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004264 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004265 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004266 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004267 case glslang::EOpImageQuerySamples:
4268 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004269 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004270 case glslang::EOpTextureQueryLod:
4271 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004272 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004273 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004274 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004275 case glslang::EOpSparseTexelsResident:
4276 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004277 default:
4278 assert(0);
4279 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004280 }
John Kessenich140f3df2015-06-26 16:58:36 -06004281 }
4282
LoopDawg4425f242018-02-18 11:40:01 -07004283 int components = node->getType().getVectorSize();
4284
4285 if (node->getOp() == glslang::EOpTextureFetch) {
4286 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4287 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4288 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4289 // here around e.g. which ones return scalars or other types.
4290 components = 4;
4291 }
4292
4293 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4294
4295 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4296
Rex Xufc618912015-09-09 16:42:49 +08004297 // Check for image functions other than queries
4298 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004299 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004300 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004301 spv::IdImmediate image = { true, *(opIt++) };
4302 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004303
4304 // Handle subpass operations
4305 // TODO: GLSL should change to have the "MS" only on the type rather than the
4306 // built-in function.
4307 if (cracked.subpass) {
4308 // add on the (0,0) coordinate
4309 spv::Id zero = builder.makeIntConstant(0);
4310 std::vector<spv::Id> comps;
4311 comps.push_back(zero);
4312 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004313 spv::IdImmediate coord = { true,
4314 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4315 operands.push_back(coord);
John Kessenichf43c7392019-03-31 10:51:57 -06004316 spv::IdImmediate imageOperands = { false, spv::ImageOperandsMaskNone };
4317 imageOperands.word = imageOperands.word | signExtensionMask();
John Kessenich6c292d32016-02-15 20:58:50 -07004318 if (sampler.ms) {
John Kessenichf43c7392019-03-31 10:51:57 -06004319 imageOperands.word = imageOperands.word | spv::ImageOperandsSampleMask;
4320 }
4321 if (imageOperands.word != spv::ImageOperandsMaskNone) {
John Kessenich149afc32018-08-14 13:31:43 -06004322 operands.push_back(imageOperands);
John Kessenichf43c7392019-03-31 10:51:57 -06004323 if (sampler.ms) {
4324 spv::IdImmediate imageOperand = { true, *(opIt++) };
4325 operands.push_back(imageOperand);
4326 }
John Kessenich6c292d32016-02-15 20:58:50 -07004327 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004328 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4329 builder.setPrecision(result, precision);
4330 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004331 }
4332
John Kessenich149afc32018-08-14 13:31:43 -06004333 spv::IdImmediate coord = { true, *(opIt++) };
4334 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004335#ifdef AMD_EXTENSIONS
4336 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4337#else
John Kessenich56bab042015-09-16 10:54:31 -06004338 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004339#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004340 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004341 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004342 mask = mask | spv::ImageOperandsSampleMask;
4343 }
Rex Xu129799a2017-07-05 17:23:28 +08004344#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004345 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004346 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4347 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004348 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004349 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004350#endif
4351 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4352 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004353 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004354 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004355 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4356 operands.push_back(imageOperands);
4357 }
4358 if (mask & spv::ImageOperandsSampleMask) {
4359 spv::IdImmediate imageOperand = { true, *opIt++ };
4360 operands.push_back(imageOperand);
4361 }
4362#ifdef AMD_EXTENSIONS
4363 if (mask & spv::ImageOperandsLodMask) {
4364 spv::IdImmediate imageOperand = { true, *opIt++ };
4365 operands.push_back(imageOperand);
4366 }
4367#endif
4368 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004369 spv::IdImmediate imageOperand = { true,
4370 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004371 operands.push_back(imageOperand);
4372 }
4373
John Kessenich149afc32018-08-14 13:31:43 -06004374 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004375 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004376
John Kessenich149afc32018-08-14 13:31:43 -06004377 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004378 builder.setPrecision(result[0], precision);
4379
4380 // If needed, add a conversion constructor to the proper size.
4381 if (components != node->getType().getVectorSize())
4382 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4383
4384 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004385#ifdef AMD_EXTENSIONS
4386 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4387#else
John Kessenich56bab042015-09-16 10:54:31 -06004388 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004389#endif
Rex Xu129799a2017-07-05 17:23:28 +08004390
Jeff Bolz36831c92018-09-05 10:11:41 -05004391 // Push the texel value before the operands
4392#ifdef AMD_EXTENSIONS
4393 if (sampler.ms || cracked.lod) {
4394#else
4395 if (sampler.ms) {
4396#endif
John Kessenich149afc32018-08-14 13:31:43 -06004397 spv::IdImmediate texel = { true, *(opIt + 1) };
4398 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004399 } else {
4400 spv::IdImmediate texel = { true, *opIt };
4401 operands.push_back(texel);
4402 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004403
4404 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4405 if (sampler.ms) {
4406 mask = mask | spv::ImageOperandsSampleMask;
4407 }
4408#ifdef AMD_EXTENSIONS
4409 if (cracked.lod) {
4410 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4411 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4412 mask = mask | spv::ImageOperandsLodMask;
4413 }
4414#endif
4415 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4416 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004417 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004418 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004419 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4420 operands.push_back(imageOperands);
4421 }
4422 if (mask & spv::ImageOperandsSampleMask) {
4423 spv::IdImmediate imageOperand = { true, *opIt++ };
4424 operands.push_back(imageOperand);
4425 }
4426#ifdef AMD_EXTENSIONS
4427 if (mask & spv::ImageOperandsLodMask) {
4428 spv::IdImmediate imageOperand = { true, *opIt++ };
4429 operands.push_back(imageOperand);
4430 }
4431#endif
4432 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
John Kessenichf43c7392019-03-31 10:51:57 -06004433 spv::IdImmediate imageOperand = { true,
4434 builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
Jeff Bolz36831c92018-09-05 10:11:41 -05004435 operands.push_back(imageOperand);
4436 }
4437
John Kessenich56bab042015-09-16 10:54:31 -06004438 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004439 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004440 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004441 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004442#ifdef AMD_EXTENSIONS
John Kessenichf43c7392019-03-31 10:51:57 -06004443 } else if (node->getOp() == glslang::EOpSparseImageLoad ||
4444 node->getOp() == glslang::EOpSparseImageLoadLod) {
Rex Xu129799a2017-07-05 17:23:28 +08004445#else
Rex Xu5eafa472016-02-19 22:24:03 +08004446 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004447#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004448 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004449 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004450 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4451
Jeff Bolz36831c92018-09-05 10:11:41 -05004452 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004453 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004454 mask = mask | spv::ImageOperandsSampleMask;
4455 }
Rex Xu129799a2017-07-05 17:23:28 +08004456#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004457 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004458 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4459 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4460
Jeff Bolz36831c92018-09-05 10:11:41 -05004461 mask = mask | spv::ImageOperandsLodMask;
4462 }
4463#endif
4464 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4465 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
John Kessenichf43c7392019-03-31 10:51:57 -06004466 mask = mask | signExtensionMask();
John Kessenich6e384fe2019-05-10 06:47:00 -06004467 if (mask != spv::ImageOperandsMaskNone) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004468 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004469 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004470 }
4471 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004472 spv::IdImmediate imageOperand = { true, *opIt++ };
4473 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004474 }
4475#ifdef AMD_EXTENSIONS
4476 if (mask & spv::ImageOperandsLodMask) {
4477 spv::IdImmediate imageOperand = { true, *opIt++ };
4478 operands.push_back(imageOperand);
4479 }
Rex Xu129799a2017-07-05 17:23:28 +08004480#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004481 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4482 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4483 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004484 }
4485
4486 // Create the return type that was a special structure
4487 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004488 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004489 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4490 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4491
4492 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4493
4494 // Decode the return type
4495 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4496 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004497 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004498 // Process image atomic operations
4499
4500 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4501 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004502 // For non-MS, the sample value should be 0
4503 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4504 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004505
Jeff Bolz36831c92018-09-05 10:11:41 -05004506 spv::Id resultTypeId;
4507 // imageAtomicStore has a void return type so base the pointer type on
4508 // the type of the value operand.
4509 if (node->getOp() == glslang::EOpImageAtomicStore) {
4510 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4511 } else {
4512 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4513 }
John Kessenich56bab042015-09-16 10:54:31 -06004514 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004515
4516 std::vector<spv::Id> operands;
4517 operands.push_back(pointer);
4518 for (; opIt != arguments.end(); ++opIt)
4519 operands.push_back(*opIt);
4520
John Kessenich8c8505c2016-07-26 12:50:38 -06004521 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004522 }
4523 }
4524
amhagan05506bb2017-06-13 16:53:02 -04004525#ifdef AMD_EXTENSIONS
4526 // Check for fragment mask functions other than queries
4527 if (cracked.fragMask) {
4528 assert(sampler.ms);
4529
4530 auto opIt = arguments.begin();
4531 std::vector<spv::Id> operands;
4532
4533 // Extract the image if necessary
4534 if (builder.isSampledImage(params.sampler))
4535 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4536
4537 operands.push_back(params.sampler);
4538 ++opIt;
4539
4540 if (sampler.isSubpass()) {
4541 // add on the (0,0) coordinate
4542 spv::Id zero = builder.makeIntConstant(0);
4543 std::vector<spv::Id> comps;
4544 comps.push_back(zero);
4545 comps.push_back(zero);
4546 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4547 }
4548
4549 for (; opIt != arguments.end(); ++opIt)
4550 operands.push_back(*opIt);
4551
4552 spv::Op fragMaskOp = spv::OpNop;
4553 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4554 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4555 else if (node->getOp() == glslang::EOpFragmentFetch)
4556 fragMaskOp = spv::OpFragmentFetchAMD;
4557
4558 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4559 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4560 return builder.createOp(fragMaskOp, resultType(), operands);
4561 }
4562#endif
4563
Rex Xufc618912015-09-09 16:42:49 +08004564 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004565 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004566#ifdef NV_EXTENSIONS
4567 bool imageFootprint = node->isImageFootprint();
4568#endif
4569
Rex Xu71519fe2015-11-11 15:35:47 +08004570 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4571
John Kessenichfc51d282015-08-19 13:34:18 -06004572 // check for bias argument
4573 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004574#ifdef AMD_EXTENSIONS
4575 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4576#else
Rex Xu71519fe2015-11-11 15:35:47 +08004577 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004578#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004579 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004580#ifdef AMD_EXTENSIONS
4581 if (cracked.gather)
4582 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004583
4584 if (f16ShadowCompare)
4585 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004586#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004587 if (cracked.offset)
4588 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004589#ifdef AMD_EXTENSIONS
4590 else if (cracked.offsets)
4591 ++nonBiasArgCount;
4592#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004593 if (cracked.grad)
4594 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004595 if (cracked.lodClamp)
4596 ++nonBiasArgCount;
4597 if (sparse)
4598 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004599#ifdef NV_EXTENSIONS
4600 if (imageFootprint)
4601 //Following three extra arguments
4602 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4603 nonBiasArgCount += 3;
4604#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004605 if ((int)arguments.size() > nonBiasArgCount)
4606 bias = true;
4607 }
4608
John Kessenicha5c33d62016-06-02 23:45:21 -06004609 // See if the sampler param should really be just the SPV image part
4610 if (cracked.fetch) {
4611 // a fetch needs to have the image extracted first
4612 if (builder.isSampledImage(params.sampler))
4613 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4614 }
4615
Rex Xu225e0fc2016-11-17 17:47:59 +08004616#ifdef AMD_EXTENSIONS
4617 if (cracked.gather) {
4618 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4619 if (bias || cracked.lod ||
4620 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4621 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004622 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004623 }
4624 }
4625#endif
4626
John Kessenichfc51d282015-08-19 13:34:18 -06004627 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004628
John Kessenichfc51d282015-08-19 13:34:18 -06004629 params.coords = arguments[1];
4630 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004631 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004632
4633 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004634#ifdef AMD_EXTENSIONS
4635 if (cubeCompare || f16ShadowCompare) {
4636#else
Rex Xu48edadf2015-12-31 16:11:41 +08004637 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004638#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004639 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004640 ++extraArgs;
4641 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004642 params.Dref = arguments[2];
4643 ++extraArgs;
4644 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004645 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004646 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004647 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004648 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004649 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004650 dRefComp = builder.getNumComponents(params.coords) - 1;
4651 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004652 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4653 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004654
4655 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004656 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004657 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004658 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004659 } else if (glslangIntermediate->getStage() != EShLangFragment
4660#ifdef NV_EXTENSIONS
4661 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4662 && !(glslangIntermediate->getStage() == EShLangCompute &&
4663 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4664#endif
4665 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004666 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4667 noImplicitLod = true;
4668 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004669
4670 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004671 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004672 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004673 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004674 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004675
4676 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004677 if (cracked.grad) {
4678 params.gradX = arguments[2 + extraArgs];
4679 params.gradY = arguments[3 + extraArgs];
4680 extraArgs += 2;
4681 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004682
4683 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004684 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004685 params.offset = arguments[2 + extraArgs];
4686 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004687 } else if (cracked.offsets) {
4688 params.offsets = arguments[2 + extraArgs];
4689 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004690 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004691
4692 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004693 if (cracked.lodClamp) {
4694 params.lodClamp = arguments[2 + extraArgs];
4695 ++extraArgs;
4696 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004697 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004698 if (sparse) {
4699 params.texelOut = arguments[2 + extraArgs];
4700 ++extraArgs;
4701 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004702
John Kessenich76d4dfc2016-06-16 12:43:23 -06004703 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004704 if (cracked.gather && ! sampler.shadow) {
4705 // default component is 0, if missing, otherwise an argument
4706 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004707 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004708 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004709 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004710 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004711 }
Chao Chen3a137962018-09-19 11:41:27 -07004712#ifdef NV_EXTENSIONS
4713 spv::Id resultStruct = spv::NoResult;
4714 if (imageFootprint) {
4715 //Following three extra arguments
4716 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4717 params.granularity = arguments[2 + extraArgs];
4718 params.coarse = arguments[3 + extraArgs];
4719 resultStruct = arguments[4 + extraArgs];
4720 extraArgs += 3;
4721 }
4722#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004723 // bias
4724 if (bias) {
4725 params.bias = arguments[2 + extraArgs];
4726 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004727 }
John Kessenichfc51d282015-08-19 13:34:18 -06004728
Chao Chen3a137962018-09-19 11:41:27 -07004729#ifdef NV_EXTENSIONS
4730 if (imageFootprint) {
4731 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4732 builder.addCapability(spv::CapabilityImageFootprintNV);
4733
4734
4735 //resultStructType(OpenGL type) contains 5 elements:
4736 //struct gl_TextureFootprint2DNV {
4737 // uvec2 anchor;
4738 // uvec2 offset;
4739 // uvec2 mask;
4740 // uint lod;
4741 // uint granularity;
4742 //};
4743 //or
4744 //struct gl_TextureFootprint3DNV {
4745 // uvec3 anchor;
4746 // uvec3 offset;
4747 // uvec2 mask;
4748 // uint lod;
4749 // uint granularity;
4750 //};
4751 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4752 assert(builder.isStructType(resultStructType));
4753
4754 //resType (SPIR-V type) contains 6 elements:
4755 //Member 0 must be a Boolean type scalar(LOD),
4756 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4757 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4758 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4759 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4760 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4761 std::vector<spv::Id> members;
4762 members.push_back(resultType());
4763 for (int i = 0; i < 5; i++) {
4764 members.push_back(builder.getContainedTypeId(resultStructType, i));
4765 }
4766 spv::Id resType = builder.makeStructType(members, "ResType");
4767
4768 //call ImageFootprintNV
John Kessenichf43c7392019-03-31 10:51:57 -06004769 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj,
4770 cracked.gather, noImplicitLod, params, signExtensionMask());
Chao Chen3a137962018-09-19 11:41:27 -07004771
4772 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4773 for (int i = 0; i < 5; i++) {
4774 builder.clearAccessChain();
4775 builder.setAccessChainLValue(resultStruct);
4776
4777 //Accessing to a struct we created, no coherent flag is set
4778 spv::Builder::AccessChain::CoherentFlags flags;
4779 flags.clear();
4780
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004781 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004782 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4783 }
4784 return builder.createCompositeExtract(res, resultType(), 0);
4785 }
4786#endif
4787
John Kessenich65336482016-06-16 14:06:26 -06004788 // projective component (might not to move)
4789 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4790 // are divided by the last component of P."
4791 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4792 // unused components will appear after all used components."
4793 if (cracked.proj) {
4794 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4795 int projTargetComp;
4796 switch (sampler.dim) {
4797 case glslang::Esd1D: projTargetComp = 1; break;
4798 case glslang::Esd2D: projTargetComp = 2; break;
4799 case glslang::EsdRect: projTargetComp = 2; break;
4800 default: projTargetComp = projSourceComp; break;
4801 }
4802 // copy the projective coordinate if we have to
4803 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004804 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004805 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4806 projSourceComp);
4807 params.coords = builder.createCompositeInsert(projComp, params.coords,
4808 builder.getTypeId(params.coords), projTargetComp);
4809 }
4810 }
4811
Jeff Bolz36831c92018-09-05 10:11:41 -05004812 // nonprivate
4813 if (imageType.getQualifier().nonprivate) {
4814 params.nonprivate = true;
4815 }
4816
4817 // volatile
4818 if (imageType.getQualifier().volatil) {
4819 params.volatil = true;
4820 }
4821
St0fFa1184dd2018-04-09 21:08:14 +02004822 std::vector<spv::Id> result( 1,
John Kessenichf43c7392019-03-31 10:51:57 -06004823 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather,
4824 noImplicitLod, params, signExtensionMask())
St0fFa1184dd2018-04-09 21:08:14 +02004825 );
LoopDawg4425f242018-02-18 11:40:01 -07004826
4827 if (components != node->getType().getVectorSize())
4828 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4829
4830 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004831}
4832
4833spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4834{
4835 // Grab the function's pointer from the previously created function
4836 spv::Function* function = functionMap[node->getName().c_str()];
4837 if (! function)
4838 return 0;
4839
4840 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4841 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4842
4843 // See comments in makeFunctions() for details about the semantics for parameter passing.
4844 //
4845 // These imply we need a four step process:
4846 // 1. Evaluate the arguments
4847 // 2. Allocate and make copies of in, out, and inout arguments
4848 // 3. Make the call
4849 // 4. Copy back the results
4850
John Kessenichd3ed90b2018-05-04 11:43:03 -06004851 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004852 std::vector<spv::Builder::AccessChain> lValues;
4853 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004854 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004855 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004856 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004857 // build l-value
4858 builder.clearAccessChain();
4859 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004860 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004861 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004862 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004863 // save l-value
4864 lValues.push_back(builder.getAccessChain());
4865 } else {
4866 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004867 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004868 }
4869 }
4870
4871 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4872 // copy the original into that space.
4873 //
4874 // Also, build up the list of actual arguments to pass in for the call
4875 int lValueCount = 0;
4876 int rValueCount = 0;
4877 std::vector<spv::Id> spvArgs;
4878 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4879 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004880 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004881 builder.setAccessChain(lValues[lValueCount]);
4882 arg = builder.accessChainGetLValue();
4883 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004884 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004885 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004886 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004887 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4888 // need to copy the input into output space
4889 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004890 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004891 builder.clearAccessChain();
4892 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004893 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004894 }
4895 ++lValueCount;
4896 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004897 // process r-value, which involves a copy for a type mismatch
4898 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4899 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4900 builder.clearAccessChain();
4901 builder.setAccessChainLValue(argCopy);
4902 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4903 arg = builder.createLoad(argCopy);
4904 } else
4905 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004906 ++rValueCount;
4907 }
4908 spvArgs.push_back(arg);
4909 }
4910
4911 // 3. Make the call.
4912 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004913 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004914
4915 // 4. Copy back out an "out" arguments.
4916 lValueCount = 0;
4917 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004918 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004919 ++lValueCount;
4920 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004921 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4922 spv::Id copy = builder.createLoad(spvArgs[a]);
4923 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004924 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004925 }
4926 ++lValueCount;
4927 }
4928 }
4929
4930 return result;
4931}
4932
4933// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004934spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004935 spv::Id typeId, spv::Id left, spv::Id right,
4936 glslang::TBasicType typeProxy, bool reduceComparison)
4937{
John Kessenich66011cb2018-03-06 16:12:04 -07004938 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4939 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004940 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004941
4942 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004943 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004944 bool comparison = false;
4945
4946 switch (op) {
4947 case glslang::EOpAdd:
4948 case glslang::EOpAddAssign:
4949 if (isFloat)
4950 binOp = spv::OpFAdd;
4951 else
4952 binOp = spv::OpIAdd;
4953 break;
4954 case glslang::EOpSub:
4955 case glslang::EOpSubAssign:
4956 if (isFloat)
4957 binOp = spv::OpFSub;
4958 else
4959 binOp = spv::OpISub;
4960 break;
4961 case glslang::EOpMul:
4962 case glslang::EOpMulAssign:
4963 if (isFloat)
4964 binOp = spv::OpFMul;
4965 else
4966 binOp = spv::OpIMul;
4967 break;
4968 case glslang::EOpVectorTimesScalar:
4969 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004970 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004971 if (builder.isVector(right))
4972 std::swap(left, right);
4973 assert(builder.isScalar(right));
4974 needMatchingVectors = false;
4975 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01004976 } else if (isFloat)
4977 binOp = spv::OpFMul;
4978 else
John Kessenichec43d0a2015-07-04 17:17:31 -06004979 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004980 break;
4981 case glslang::EOpVectorTimesMatrix:
4982 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004983 binOp = spv::OpVectorTimesMatrix;
4984 break;
4985 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004986 binOp = spv::OpMatrixTimesVector;
4987 break;
4988 case glslang::EOpMatrixTimesScalar:
4989 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004990 binOp = spv::OpMatrixTimesScalar;
4991 break;
4992 case glslang::EOpMatrixTimesMatrix:
4993 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004994 binOp = spv::OpMatrixTimesMatrix;
4995 break;
4996 case glslang::EOpOuterProduct:
4997 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004998 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004999 break;
5000
5001 case glslang::EOpDiv:
5002 case glslang::EOpDivAssign:
5003 if (isFloat)
5004 binOp = spv::OpFDiv;
5005 else if (isUnsigned)
5006 binOp = spv::OpUDiv;
5007 else
5008 binOp = spv::OpSDiv;
5009 break;
5010 case glslang::EOpMod:
5011 case glslang::EOpModAssign:
5012 if (isFloat)
5013 binOp = spv::OpFMod;
5014 else if (isUnsigned)
5015 binOp = spv::OpUMod;
5016 else
5017 binOp = spv::OpSMod;
5018 break;
5019 case glslang::EOpRightShift:
5020 case glslang::EOpRightShiftAssign:
5021 if (isUnsigned)
5022 binOp = spv::OpShiftRightLogical;
5023 else
5024 binOp = spv::OpShiftRightArithmetic;
5025 break;
5026 case glslang::EOpLeftShift:
5027 case glslang::EOpLeftShiftAssign:
5028 binOp = spv::OpShiftLeftLogical;
5029 break;
5030 case glslang::EOpAnd:
5031 case glslang::EOpAndAssign:
5032 binOp = spv::OpBitwiseAnd;
5033 break;
5034 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06005035 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005036 binOp = spv::OpLogicalAnd;
5037 break;
5038 case glslang::EOpInclusiveOr:
5039 case glslang::EOpInclusiveOrAssign:
5040 binOp = spv::OpBitwiseOr;
5041 break;
5042 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06005043 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06005044 binOp = spv::OpLogicalOr;
5045 break;
5046 case glslang::EOpExclusiveOr:
5047 case glslang::EOpExclusiveOrAssign:
5048 binOp = spv::OpBitwiseXor;
5049 break;
5050 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06005051 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06005052 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005053 break;
5054
5055 case glslang::EOpLessThan:
5056 case glslang::EOpGreaterThan:
5057 case glslang::EOpLessThanEqual:
5058 case glslang::EOpGreaterThanEqual:
5059 case glslang::EOpEqual:
5060 case glslang::EOpNotEqual:
5061 case glslang::EOpVectorEqual:
5062 case glslang::EOpVectorNotEqual:
5063 comparison = true;
5064 break;
5065 default:
5066 break;
5067 }
5068
John Kessenich7c1aa102015-10-15 13:29:11 -06005069 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005070 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005071 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005072 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5073 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005074 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005075
5076 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005077 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005078 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005079
qining25262b32016-05-06 17:25:16 -04005080 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005081 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005082 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005083 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005084 }
5085
5086 if (! comparison)
5087 return 0;
5088
John Kessenich7c1aa102015-10-15 13:29:11 -06005089 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005090
John Kessenich4583b612016-08-07 19:14:22 -06005091 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005092 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5093 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06005094 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005095 return result;
5096 }
John Kessenich140f3df2015-06-26 16:58:36 -06005097
5098 switch (op) {
5099 case glslang::EOpLessThan:
5100 if (isFloat)
5101 binOp = spv::OpFOrdLessThan;
5102 else if (isUnsigned)
5103 binOp = spv::OpULessThan;
5104 else
5105 binOp = spv::OpSLessThan;
5106 break;
5107 case glslang::EOpGreaterThan:
5108 if (isFloat)
5109 binOp = spv::OpFOrdGreaterThan;
5110 else if (isUnsigned)
5111 binOp = spv::OpUGreaterThan;
5112 else
5113 binOp = spv::OpSGreaterThan;
5114 break;
5115 case glslang::EOpLessThanEqual:
5116 if (isFloat)
5117 binOp = spv::OpFOrdLessThanEqual;
5118 else if (isUnsigned)
5119 binOp = spv::OpULessThanEqual;
5120 else
5121 binOp = spv::OpSLessThanEqual;
5122 break;
5123 case glslang::EOpGreaterThanEqual:
5124 if (isFloat)
5125 binOp = spv::OpFOrdGreaterThanEqual;
5126 else if (isUnsigned)
5127 binOp = spv::OpUGreaterThanEqual;
5128 else
5129 binOp = spv::OpSGreaterThanEqual;
5130 break;
5131 case glslang::EOpEqual:
5132 case glslang::EOpVectorEqual:
5133 if (isFloat)
5134 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005135 else if (isBool)
5136 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005137 else
5138 binOp = spv::OpIEqual;
5139 break;
5140 case glslang::EOpNotEqual:
5141 case glslang::EOpVectorNotEqual:
5142 if (isFloat)
5143 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005144 else if (isBool)
5145 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005146 else
5147 binOp = spv::OpINotEqual;
5148 break;
5149 default:
5150 break;
5151 }
5152
qining25262b32016-05-06 17:25:16 -04005153 if (binOp != spv::OpNop) {
5154 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005155 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005156 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005157 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005158 }
John Kessenich140f3df2015-06-26 16:58:36 -06005159
5160 return 0;
5161}
5162
John Kessenich04bb8a02015-12-12 12:28:14 -07005163//
5164// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5165// These can be any of:
5166//
5167// matrix * scalar
5168// scalar * matrix
5169// matrix * matrix linear algebraic
5170// matrix * vector
5171// vector * matrix
5172// matrix * matrix componentwise
5173// matrix op matrix op in {+, -, /}
5174// matrix op scalar op in {+, -, /}
5175// scalar op matrix op in {+, -, /}
5176//
John Kessenichead86222018-03-28 18:01:20 -06005177spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5178 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005179{
5180 bool firstClass = true;
5181
5182 // First, handle first-class matrix operations (* and matrix/scalar)
5183 switch (op) {
5184 case spv::OpFDiv:
5185 if (builder.isMatrix(left) && builder.isScalar(right)) {
5186 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005187 spv::Id resultType = builder.getTypeId(right);
5188 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005189 op = spv::OpMatrixTimesScalar;
5190 } else
5191 firstClass = false;
5192 break;
5193 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005194 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005195 std::swap(left, right);
5196 assert(builder.isScalar(right));
5197 break;
5198 case spv::OpVectorTimesMatrix:
5199 assert(builder.isVector(left));
5200 assert(builder.isMatrix(right));
5201 break;
5202 case spv::OpMatrixTimesVector:
5203 assert(builder.isMatrix(left));
5204 assert(builder.isVector(right));
5205 break;
5206 case spv::OpMatrixTimesMatrix:
5207 assert(builder.isMatrix(left));
5208 assert(builder.isMatrix(right));
5209 break;
5210 default:
5211 firstClass = false;
5212 break;
5213 }
5214
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005215 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5216 firstClass = true;
5217
qining25262b32016-05-06 17:25:16 -04005218 if (firstClass) {
5219 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005220 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005221 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005222 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005223 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005224
LoopDawg592860c2016-06-09 08:57:35 -06005225 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005226 // The result type of all of them is the same type as the (a) matrix operand.
5227 // The algorithm is to:
5228 // - break the matrix(es) into vectors
5229 // - smear any scalar to a vector
5230 // - do vector operations
5231 // - make a matrix out the vector results
5232 switch (op) {
5233 case spv::OpFAdd:
5234 case spv::OpFSub:
5235 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005236 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005237 case spv::OpFMul:
5238 {
5239 // one time set up...
5240 bool leftMat = builder.isMatrix(left);
5241 bool rightMat = builder.isMatrix(right);
5242 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5243 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5244 spv::Id scalarType = builder.getScalarTypeId(typeId);
5245 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5246 std::vector<spv::Id> results;
5247 spv::Id smearVec = spv::NoResult;
5248 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005249 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005250 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005251 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005252
5253 // do each vector op
5254 for (unsigned int c = 0; c < numCols; ++c) {
5255 std::vector<unsigned int> indexes;
5256 indexes.push_back(c);
5257 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5258 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005259 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005260 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005261 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005262 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005263 }
5264
5265 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005266 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005267 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005268 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005269 }
5270 default:
5271 assert(0);
5272 return spv::NoResult;
5273 }
5274}
5275
John Kessenichead86222018-03-28 18:01:20 -06005276spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
5277 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005278{
5279 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005280 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005281 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005282 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5283 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005284
5285 switch (op) {
5286 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005287 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005288 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005289 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005290 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005291 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005292 unaryOp = spv::OpSNegate;
5293 break;
5294
5295 case glslang::EOpLogicalNot:
5296 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005297 unaryOp = spv::OpLogicalNot;
5298 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005299 case glslang::EOpBitwiseNot:
5300 unaryOp = spv::OpNot;
5301 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005302
John Kessenich140f3df2015-06-26 16:58:36 -06005303 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005304 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005305 break;
5306 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005307 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005308 break;
5309 case glslang::EOpTranspose:
5310 unaryOp = spv::OpTranspose;
5311 break;
5312
5313 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005314 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005315 break;
5316 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005317 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005318 break;
5319 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005320 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005321 break;
5322 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005323 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005324 break;
5325 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005326 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005327 break;
5328 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005329 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005330 break;
5331 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005332 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005333 break;
5334 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005335 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005336 break;
5337
5338 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005339 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005340 break;
5341 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005342 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005343 break;
5344 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005345 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005346 break;
5347 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005348 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005349 break;
5350 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005351 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005352 break;
5353 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005354 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005355 break;
5356
5357 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005358 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005359 break;
5360 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005361 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005362 break;
5363
5364 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005365 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005366 break;
5367 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005368 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005369 break;
5370 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005371 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005372 break;
5373 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005374 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005375 break;
5376 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005377 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005378 break;
5379 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005380 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005381 break;
5382
5383 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005384 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005385 break;
5386 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005387 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005388 break;
5389 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005390 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005391 break;
5392 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005393 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005394 break;
5395 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005396 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005397 break;
5398 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005399 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005400 break;
5401
5402 case glslang::EOpIsNan:
5403 unaryOp = spv::OpIsNan;
5404 break;
5405 case glslang::EOpIsInf:
5406 unaryOp = spv::OpIsInf;
5407 break;
LoopDawg592860c2016-06-09 08:57:35 -06005408 case glslang::EOpIsFinite:
5409 unaryOp = spv::OpIsFinite;
5410 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005411
Rex Xucbc426e2015-12-15 16:03:10 +08005412 case glslang::EOpFloatBitsToInt:
5413 case glslang::EOpFloatBitsToUint:
5414 case glslang::EOpIntBitsToFloat:
5415 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005416 case glslang::EOpDoubleBitsToInt64:
5417 case glslang::EOpDoubleBitsToUint64:
5418 case glslang::EOpInt64BitsToDouble:
5419 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005420 case glslang::EOpFloat16BitsToInt16:
5421 case glslang::EOpFloat16BitsToUint16:
5422 case glslang::EOpInt16BitsToFloat16:
5423 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005424 unaryOp = spv::OpBitcast;
5425 break;
5426
John Kessenich140f3df2015-06-26 16:58:36 -06005427 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005428 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005429 break;
5430 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005431 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005432 break;
5433 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005434 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005435 break;
5436 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005437 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005438 break;
5439 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005440 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005441 break;
5442 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005443 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005444 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005445 case glslang::EOpPackSnorm4x8:
5446 libCall = spv::GLSLstd450PackSnorm4x8;
5447 break;
5448 case glslang::EOpUnpackSnorm4x8:
5449 libCall = spv::GLSLstd450UnpackSnorm4x8;
5450 break;
5451 case glslang::EOpPackUnorm4x8:
5452 libCall = spv::GLSLstd450PackUnorm4x8;
5453 break;
5454 case glslang::EOpUnpackUnorm4x8:
5455 libCall = spv::GLSLstd450UnpackUnorm4x8;
5456 break;
5457 case glslang::EOpPackDouble2x32:
5458 libCall = spv::GLSLstd450PackDouble2x32;
5459 break;
5460 case glslang::EOpUnpackDouble2x32:
5461 libCall = spv::GLSLstd450UnpackDouble2x32;
5462 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005463
Rex Xu8ff43de2016-04-22 16:51:45 +08005464 case glslang::EOpPackInt2x32:
5465 case glslang::EOpUnpackInt2x32:
5466 case glslang::EOpPackUint2x32:
5467 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005468 case glslang::EOpPack16:
5469 case glslang::EOpPack32:
5470 case glslang::EOpPack64:
5471 case glslang::EOpUnpack32:
5472 case glslang::EOpUnpack16:
5473 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005474 case glslang::EOpPackInt2x16:
5475 case glslang::EOpUnpackInt2x16:
5476 case glslang::EOpPackUint2x16:
5477 case glslang::EOpUnpackUint2x16:
5478 case glslang::EOpPackInt4x16:
5479 case glslang::EOpUnpackInt4x16:
5480 case glslang::EOpPackUint4x16:
5481 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005482 case glslang::EOpPackFloat2x16:
5483 case glslang::EOpUnpackFloat2x16:
5484 unaryOp = spv::OpBitcast;
5485 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005486
John Kessenich140f3df2015-06-26 16:58:36 -06005487 case glslang::EOpDPdx:
5488 unaryOp = spv::OpDPdx;
5489 break;
5490 case glslang::EOpDPdy:
5491 unaryOp = spv::OpDPdy;
5492 break;
5493 case glslang::EOpFwidth:
5494 unaryOp = spv::OpFwidth;
5495 break;
5496 case glslang::EOpDPdxFine:
5497 unaryOp = spv::OpDPdxFine;
5498 break;
5499 case glslang::EOpDPdyFine:
5500 unaryOp = spv::OpDPdyFine;
5501 break;
5502 case glslang::EOpFwidthFine:
5503 unaryOp = spv::OpFwidthFine;
5504 break;
5505 case glslang::EOpDPdxCoarse:
5506 unaryOp = spv::OpDPdxCoarse;
5507 break;
5508 case glslang::EOpDPdyCoarse:
5509 unaryOp = spv::OpDPdyCoarse;
5510 break;
5511 case glslang::EOpFwidthCoarse:
5512 unaryOp = spv::OpFwidthCoarse;
5513 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005514 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005515#ifdef AMD_EXTENSIONS
5516 if (typeProxy == glslang::EbtFloat16)
5517 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5518#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005519 libCall = spv::GLSLstd450InterpolateAtCentroid;
5520 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005521 case glslang::EOpAny:
5522 unaryOp = spv::OpAny;
5523 break;
5524 case glslang::EOpAll:
5525 unaryOp = spv::OpAll;
5526 break;
5527
5528 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005529 if (isFloat)
5530 libCall = spv::GLSLstd450FAbs;
5531 else
5532 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005533 break;
5534 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005535 if (isFloat)
5536 libCall = spv::GLSLstd450FSign;
5537 else
5538 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005539 break;
5540
John Kessenichfc51d282015-08-19 13:34:18 -06005541 case glslang::EOpAtomicCounterIncrement:
5542 case glslang::EOpAtomicCounterDecrement:
5543 case glslang::EOpAtomicCounter:
5544 {
5545 // Handle all of the atomics in one place, in createAtomicOperation()
5546 std::vector<spv::Id> operands;
5547 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005548 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005549 }
5550
John Kessenichfc51d282015-08-19 13:34:18 -06005551 case glslang::EOpBitFieldReverse:
5552 unaryOp = spv::OpBitReverse;
5553 break;
5554 case glslang::EOpBitCount:
5555 unaryOp = spv::OpBitCount;
5556 break;
5557 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005558 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005559 break;
5560 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005561 if (isUnsigned)
5562 libCall = spv::GLSLstd450FindUMsb;
5563 else
5564 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005565 break;
5566
Rex Xu574ab042016-04-14 16:53:07 +08005567 case glslang::EOpBallot:
5568 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005569 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005570 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005571 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005572#ifdef AMD_EXTENSIONS
5573 case glslang::EOpMinInvocations:
5574 case glslang::EOpMaxInvocations:
5575 case glslang::EOpAddInvocations:
5576 case glslang::EOpMinInvocationsNonUniform:
5577 case glslang::EOpMaxInvocationsNonUniform:
5578 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005579 case glslang::EOpMinInvocationsInclusiveScan:
5580 case glslang::EOpMaxInvocationsInclusiveScan:
5581 case glslang::EOpAddInvocationsInclusiveScan:
5582 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5583 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5584 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5585 case glslang::EOpMinInvocationsExclusiveScan:
5586 case glslang::EOpMaxInvocationsExclusiveScan:
5587 case glslang::EOpAddInvocationsExclusiveScan:
5588 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5589 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5590 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005591#endif
Rex Xu51596642016-09-21 18:56:12 +08005592 {
5593 std::vector<spv::Id> operands;
5594 operands.push_back(operand);
5595 return createInvocationsOperation(op, typeId, operands, typeProxy);
5596 }
John Kessenich66011cb2018-03-06 16:12:04 -07005597 case glslang::EOpSubgroupAll:
5598 case glslang::EOpSubgroupAny:
5599 case glslang::EOpSubgroupAllEqual:
5600 case glslang::EOpSubgroupBroadcastFirst:
5601 case glslang::EOpSubgroupBallot:
5602 case glslang::EOpSubgroupInverseBallot:
5603 case glslang::EOpSubgroupBallotBitCount:
5604 case glslang::EOpSubgroupBallotInclusiveBitCount:
5605 case glslang::EOpSubgroupBallotExclusiveBitCount:
5606 case glslang::EOpSubgroupBallotFindLSB:
5607 case glslang::EOpSubgroupBallotFindMSB:
5608 case glslang::EOpSubgroupAdd:
5609 case glslang::EOpSubgroupMul:
5610 case glslang::EOpSubgroupMin:
5611 case glslang::EOpSubgroupMax:
5612 case glslang::EOpSubgroupAnd:
5613 case glslang::EOpSubgroupOr:
5614 case glslang::EOpSubgroupXor:
5615 case glslang::EOpSubgroupInclusiveAdd:
5616 case glslang::EOpSubgroupInclusiveMul:
5617 case glslang::EOpSubgroupInclusiveMin:
5618 case glslang::EOpSubgroupInclusiveMax:
5619 case glslang::EOpSubgroupInclusiveAnd:
5620 case glslang::EOpSubgroupInclusiveOr:
5621 case glslang::EOpSubgroupInclusiveXor:
5622 case glslang::EOpSubgroupExclusiveAdd:
5623 case glslang::EOpSubgroupExclusiveMul:
5624 case glslang::EOpSubgroupExclusiveMin:
5625 case glslang::EOpSubgroupExclusiveMax:
5626 case glslang::EOpSubgroupExclusiveAnd:
5627 case glslang::EOpSubgroupExclusiveOr:
5628 case glslang::EOpSubgroupExclusiveXor:
5629 case glslang::EOpSubgroupQuadSwapHorizontal:
5630 case glslang::EOpSubgroupQuadSwapVertical:
5631 case glslang::EOpSubgroupQuadSwapDiagonal: {
5632 std::vector<spv::Id> operands;
5633 operands.push_back(operand);
5634 return createSubgroupOperation(op, typeId, operands, typeProxy);
5635 }
Rex Xu9d93a232016-05-05 12:30:44 +08005636#ifdef AMD_EXTENSIONS
5637 case glslang::EOpMbcnt:
5638 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5639 libCall = spv::MbcntAMD;
5640 break;
5641
5642 case glslang::EOpCubeFaceIndex:
5643 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5644 libCall = spv::CubeFaceIndexAMD;
5645 break;
5646
5647 case glslang::EOpCubeFaceCoord:
5648 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5649 libCall = spv::CubeFaceCoordAMD;
5650 break;
5651#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005652#ifdef NV_EXTENSIONS
5653 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005654 unaryOp = spv::OpGroupNonUniformPartitionNV;
5655 break;
5656#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005657 case glslang::EOpConstructReference:
5658 unaryOp = spv::OpBitcast;
5659 break;
Jeff Bolz88220d52019-05-08 10:24:46 -05005660
5661 case glslang::EOpCopyObject:
5662 unaryOp = spv::OpCopyObject;
5663 break;
5664
John Kessenich140f3df2015-06-26 16:58:36 -06005665 default:
5666 return 0;
5667 }
5668
5669 spv::Id id;
5670 if (libCall >= 0) {
5671 std::vector<spv::Id> args;
5672 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005673 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005674 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005675 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005676 }
John Kessenich140f3df2015-06-26 16:58:36 -06005677
John Kessenichead86222018-03-28 18:01:20 -06005678 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005679 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005680 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005681}
5682
John Kessenich7a53f762016-01-20 11:19:27 -07005683// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005684spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5685 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005686{
5687 // Handle unary operations vector by vector.
5688 // The result type is the same type as the original type.
5689 // The algorithm is to:
5690 // - break the matrix into vectors
5691 // - apply the operation to each vector
5692 // - make a matrix out the vector results
5693
5694 // get the types sorted out
5695 int numCols = builder.getNumColumns(operand);
5696 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005697 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5698 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005699 std::vector<spv::Id> results;
5700
5701 // do each vector op
5702 for (int c = 0; c < numCols; ++c) {
5703 std::vector<unsigned int> indexes;
5704 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005705 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5706 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005707 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005708 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005709 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005710 }
5711
5712 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005713 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005714 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005715 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005716}
5717
John Kessenichad7645f2018-06-04 19:11:25 -06005718// For converting integers where both the bitwidth and the signedness could
5719// change, but only do the width change here. The caller is still responsible
5720// for the signedness conversion.
5721spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005722{
John Kessenichad7645f2018-06-04 19:11:25 -06005723 // Get the result type width, based on the type to convert to.
5724 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005725 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005726 case glslang::EOpConvInt16ToUint8:
5727 case glslang::EOpConvIntToUint8:
5728 case glslang::EOpConvInt64ToUint8:
5729 case glslang::EOpConvUint16ToInt8:
5730 case glslang::EOpConvUintToInt8:
5731 case glslang::EOpConvUint64ToInt8:
5732 width = 8;
5733 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005734 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005735 case glslang::EOpConvIntToUint16:
5736 case glslang::EOpConvInt64ToUint16:
5737 case glslang::EOpConvUint8ToInt16:
5738 case glslang::EOpConvUintToInt16:
5739 case glslang::EOpConvUint64ToInt16:
5740 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005741 break;
5742 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005743 case glslang::EOpConvInt16ToUint:
5744 case glslang::EOpConvInt64ToUint:
5745 case glslang::EOpConvUint8ToInt:
5746 case glslang::EOpConvUint16ToInt:
5747 case glslang::EOpConvUint64ToInt:
5748 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005749 break;
5750 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005751 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005752 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005753 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005754 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005755 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005756 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005757 break;
5758
5759 default:
5760 assert(false && "Default missing");
5761 break;
5762 }
5763
John Kessenichad7645f2018-06-04 19:11:25 -06005764 // Get the conversion operation and result type,
5765 // based on the target width, but the source type.
5766 spv::Id type = spv::NoType;
5767 spv::Op convOp = spv::OpNop;
5768 switch(op) {
5769 case glslang::EOpConvInt8ToUint16:
5770 case glslang::EOpConvInt8ToUint:
5771 case glslang::EOpConvInt8ToUint64:
5772 case glslang::EOpConvInt16ToUint8:
5773 case glslang::EOpConvInt16ToUint:
5774 case glslang::EOpConvInt16ToUint64:
5775 case glslang::EOpConvIntToUint8:
5776 case glslang::EOpConvIntToUint16:
5777 case glslang::EOpConvIntToUint64:
5778 case glslang::EOpConvInt64ToUint8:
5779 case glslang::EOpConvInt64ToUint16:
5780 case glslang::EOpConvInt64ToUint:
5781 convOp = spv::OpSConvert;
5782 type = builder.makeIntType(width);
5783 break;
5784 default:
5785 convOp = spv::OpUConvert;
5786 type = builder.makeUintType(width);
5787 break;
5788 }
5789
John Kessenich66011cb2018-03-06 16:12:04 -07005790 if (vectorSize > 0)
5791 type = builder.makeVectorType(type, vectorSize);
5792
John Kessenichad7645f2018-06-04 19:11:25 -06005793 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005794}
5795
John Kessenichead86222018-03-28 18:01:20 -06005796spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5797 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005798{
5799 spv::Op convOp = spv::OpNop;
5800 spv::Id zero = 0;
5801 spv::Id one = 0;
5802
5803 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5804
5805 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005806 case glslang::EOpConvInt8ToBool:
5807 case glslang::EOpConvUint8ToBool:
5808 zero = builder.makeUint8Constant(0);
5809 zero = makeSmearedConstant(zero, vectorSize);
5810 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005811 case glslang::EOpConvInt16ToBool:
5812 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005813 zero = builder.makeUint16Constant(0);
5814 zero = makeSmearedConstant(zero, vectorSize);
5815 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5816 case glslang::EOpConvIntToBool:
5817 case glslang::EOpConvUintToBool:
5818 zero = builder.makeUintConstant(0);
5819 zero = makeSmearedConstant(zero, vectorSize);
5820 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5821 case glslang::EOpConvInt64ToBool:
5822 case glslang::EOpConvUint64ToBool:
5823 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005824 zero = makeSmearedConstant(zero, vectorSize);
5825 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5826
5827 case glslang::EOpConvFloatToBool:
5828 zero = builder.makeFloatConstant(0.0F);
5829 zero = makeSmearedConstant(zero, vectorSize);
5830 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5831
5832 case glslang::EOpConvDoubleToBool:
5833 zero = builder.makeDoubleConstant(0.0);
5834 zero = makeSmearedConstant(zero, vectorSize);
5835 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5836
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005837 case glslang::EOpConvFloat16ToBool:
5838 zero = builder.makeFloat16Constant(0.0F);
5839 zero = makeSmearedConstant(zero, vectorSize);
5840 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005841
John Kessenich140f3df2015-06-26 16:58:36 -06005842 case glslang::EOpConvBoolToFloat:
5843 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005844 zero = builder.makeFloatConstant(0.0F);
5845 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005846 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005847
John Kessenich140f3df2015-06-26 16:58:36 -06005848 case glslang::EOpConvBoolToDouble:
5849 convOp = spv::OpSelect;
5850 zero = builder.makeDoubleConstant(0.0);
5851 one = builder.makeDoubleConstant(1.0);
5852 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005853
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005854 case glslang::EOpConvBoolToFloat16:
5855 convOp = spv::OpSelect;
5856 zero = builder.makeFloat16Constant(0.0F);
5857 one = builder.makeFloat16Constant(1.0F);
5858 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005859
5860 case glslang::EOpConvBoolToInt8:
5861 zero = builder.makeInt8Constant(0);
5862 one = builder.makeInt8Constant(1);
5863 convOp = spv::OpSelect;
5864 break;
5865
5866 case glslang::EOpConvBoolToUint8:
5867 zero = builder.makeUint8Constant(0);
5868 one = builder.makeUint8Constant(1);
5869 convOp = spv::OpSelect;
5870 break;
5871
5872 case glslang::EOpConvBoolToInt16:
5873 zero = builder.makeInt16Constant(0);
5874 one = builder.makeInt16Constant(1);
5875 convOp = spv::OpSelect;
5876 break;
5877
5878 case glslang::EOpConvBoolToUint16:
5879 zero = builder.makeUint16Constant(0);
5880 one = builder.makeUint16Constant(1);
5881 convOp = spv::OpSelect;
5882 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005883
John Kessenich140f3df2015-06-26 16:58:36 -06005884 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005885 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005886 if (op == glslang::EOpConvBoolToInt64)
5887 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005888 else
5889 zero = builder.makeIntConstant(0);
5890
5891 if (op == glslang::EOpConvBoolToInt64)
5892 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005893 else
5894 one = builder.makeIntConstant(1);
5895
John Kessenich140f3df2015-06-26 16:58:36 -06005896 convOp = spv::OpSelect;
5897 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005898
John Kessenich140f3df2015-06-26 16:58:36 -06005899 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005900 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005901 if (op == glslang::EOpConvBoolToUint64)
5902 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005903 else
5904 zero = builder.makeUintConstant(0);
5905
5906 if (op == glslang::EOpConvBoolToUint64)
5907 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005908 else
5909 one = builder.makeUintConstant(1);
5910
John Kessenich140f3df2015-06-26 16:58:36 -06005911 convOp = spv::OpSelect;
5912 break;
5913
John Kessenich66011cb2018-03-06 16:12:04 -07005914 case glslang::EOpConvInt8ToFloat16:
5915 case glslang::EOpConvInt8ToFloat:
5916 case glslang::EOpConvInt8ToDouble:
5917 case glslang::EOpConvInt16ToFloat16:
5918 case glslang::EOpConvInt16ToFloat:
5919 case glslang::EOpConvInt16ToDouble:
5920 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005921 case glslang::EOpConvIntToFloat:
5922 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005923 case glslang::EOpConvInt64ToFloat:
5924 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005925 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005926 convOp = spv::OpConvertSToF;
5927 break;
5928
John Kessenich66011cb2018-03-06 16:12:04 -07005929 case glslang::EOpConvUint8ToFloat16:
5930 case glslang::EOpConvUint8ToFloat:
5931 case glslang::EOpConvUint8ToDouble:
5932 case glslang::EOpConvUint16ToFloat16:
5933 case glslang::EOpConvUint16ToFloat:
5934 case glslang::EOpConvUint16ToDouble:
5935 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005936 case glslang::EOpConvUintToFloat:
5937 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005938 case glslang::EOpConvUint64ToFloat:
5939 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005940 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005941 convOp = spv::OpConvertUToF;
5942 break;
5943
5944 case glslang::EOpConvDoubleToFloat:
5945 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005946 case glslang::EOpConvDoubleToFloat16:
5947 case glslang::EOpConvFloat16ToDouble:
5948 case glslang::EOpConvFloatToFloat16:
5949 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005950 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005951 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005952 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005953 break;
5954
John Kessenich66011cb2018-03-06 16:12:04 -07005955 case glslang::EOpConvFloat16ToInt8:
5956 case glslang::EOpConvFloatToInt8:
5957 case glslang::EOpConvDoubleToInt8:
5958 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005959 case glslang::EOpConvFloatToInt16:
5960 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005961 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005962 case glslang::EOpConvFloatToInt:
5963 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005964 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005965 case glslang::EOpConvFloatToInt64:
5966 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005967 convOp = spv::OpConvertFToS;
5968 break;
5969
John Kessenich66011cb2018-03-06 16:12:04 -07005970 case glslang::EOpConvUint8ToInt8:
5971 case glslang::EOpConvInt8ToUint8:
5972 case glslang::EOpConvUint16ToInt16:
5973 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005974 case glslang::EOpConvUintToInt:
5975 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005976 case glslang::EOpConvUint64ToInt64:
5977 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005978 if (builder.isInSpecConstCodeGenMode()) {
5979 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005980 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5981 zero = builder.makeUint8Constant(0);
5982 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005983 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005984 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5985 zero = builder.makeUint64Constant(0);
5986 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005987 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005988 }
qining189b2032016-04-12 23:16:20 -04005989 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005990 // Use OpIAdd, instead of OpBitcast to do the conversion when
5991 // generating for OpSpecConstantOp instruction.
5992 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5993 }
5994 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005995 convOp = spv::OpBitcast;
5996 break;
5997
John Kessenich66011cb2018-03-06 16:12:04 -07005998 case glslang::EOpConvFloat16ToUint8:
5999 case glslang::EOpConvFloatToUint8:
6000 case glslang::EOpConvDoubleToUint8:
6001 case glslang::EOpConvFloat16ToUint16:
6002 case glslang::EOpConvFloatToUint16:
6003 case glslang::EOpConvDoubleToUint16:
6004 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06006005 case glslang::EOpConvFloatToUint:
6006 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006007 case glslang::EOpConvFloatToUint64:
6008 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006009 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06006010 convOp = spv::OpConvertFToU;
6011 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006012
John Kessenich66011cb2018-03-06 16:12:04 -07006013 case glslang::EOpConvInt8ToInt16:
6014 case glslang::EOpConvInt8ToInt:
6015 case glslang::EOpConvInt8ToInt64:
6016 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08006017 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006018 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07006019 case glslang::EOpConvIntToInt8:
6020 case glslang::EOpConvIntToInt16:
6021 case glslang::EOpConvIntToInt64:
6022 case glslang::EOpConvInt64ToInt8:
6023 case glslang::EOpConvInt64ToInt16:
6024 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006025 convOp = spv::OpSConvert;
6026 break;
6027
John Kessenich66011cb2018-03-06 16:12:04 -07006028 case glslang::EOpConvUint8ToUint16:
6029 case glslang::EOpConvUint8ToUint:
6030 case glslang::EOpConvUint8ToUint64:
6031 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006032 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006033 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006034 case glslang::EOpConvUintToUint8:
6035 case glslang::EOpConvUintToUint16:
6036 case glslang::EOpConvUintToUint64:
6037 case glslang::EOpConvUint64ToUint8:
6038 case glslang::EOpConvUint64ToUint16:
6039 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08006040 convOp = spv::OpUConvert;
6041 break;
6042
John Kessenich66011cb2018-03-06 16:12:04 -07006043 case glslang::EOpConvInt8ToUint16:
6044 case glslang::EOpConvInt8ToUint:
6045 case glslang::EOpConvInt8ToUint64:
6046 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006047 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08006048 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07006049 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006050 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006051 case glslang::EOpConvIntToUint64:
6052 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08006053 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07006054 case glslang::EOpConvInt64ToUint:
6055 case glslang::EOpConvUint8ToInt16:
6056 case glslang::EOpConvUint8ToInt:
6057 case glslang::EOpConvUint8ToInt64:
6058 case glslang::EOpConvUint16ToInt8:
6059 case glslang::EOpConvUint16ToInt:
6060 case glslang::EOpConvUint16ToInt64:
6061 case glslang::EOpConvUintToInt8:
6062 case glslang::EOpConvUintToInt16:
6063 case glslang::EOpConvUintToInt64:
6064 case glslang::EOpConvUint64ToInt8:
6065 case glslang::EOpConvUint64ToInt16:
6066 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006067 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006068 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006069
6070 if (builder.isInSpecConstCodeGenMode()) {
6071 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006072 switch(op) {
6073 case glslang::EOpConvInt16ToUint8:
6074 case glslang::EOpConvIntToUint8:
6075 case glslang::EOpConvInt64ToUint8:
6076 case glslang::EOpConvUint16ToInt8:
6077 case glslang::EOpConvUintToInt8:
6078 case glslang::EOpConvUint64ToInt8:
6079 zero = builder.makeUint8Constant(0);
6080 break;
6081 case glslang::EOpConvInt8ToUint16:
6082 case glslang::EOpConvIntToUint16:
6083 case glslang::EOpConvInt64ToUint16:
6084 case glslang::EOpConvUint8ToInt16:
6085 case glslang::EOpConvUintToInt16:
6086 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006087 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006088 break;
6089 case glslang::EOpConvInt8ToUint:
6090 case glslang::EOpConvInt16ToUint:
6091 case glslang::EOpConvInt64ToUint:
6092 case glslang::EOpConvUint8ToInt:
6093 case glslang::EOpConvUint16ToInt:
6094 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006095 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006096 break;
6097 case glslang::EOpConvInt8ToUint64:
6098 case glslang::EOpConvInt16ToUint64:
6099 case glslang::EOpConvIntToUint64:
6100 case glslang::EOpConvUint8ToInt64:
6101 case glslang::EOpConvUint16ToInt64:
6102 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006103 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006104 break;
6105 default:
6106 assert(false && "Default missing");
6107 break;
6108 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006109 zero = makeSmearedConstant(zero, vectorSize);
6110 // Use OpIAdd, instead of OpBitcast to do the conversion when
6111 // generating for OpSpecConstantOp instruction.
6112 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6113 }
6114 // For normal run-time conversion instruction, use OpBitcast.
6115 convOp = spv::OpBitcast;
6116 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006117 case glslang::EOpConvUint64ToPtr:
6118 convOp = spv::OpConvertUToPtr;
6119 break;
6120 case glslang::EOpConvPtrToUint64:
6121 convOp = spv::OpConvertPtrToU;
6122 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006123 default:
6124 break;
6125 }
6126
6127 spv::Id result = 0;
6128 if (convOp == spv::OpNop)
6129 return result;
6130
6131 if (convOp == spv::OpSelect) {
6132 zero = makeSmearedConstant(zero, vectorSize);
6133 one = makeSmearedConstant(one, vectorSize);
6134 result = builder.createTriOp(convOp, destType, operand, one, zero);
6135 } else
6136 result = builder.createUnaryOp(convOp, destType, operand);
6137
John Kessenichead86222018-03-28 18:01:20 -06006138 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006139 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006140 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006141}
6142
6143spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6144{
6145 if (vectorSize == 0)
6146 return constant;
6147
6148 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6149 std::vector<spv::Id> components;
6150 for (int c = 0; c < vectorSize; ++c)
6151 components.push_back(constant);
6152 return builder.makeCompositeConstant(vectorTypeId, components);
6153}
6154
John Kessenich426394d2015-07-23 10:22:48 -06006155// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07006156spv::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 -06006157{
6158 spv::Op opCode = spv::OpNop;
6159
6160 switch (op) {
6161 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006162 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006163 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006164 opCode = spv::OpAtomicIAdd;
6165 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006166 case glslang::EOpAtomicCounterSubtract:
6167 opCode = spv::OpAtomicISub;
6168 break;
John Kessenich426394d2015-07-23 10:22:48 -06006169 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006170 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006171 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006172 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006173 break;
6174 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006175 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006176 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006177 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006178 break;
6179 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006180 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006181 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006182 opCode = spv::OpAtomicAnd;
6183 break;
6184 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006185 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006186 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006187 opCode = spv::OpAtomicOr;
6188 break;
6189 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006190 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006191 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006192 opCode = spv::OpAtomicXor;
6193 break;
6194 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006195 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006196 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006197 opCode = spv::OpAtomicExchange;
6198 break;
6199 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006200 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006201 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006202 opCode = spv::OpAtomicCompareExchange;
6203 break;
6204 case glslang::EOpAtomicCounterIncrement:
6205 opCode = spv::OpAtomicIIncrement;
6206 break;
6207 case glslang::EOpAtomicCounterDecrement:
6208 opCode = spv::OpAtomicIDecrement;
6209 break;
6210 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006211 case glslang::EOpImageAtomicLoad:
6212 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006213 opCode = spv::OpAtomicLoad;
6214 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006215 case glslang::EOpAtomicStore:
6216 case glslang::EOpImageAtomicStore:
6217 opCode = spv::OpAtomicStore;
6218 break;
John Kessenich426394d2015-07-23 10:22:48 -06006219 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006220 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006221 break;
6222 }
6223
Rex Xue8fe8b02017-09-26 15:42:56 +08006224 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6225 builder.addCapability(spv::CapabilityInt64Atomics);
6226
John Kessenich426394d2015-07-23 10:22:48 -06006227 // Sort out the operands
6228 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006229 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006230 // - compare-exchange swaps the value and comparator
6231 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006232 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006233 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6234 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6235 spv::Id scopeId;
6236 if (glslangIntermediate->usingVulkanMemoryModel()) {
6237 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6238 } else {
6239 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6240 }
6241 // semantics default to relaxed
6242 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
6243 spv::Id semanticsId2 = semanticsId;
6244
6245 pointerId = operands[0];
6246 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6247 // no additional operands
6248 } else if (opCode == spv::OpAtomicCompareExchange) {
6249 compareId = operands[1];
6250 valueId = operands[2];
6251 if (operands.size() > 3) {
6252 scopeId = operands[3];
6253 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6254 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6255 }
6256 } else if (opCode == spv::OpAtomicLoad) {
6257 if (operands.size() > 1) {
6258 scopeId = operands[1];
6259 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6260 }
6261 } else {
6262 // atomic store or RMW
6263 valueId = operands[1];
6264 if (operands.size() > 2) {
6265 scopeId = operands[2];
6266 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6267 }
Rex Xu04db3f52015-09-16 11:44:02 +08006268 }
John Kessenich426394d2015-07-23 10:22:48 -06006269
Jeff Bolz36831c92018-09-05 10:11:41 -05006270 // Check for capabilities
6271 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
6272 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6273 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6274 }
John Kessenich426394d2015-07-23 10:22:48 -06006275
Jeff Bolz36831c92018-09-05 10:11:41 -05006276 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6277 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6278 }
John Kessenich48d6e792017-10-06 21:21:48 -06006279
Jeff Bolz36831c92018-09-05 10:11:41 -05006280 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6281 spvAtomicOperands.push_back(pointerId);
6282 spvAtomicOperands.push_back(scopeId);
6283 spvAtomicOperands.push_back(semanticsId);
6284 if (opCode == spv::OpAtomicCompareExchange) {
6285 spvAtomicOperands.push_back(semanticsId2);
6286 spvAtomicOperands.push_back(valueId);
6287 spvAtomicOperands.push_back(compareId);
6288 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6289 spvAtomicOperands.push_back(valueId);
6290 }
John Kessenich48d6e792017-10-06 21:21:48 -06006291
Jeff Bolz36831c92018-09-05 10:11:41 -05006292 if (opCode == spv::OpAtomicStore) {
6293 builder.createNoResultOp(opCode, spvAtomicOperands);
6294 return 0;
6295 } else {
6296 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6297
6298 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6299 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6300 if (op == glslang::EOpAtomicCounterDecrement)
6301 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6302
6303 return resultId;
6304 }
John Kessenich426394d2015-07-23 10:22:48 -06006305}
6306
John Kessenich91cef522016-05-05 16:45:40 -06006307// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006308spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006309{
Corentin Walleze7061422018-08-08 15:20:15 +02006310#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006311 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6312 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006313#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006314
Rex Xu51596642016-09-21 18:56:12 +08006315 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006316 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006317 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6318
chaocf200da82016-12-20 12:44:35 -08006319 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6320 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006321 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6322 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006323 } else if (op == glslang::EOpAnyInvocation ||
6324 op == glslang::EOpAllInvocations ||
6325 op == glslang::EOpAllInvocationsEqual) {
6326 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6327 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006328 } else {
6329 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006330#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006331 if (op == glslang::EOpMinInvocationsNonUniform ||
6332 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006333 op == glslang::EOpAddInvocationsNonUniform ||
6334 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6335 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6336 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6337 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6338 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6339 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006340 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006341#endif
Rex Xu51596642016-09-21 18:56:12 +08006342
Rex Xu9d93a232016-05-05 12:30:44 +08006343#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006344 switch (op) {
6345 case glslang::EOpMinInvocations:
6346 case glslang::EOpMaxInvocations:
6347 case glslang::EOpAddInvocations:
6348 case glslang::EOpMinInvocationsNonUniform:
6349 case glslang::EOpMaxInvocationsNonUniform:
6350 case glslang::EOpAddInvocationsNonUniform:
6351 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006352 break;
6353 case glslang::EOpMinInvocationsInclusiveScan:
6354 case glslang::EOpMaxInvocationsInclusiveScan:
6355 case glslang::EOpAddInvocationsInclusiveScan:
6356 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6357 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6358 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6359 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006360 break;
6361 case glslang::EOpMinInvocationsExclusiveScan:
6362 case glslang::EOpMaxInvocationsExclusiveScan:
6363 case glslang::EOpAddInvocationsExclusiveScan:
6364 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6365 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6366 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6367 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006368 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006369 default:
6370 break;
Rex Xu430ef402016-10-14 17:22:23 +08006371 }
John Kessenich149afc32018-08-14 13:31:43 -06006372 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6373 spvGroupOperands.push_back(scope);
6374 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006375 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006376 spvGroupOperands.push_back(groupOp);
6377 }
Rex Xu9d93a232016-05-05 12:30:44 +08006378#endif
Rex Xu51596642016-09-21 18:56:12 +08006379 }
6380
John Kessenich149afc32018-08-14 13:31:43 -06006381 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6382 spv::IdImmediate op = { true, *opIt };
6383 spvGroupOperands.push_back(op);
6384 }
John Kessenich91cef522016-05-05 16:45:40 -06006385
6386 switch (op) {
6387 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006388 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006389 break;
John Kessenich91cef522016-05-05 16:45:40 -06006390 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006391 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006392 break;
John Kessenich91cef522016-05-05 16:45:40 -06006393 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006394 opCode = spv::OpSubgroupAllEqualKHR;
6395 break;
Rex Xu51596642016-09-21 18:56:12 +08006396 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006397 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006398 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006399 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006400 break;
6401 case glslang::EOpReadFirstInvocation:
6402 opCode = spv::OpSubgroupFirstInvocationKHR;
6403 break;
6404 case glslang::EOpBallot:
6405 {
6406 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6407 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6408 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6409 //
6410 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6411 //
6412 spv::Id uintType = builder.makeUintType(32);
6413 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6414 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6415
6416 std::vector<spv::Id> components;
6417 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6418 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6419
6420 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6421 return builder.createUnaryOp(spv::OpBitcast, typeId,
6422 builder.createCompositeConstruct(uvec2Type, components));
6423 }
6424
Rex Xu9d93a232016-05-05 12:30:44 +08006425#ifdef AMD_EXTENSIONS
6426 case glslang::EOpMinInvocations:
6427 case glslang::EOpMaxInvocations:
6428 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006429 case glslang::EOpMinInvocationsInclusiveScan:
6430 case glslang::EOpMaxInvocationsInclusiveScan:
6431 case glslang::EOpAddInvocationsInclusiveScan:
6432 case glslang::EOpMinInvocationsExclusiveScan:
6433 case glslang::EOpMaxInvocationsExclusiveScan:
6434 case glslang::EOpAddInvocationsExclusiveScan:
6435 if (op == glslang::EOpMinInvocations ||
6436 op == glslang::EOpMinInvocationsInclusiveScan ||
6437 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006438 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006439 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006440 else {
6441 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006442 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006443 else
Rex Xu51596642016-09-21 18:56:12 +08006444 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006445 }
Rex Xu430ef402016-10-14 17:22:23 +08006446 } else if (op == glslang::EOpMaxInvocations ||
6447 op == glslang::EOpMaxInvocationsInclusiveScan ||
6448 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006449 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006450 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006451 else {
6452 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006453 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006454 else
Rex Xu51596642016-09-21 18:56:12 +08006455 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006456 }
6457 } else {
6458 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006459 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006460 else
Rex Xu51596642016-09-21 18:56:12 +08006461 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006462 }
6463
Rex Xu2bbbe062016-08-23 15:41:05 +08006464 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006465 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006466
6467 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006468 case glslang::EOpMinInvocationsNonUniform:
6469 case glslang::EOpMaxInvocationsNonUniform:
6470 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006471 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6472 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6473 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6474 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6475 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6476 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6477 if (op == glslang::EOpMinInvocationsNonUniform ||
6478 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6479 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006480 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006481 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006482 else {
6483 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006484 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006485 else
Rex Xu51596642016-09-21 18:56:12 +08006486 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006487 }
6488 }
Rex Xu430ef402016-10-14 17:22:23 +08006489 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6490 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6491 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006492 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006493 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006494 else {
6495 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006496 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006497 else
Rex Xu51596642016-09-21 18:56:12 +08006498 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006499 }
6500 }
6501 else {
6502 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006503 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006504 else
Rex Xu51596642016-09-21 18:56:12 +08006505 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006506 }
6507
Rex Xu2bbbe062016-08-23 15:41:05 +08006508 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006509 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006510
6511 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006512#endif
John Kessenich91cef522016-05-05 16:45:40 -06006513 default:
6514 logger->missingFunctionality("invocation operation");
6515 return spv::NoResult;
6516 }
Rex Xu51596642016-09-21 18:56:12 +08006517
6518 assert(opCode != spv::OpNop);
6519 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006520}
6521
Rex Xu2bbbe062016-08-23 15:41:05 +08006522// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006523spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6524 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006525{
Rex Xub7072052016-09-26 15:53:40 +08006526#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006527 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6528 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006529 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006530 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006531 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6532 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6533 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006534#else
6535 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6536 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006537 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6538 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006539#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006540
6541 // Handle group invocation operations scalar by scalar.
6542 // The result type is the same type as the original type.
6543 // The algorithm is to:
6544 // - break the vector into scalars
6545 // - apply the operation to each scalar
6546 // - make a vector out the scalar results
6547
6548 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006549 int numComponents = builder.getNumComponents(operands[0]);
6550 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006551 std::vector<spv::Id> results;
6552
6553 // do each scalar op
6554 for (int comp = 0; comp < numComponents; ++comp) {
6555 std::vector<unsigned int> indexes;
6556 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006557 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6558 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006559 if (op == spv::OpSubgroupReadInvocationKHR) {
6560 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006561 spv::IdImmediate operand = { true, operands[1] };
6562 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006563 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006564 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6565 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006566 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006567 spv::IdImmediate operand = { true, operands[1] };
6568 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006569 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006570 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6571 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006572 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006573 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006574 spvGroupOperands.push_back(scalar);
6575 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006576
Rex Xub7072052016-09-26 15:53:40 +08006577 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006578 }
6579
6580 // put the pieces together
6581 return builder.createCompositeConstruct(typeId, results);
6582}
Rex Xu2bbbe062016-08-23 15:41:05 +08006583
John Kessenich66011cb2018-03-06 16:12:04 -07006584// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006585spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6586 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006587{
6588 // Add the required capabilities.
6589 switch (op) {
6590 case glslang::EOpSubgroupElect:
6591 builder.addCapability(spv::CapabilityGroupNonUniform);
6592 break;
6593 case glslang::EOpSubgroupAll:
6594 case glslang::EOpSubgroupAny:
6595 case glslang::EOpSubgroupAllEqual:
6596 builder.addCapability(spv::CapabilityGroupNonUniform);
6597 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6598 break;
6599 case glslang::EOpSubgroupBroadcast:
6600 case glslang::EOpSubgroupBroadcastFirst:
6601 case glslang::EOpSubgroupBallot:
6602 case glslang::EOpSubgroupInverseBallot:
6603 case glslang::EOpSubgroupBallotBitExtract:
6604 case glslang::EOpSubgroupBallotBitCount:
6605 case glslang::EOpSubgroupBallotInclusiveBitCount:
6606 case glslang::EOpSubgroupBallotExclusiveBitCount:
6607 case glslang::EOpSubgroupBallotFindLSB:
6608 case glslang::EOpSubgroupBallotFindMSB:
6609 builder.addCapability(spv::CapabilityGroupNonUniform);
6610 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6611 break;
6612 case glslang::EOpSubgroupShuffle:
6613 case glslang::EOpSubgroupShuffleXor:
6614 builder.addCapability(spv::CapabilityGroupNonUniform);
6615 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6616 break;
6617 case glslang::EOpSubgroupShuffleUp:
6618 case glslang::EOpSubgroupShuffleDown:
6619 builder.addCapability(spv::CapabilityGroupNonUniform);
6620 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6621 break;
6622 case glslang::EOpSubgroupAdd:
6623 case glslang::EOpSubgroupMul:
6624 case glslang::EOpSubgroupMin:
6625 case glslang::EOpSubgroupMax:
6626 case glslang::EOpSubgroupAnd:
6627 case glslang::EOpSubgroupOr:
6628 case glslang::EOpSubgroupXor:
6629 case glslang::EOpSubgroupInclusiveAdd:
6630 case glslang::EOpSubgroupInclusiveMul:
6631 case glslang::EOpSubgroupInclusiveMin:
6632 case glslang::EOpSubgroupInclusiveMax:
6633 case glslang::EOpSubgroupInclusiveAnd:
6634 case glslang::EOpSubgroupInclusiveOr:
6635 case glslang::EOpSubgroupInclusiveXor:
6636 case glslang::EOpSubgroupExclusiveAdd:
6637 case glslang::EOpSubgroupExclusiveMul:
6638 case glslang::EOpSubgroupExclusiveMin:
6639 case glslang::EOpSubgroupExclusiveMax:
6640 case glslang::EOpSubgroupExclusiveAnd:
6641 case glslang::EOpSubgroupExclusiveOr:
6642 case glslang::EOpSubgroupExclusiveXor:
6643 builder.addCapability(spv::CapabilityGroupNonUniform);
6644 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6645 break;
6646 case glslang::EOpSubgroupClusteredAdd:
6647 case glslang::EOpSubgroupClusteredMul:
6648 case glslang::EOpSubgroupClusteredMin:
6649 case glslang::EOpSubgroupClusteredMax:
6650 case glslang::EOpSubgroupClusteredAnd:
6651 case glslang::EOpSubgroupClusteredOr:
6652 case glslang::EOpSubgroupClusteredXor:
6653 builder.addCapability(spv::CapabilityGroupNonUniform);
6654 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6655 break;
6656 case glslang::EOpSubgroupQuadBroadcast:
6657 case glslang::EOpSubgroupQuadSwapHorizontal:
6658 case glslang::EOpSubgroupQuadSwapVertical:
6659 case glslang::EOpSubgroupQuadSwapDiagonal:
6660 builder.addCapability(spv::CapabilityGroupNonUniform);
6661 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6662 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006663#ifdef NV_EXTENSIONS
6664 case glslang::EOpSubgroupPartitionedAdd:
6665 case glslang::EOpSubgroupPartitionedMul:
6666 case glslang::EOpSubgroupPartitionedMin:
6667 case glslang::EOpSubgroupPartitionedMax:
6668 case glslang::EOpSubgroupPartitionedAnd:
6669 case glslang::EOpSubgroupPartitionedOr:
6670 case glslang::EOpSubgroupPartitionedXor:
6671 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6672 case glslang::EOpSubgroupPartitionedInclusiveMul:
6673 case glslang::EOpSubgroupPartitionedInclusiveMin:
6674 case glslang::EOpSubgroupPartitionedInclusiveMax:
6675 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6676 case glslang::EOpSubgroupPartitionedInclusiveOr:
6677 case glslang::EOpSubgroupPartitionedInclusiveXor:
6678 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6679 case glslang::EOpSubgroupPartitionedExclusiveMul:
6680 case glslang::EOpSubgroupPartitionedExclusiveMin:
6681 case glslang::EOpSubgroupPartitionedExclusiveMax:
6682 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6683 case glslang::EOpSubgroupPartitionedExclusiveOr:
6684 case glslang::EOpSubgroupPartitionedExclusiveXor:
6685 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6686 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6687 break;
6688#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006689 default: assert(0 && "Unhandled subgroup operation!");
6690 }
6691
6692 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6693 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6694 const bool isBool = typeProxy == glslang::EbtBool;
6695
6696 spv::Op opCode = spv::OpNop;
6697
6698 // Figure out which opcode to use.
6699 switch (op) {
6700 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6701 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6702 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6703 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6704 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6705 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6706 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6707 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6708 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6709 case glslang::EOpSubgroupBallotBitCount:
6710 case glslang::EOpSubgroupBallotInclusiveBitCount:
6711 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6712 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6713 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6714 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6715 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6716 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6717 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6718 case glslang::EOpSubgroupAdd:
6719 case glslang::EOpSubgroupInclusiveAdd:
6720 case glslang::EOpSubgroupExclusiveAdd:
6721 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006722#ifdef NV_EXTENSIONS
6723 case glslang::EOpSubgroupPartitionedAdd:
6724 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6725 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6726#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006727 if (isFloat) {
6728 opCode = spv::OpGroupNonUniformFAdd;
6729 } else {
6730 opCode = spv::OpGroupNonUniformIAdd;
6731 }
6732 break;
6733 case glslang::EOpSubgroupMul:
6734 case glslang::EOpSubgroupInclusiveMul:
6735 case glslang::EOpSubgroupExclusiveMul:
6736 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006737#ifdef NV_EXTENSIONS
6738 case glslang::EOpSubgroupPartitionedMul:
6739 case glslang::EOpSubgroupPartitionedInclusiveMul:
6740 case glslang::EOpSubgroupPartitionedExclusiveMul:
6741#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006742 if (isFloat) {
6743 opCode = spv::OpGroupNonUniformFMul;
6744 } else {
6745 opCode = spv::OpGroupNonUniformIMul;
6746 }
6747 break;
6748 case glslang::EOpSubgroupMin:
6749 case glslang::EOpSubgroupInclusiveMin:
6750 case glslang::EOpSubgroupExclusiveMin:
6751 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006752#ifdef NV_EXTENSIONS
6753 case glslang::EOpSubgroupPartitionedMin:
6754 case glslang::EOpSubgroupPartitionedInclusiveMin:
6755 case glslang::EOpSubgroupPartitionedExclusiveMin:
6756#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006757 if (isFloat) {
6758 opCode = spv::OpGroupNonUniformFMin;
6759 } else if (isUnsigned) {
6760 opCode = spv::OpGroupNonUniformUMin;
6761 } else {
6762 opCode = spv::OpGroupNonUniformSMin;
6763 }
6764 break;
6765 case glslang::EOpSubgroupMax:
6766 case glslang::EOpSubgroupInclusiveMax:
6767 case glslang::EOpSubgroupExclusiveMax:
6768 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006769#ifdef NV_EXTENSIONS
6770 case glslang::EOpSubgroupPartitionedMax:
6771 case glslang::EOpSubgroupPartitionedInclusiveMax:
6772 case glslang::EOpSubgroupPartitionedExclusiveMax:
6773#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006774 if (isFloat) {
6775 opCode = spv::OpGroupNonUniformFMax;
6776 } else if (isUnsigned) {
6777 opCode = spv::OpGroupNonUniformUMax;
6778 } else {
6779 opCode = spv::OpGroupNonUniformSMax;
6780 }
6781 break;
6782 case glslang::EOpSubgroupAnd:
6783 case glslang::EOpSubgroupInclusiveAnd:
6784 case glslang::EOpSubgroupExclusiveAnd:
6785 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006786#ifdef NV_EXTENSIONS
6787 case glslang::EOpSubgroupPartitionedAnd:
6788 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6789 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6790#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006791 if (isBool) {
6792 opCode = spv::OpGroupNonUniformLogicalAnd;
6793 } else {
6794 opCode = spv::OpGroupNonUniformBitwiseAnd;
6795 }
6796 break;
6797 case glslang::EOpSubgroupOr:
6798 case glslang::EOpSubgroupInclusiveOr:
6799 case glslang::EOpSubgroupExclusiveOr:
6800 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006801#ifdef NV_EXTENSIONS
6802 case glslang::EOpSubgroupPartitionedOr:
6803 case glslang::EOpSubgroupPartitionedInclusiveOr:
6804 case glslang::EOpSubgroupPartitionedExclusiveOr:
6805#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006806 if (isBool) {
6807 opCode = spv::OpGroupNonUniformLogicalOr;
6808 } else {
6809 opCode = spv::OpGroupNonUniformBitwiseOr;
6810 }
6811 break;
6812 case glslang::EOpSubgroupXor:
6813 case glslang::EOpSubgroupInclusiveXor:
6814 case glslang::EOpSubgroupExclusiveXor:
6815 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006816#ifdef NV_EXTENSIONS
6817 case glslang::EOpSubgroupPartitionedXor:
6818 case glslang::EOpSubgroupPartitionedInclusiveXor:
6819 case glslang::EOpSubgroupPartitionedExclusiveXor:
6820#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006821 if (isBool) {
6822 opCode = spv::OpGroupNonUniformLogicalXor;
6823 } else {
6824 opCode = spv::OpGroupNonUniformBitwiseXor;
6825 }
6826 break;
6827 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6828 case glslang::EOpSubgroupQuadSwapHorizontal:
6829 case glslang::EOpSubgroupQuadSwapVertical:
6830 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6831 default: assert(0 && "Unhandled subgroup operation!");
6832 }
6833
John Kessenich149afc32018-08-14 13:31:43 -06006834 // get the right Group Operation
6835 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006836 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006837 default:
6838 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006839 case glslang::EOpSubgroupBallotBitCount:
6840 case glslang::EOpSubgroupAdd:
6841 case glslang::EOpSubgroupMul:
6842 case glslang::EOpSubgroupMin:
6843 case glslang::EOpSubgroupMax:
6844 case glslang::EOpSubgroupAnd:
6845 case glslang::EOpSubgroupOr:
6846 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006847 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006848 break;
6849 case glslang::EOpSubgroupBallotInclusiveBitCount:
6850 case glslang::EOpSubgroupInclusiveAdd:
6851 case glslang::EOpSubgroupInclusiveMul:
6852 case glslang::EOpSubgroupInclusiveMin:
6853 case glslang::EOpSubgroupInclusiveMax:
6854 case glslang::EOpSubgroupInclusiveAnd:
6855 case glslang::EOpSubgroupInclusiveOr:
6856 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006857 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006858 break;
6859 case glslang::EOpSubgroupBallotExclusiveBitCount:
6860 case glslang::EOpSubgroupExclusiveAdd:
6861 case glslang::EOpSubgroupExclusiveMul:
6862 case glslang::EOpSubgroupExclusiveMin:
6863 case glslang::EOpSubgroupExclusiveMax:
6864 case glslang::EOpSubgroupExclusiveAnd:
6865 case glslang::EOpSubgroupExclusiveOr:
6866 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006867 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006868 break;
6869 case glslang::EOpSubgroupClusteredAdd:
6870 case glslang::EOpSubgroupClusteredMul:
6871 case glslang::EOpSubgroupClusteredMin:
6872 case glslang::EOpSubgroupClusteredMax:
6873 case glslang::EOpSubgroupClusteredAnd:
6874 case glslang::EOpSubgroupClusteredOr:
6875 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006876 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006877 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006878#ifdef NV_EXTENSIONS
6879 case glslang::EOpSubgroupPartitionedAdd:
6880 case glslang::EOpSubgroupPartitionedMul:
6881 case glslang::EOpSubgroupPartitionedMin:
6882 case glslang::EOpSubgroupPartitionedMax:
6883 case glslang::EOpSubgroupPartitionedAnd:
6884 case glslang::EOpSubgroupPartitionedOr:
6885 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006886 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006887 break;
6888 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6889 case glslang::EOpSubgroupPartitionedInclusiveMul:
6890 case glslang::EOpSubgroupPartitionedInclusiveMin:
6891 case glslang::EOpSubgroupPartitionedInclusiveMax:
6892 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6893 case glslang::EOpSubgroupPartitionedInclusiveOr:
6894 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006895 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006896 break;
6897 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6898 case glslang::EOpSubgroupPartitionedExclusiveMul:
6899 case glslang::EOpSubgroupPartitionedExclusiveMin:
6900 case glslang::EOpSubgroupPartitionedExclusiveMax:
6901 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6902 case glslang::EOpSubgroupPartitionedExclusiveOr:
6903 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006904 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006905 break;
6906#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006907 }
6908
John Kessenich149afc32018-08-14 13:31:43 -06006909 // build the instruction
6910 std::vector<spv::IdImmediate> spvGroupOperands;
6911
6912 // Every operation begins with the Execution Scope operand.
6913 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6914 spvGroupOperands.push_back(executionScope);
6915
6916 // Next, for all operations that use a Group Operation, push that as an operand.
6917 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006918 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006919 spvGroupOperands.push_back(groupOperand);
6920 }
6921
John Kessenich66011cb2018-03-06 16:12:04 -07006922 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006923 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6924 spv::IdImmediate operand = { true, *opIt };
6925 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006926 }
6927
6928 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006929 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006930 switch (op) {
6931 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006932 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6933 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6934 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6935 }
6936 if (directionId != spv::NoResult) {
6937 spv::IdImmediate direction = { true, directionId };
6938 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006939 }
6940
6941 return builder.createOp(opCode, typeId, spvGroupOperands);
6942}
6943
John Kessenich5e4b1242015-08-06 22:53:06 -06006944spv::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 -06006945{
John Kessenich66011cb2018-03-06 16:12:04 -07006946 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6947 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006948
John Kessenich140f3df2015-06-26 16:58:36 -06006949 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006950 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006951 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006952 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006953 spv::Id typeId0 = 0;
6954 if (consumedOperands > 0)
6955 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006956 spv::Id typeId1 = 0;
6957 if (consumedOperands > 1)
6958 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006959 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006960
6961 switch (op) {
6962 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006963 if (isFloat)
6964 libCall = spv::GLSLstd450FMin;
6965 else if (isUnsigned)
6966 libCall = spv::GLSLstd450UMin;
6967 else
6968 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006969 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006970 break;
6971 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006972 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006973 break;
6974 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006975 if (isFloat)
6976 libCall = spv::GLSLstd450FMax;
6977 else if (isUnsigned)
6978 libCall = spv::GLSLstd450UMax;
6979 else
6980 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006981 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006982 break;
6983 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006984 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006985 break;
6986 case glslang::EOpDot:
6987 opCode = spv::OpDot;
6988 break;
6989 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006990 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006991 break;
6992
6993 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006994 if (isFloat)
6995 libCall = spv::GLSLstd450FClamp;
6996 else if (isUnsigned)
6997 libCall = spv::GLSLstd450UClamp;
6998 else
6999 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007000 builder.promoteScalar(precision, operands.front(), operands[1]);
7001 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007002 break;
7003 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08007004 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
7005 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07007006 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08007007 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07007008 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08007009 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07007010 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07007011 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007012 break;
7013 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007014 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007015 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06007016 break;
7017 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06007018 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07007019 builder.promoteScalar(precision, operands[0], operands[2]);
7020 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06007021 break;
7022
7023 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06007024 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06007025 break;
7026 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06007027 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06007028 break;
7029 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06007030 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06007031 break;
7032 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06007033 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06007034 break;
7035 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06007036 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06007037 break;
Rex Xu7a26c172015-12-08 17:12:09 +08007038 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007039#ifdef AMD_EXTENSIONS
7040 if (typeProxy == glslang::EbtFloat16)
7041 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7042#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007043 libCall = spv::GLSLstd450InterpolateAtSample;
7044 break;
7045 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007046#ifdef AMD_EXTENSIONS
7047 if (typeProxy == glslang::EbtFloat16)
7048 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
7049#endif
Rex Xu7a26c172015-12-08 17:12:09 +08007050 libCall = spv::GLSLstd450InterpolateAtOffset;
7051 break;
John Kessenich55e7d112015-11-15 21:33:39 -07007052 case glslang::EOpAddCarry:
7053 opCode = spv::OpIAddCarry;
7054 typeId = builder.makeStructResultType(typeId0, typeId0);
7055 consumedOperands = 2;
7056 break;
7057 case glslang::EOpSubBorrow:
7058 opCode = spv::OpISubBorrow;
7059 typeId = builder.makeStructResultType(typeId0, typeId0);
7060 consumedOperands = 2;
7061 break;
7062 case glslang::EOpUMulExtended:
7063 opCode = spv::OpUMulExtended;
7064 typeId = builder.makeStructResultType(typeId0, typeId0);
7065 consumedOperands = 2;
7066 break;
7067 case glslang::EOpIMulExtended:
7068 opCode = spv::OpSMulExtended;
7069 typeId = builder.makeStructResultType(typeId0, typeId0);
7070 consumedOperands = 2;
7071 break;
7072 case glslang::EOpBitfieldExtract:
7073 if (isUnsigned)
7074 opCode = spv::OpBitFieldUExtract;
7075 else
7076 opCode = spv::OpBitFieldSExtract;
7077 break;
7078 case glslang::EOpBitfieldInsert:
7079 opCode = spv::OpBitFieldInsert;
7080 break;
7081
7082 case glslang::EOpFma:
7083 libCall = spv::GLSLstd450Fma;
7084 break;
7085 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007086 {
7087 libCall = spv::GLSLstd450FrexpStruct;
7088 assert(builder.isPointerType(typeId1));
7089 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007090 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007091#ifdef AMD_EXTENSIONS
7092 if (width == 16)
7093 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7094 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
7095#endif
Rex Xu470026f2017-03-29 17:12:40 +08007096 if (builder.getNumComponents(operands[0]) == 1)
7097 frexpIntType = builder.makeIntegerType(width, true);
7098 else
7099 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7100 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7101 consumedOperands = 1;
7102 }
John Kessenich55e7d112015-11-15 21:33:39 -07007103 break;
7104 case glslang::EOpLdexp:
7105 libCall = spv::GLSLstd450Ldexp;
7106 break;
7107
Rex Xu574ab042016-04-14 16:53:07 +08007108 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007109 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007110
John Kessenich66011cb2018-03-06 16:12:04 -07007111 case glslang::EOpSubgroupBroadcast:
7112 case glslang::EOpSubgroupBallotBitExtract:
7113 case glslang::EOpSubgroupShuffle:
7114 case glslang::EOpSubgroupShuffleXor:
7115 case glslang::EOpSubgroupShuffleUp:
7116 case glslang::EOpSubgroupShuffleDown:
7117 case glslang::EOpSubgroupClusteredAdd:
7118 case glslang::EOpSubgroupClusteredMul:
7119 case glslang::EOpSubgroupClusteredMin:
7120 case glslang::EOpSubgroupClusteredMax:
7121 case glslang::EOpSubgroupClusteredAnd:
7122 case glslang::EOpSubgroupClusteredOr:
7123 case glslang::EOpSubgroupClusteredXor:
7124 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007125#ifdef NV_EXTENSIONS
7126 case glslang::EOpSubgroupPartitionedAdd:
7127 case glslang::EOpSubgroupPartitionedMul:
7128 case glslang::EOpSubgroupPartitionedMin:
7129 case glslang::EOpSubgroupPartitionedMax:
7130 case glslang::EOpSubgroupPartitionedAnd:
7131 case glslang::EOpSubgroupPartitionedOr:
7132 case glslang::EOpSubgroupPartitionedXor:
7133 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7134 case glslang::EOpSubgroupPartitionedInclusiveMul:
7135 case glslang::EOpSubgroupPartitionedInclusiveMin:
7136 case glslang::EOpSubgroupPartitionedInclusiveMax:
7137 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7138 case glslang::EOpSubgroupPartitionedInclusiveOr:
7139 case glslang::EOpSubgroupPartitionedInclusiveXor:
7140 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7141 case glslang::EOpSubgroupPartitionedExclusiveMul:
7142 case glslang::EOpSubgroupPartitionedExclusiveMin:
7143 case glslang::EOpSubgroupPartitionedExclusiveMax:
7144 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7145 case glslang::EOpSubgroupPartitionedExclusiveOr:
7146 case glslang::EOpSubgroupPartitionedExclusiveXor:
7147#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007148 return createSubgroupOperation(op, typeId, operands, typeProxy);
7149
Rex Xu9d93a232016-05-05 12:30:44 +08007150#ifdef AMD_EXTENSIONS
7151 case glslang::EOpSwizzleInvocations:
7152 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7153 libCall = spv::SwizzleInvocationsAMD;
7154 break;
7155 case glslang::EOpSwizzleInvocationsMasked:
7156 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7157 libCall = spv::SwizzleInvocationsMaskedAMD;
7158 break;
7159 case glslang::EOpWriteInvocation:
7160 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7161 libCall = spv::WriteInvocationAMD;
7162 break;
7163
7164 case glslang::EOpMin3:
7165 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7166 if (isFloat)
7167 libCall = spv::FMin3AMD;
7168 else {
7169 if (isUnsigned)
7170 libCall = spv::UMin3AMD;
7171 else
7172 libCall = spv::SMin3AMD;
7173 }
7174 break;
7175 case glslang::EOpMax3:
7176 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7177 if (isFloat)
7178 libCall = spv::FMax3AMD;
7179 else {
7180 if (isUnsigned)
7181 libCall = spv::UMax3AMD;
7182 else
7183 libCall = spv::SMax3AMD;
7184 }
7185 break;
7186 case glslang::EOpMid3:
7187 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7188 if (isFloat)
7189 libCall = spv::FMid3AMD;
7190 else {
7191 if (isUnsigned)
7192 libCall = spv::UMid3AMD;
7193 else
7194 libCall = spv::SMid3AMD;
7195 }
7196 break;
7197
7198 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007199 if (typeProxy == glslang::EbtFloat16)
7200 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007201 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7202 libCall = spv::InterpolateAtVertexAMD;
7203 break;
7204#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007205 case glslang::EOpBarrier:
7206 {
7207 // This is for the extended controlBarrier function, with four operands.
7208 // The unextended barrier() goes through createNoArgOperation.
7209 assert(operands.size() == 4);
7210 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7211 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7212 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7213 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7214 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7215 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7216 }
7217 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7218 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7219 }
7220 return 0;
7221 }
7222 break;
7223 case glslang::EOpMemoryBarrier:
7224 {
7225 // This is for the extended memoryBarrier function, with three operands.
7226 // The unextended memoryBarrier() goes through createNoArgOperation.
7227 assert(operands.size() == 3);
7228 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7229 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7230 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7231 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7232 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7233 }
7234 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7235 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7236 }
7237 return 0;
7238 }
7239 break;
Chao Chen3c366992018-09-19 11:41:59 -07007240
7241#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007242 case glslang::EOpReportIntersectionNV:
7243 {
7244 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007245 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007246 }
7247 break;
7248 case glslang::EOpTraceNV:
7249 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007250 builder.createNoResultOp(spv::OpTraceNV, operands);
7251 return 0;
7252 }
7253 break;
7254 case glslang::EOpExecuteCallableNV:
7255 {
7256 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007257 return 0;
7258 }
7259 break;
Chao Chen3c366992018-09-19 11:41:59 -07007260 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7261 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7262 return 0;
7263#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007264 case glslang::EOpCooperativeMatrixMulAdd:
7265 opCode = spv::OpCooperativeMatrixMulAddNV;
7266 break;
7267
John Kessenich140f3df2015-06-26 16:58:36 -06007268 default:
7269 return 0;
7270 }
7271
7272 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007273 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007274 // Use an extended instruction from the standard library.
7275 // Construct the call arguments, without modifying the original operands vector.
7276 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7277 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007278 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007279 } else if (opCode == spv::OpDot && !isFloat) {
7280 // int dot(int, int)
7281 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7282 const int componentCount = builder.getNumComponents(operands[0]);
7283 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7284 builder.setPrecision(mulOp, precision);
7285 id = builder.createCompositeExtract(mulOp, typeId, 0);
7286 for (int i = 1; i < componentCount; ++i) {
7287 builder.setPrecision(id, precision);
7288 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7289 }
John Kessenich2359bd02015-12-06 19:29:11 -07007290 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007291 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007292 case 0:
7293 // should all be handled by visitAggregate and createNoArgOperation
7294 assert(0);
7295 return 0;
7296 case 1:
7297 // should all be handled by createUnaryOperation
7298 assert(0);
7299 return 0;
7300 case 2:
7301 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7302 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007303 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007304 // anything 3 or over doesn't have l-value operands, so all should be consumed
7305 assert(consumedOperands == operands.size());
7306 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007307 break;
7308 }
7309 }
7310
John Kessenich55e7d112015-11-15 21:33:39 -07007311 // Decode the return types that were structures
7312 switch (op) {
7313 case glslang::EOpAddCarry:
7314 case glslang::EOpSubBorrow:
7315 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7316 id = builder.createCompositeExtract(id, typeId0, 0);
7317 break;
7318 case glslang::EOpUMulExtended:
7319 case glslang::EOpIMulExtended:
7320 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7321 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7322 break;
7323 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007324 {
7325 assert(operands.size() == 2);
7326 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7327 // "exp" is floating-point type (from HLSL intrinsic)
7328 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7329 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7330 builder.createStore(member1, operands[1]);
7331 } else
7332 // "exp" is integer type (from GLSL built-in function)
7333 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7334 id = builder.createCompositeExtract(id, typeId0, 0);
7335 }
John Kessenich55e7d112015-11-15 21:33:39 -07007336 break;
7337 default:
7338 break;
7339 }
7340
John Kessenich32cfd492016-02-02 12:37:46 -07007341 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007342}
7343
Rex Xu9d93a232016-05-05 12:30:44 +08007344// Intrinsics with no arguments (or no return value, and no precision).
7345spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007346{
Jeff Bolz36831c92018-09-05 10:11:41 -05007347 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7348 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007349
7350 switch (op) {
7351 case glslang::EOpEmitVertex:
7352 builder.createNoResultOp(spv::OpEmitVertex);
7353 return 0;
7354 case glslang::EOpEndPrimitive:
7355 builder.createNoResultOp(spv::OpEndPrimitive);
7356 return 0;
7357 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007358 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007359 if (glslangIntermediate->usingVulkanMemoryModel()) {
7360 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7361 spv::MemorySemanticsOutputMemoryKHRMask |
7362 spv::MemorySemanticsAcquireReleaseMask);
7363 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7364 } else {
7365 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7366 }
John Kessenich82979362017-12-11 04:02:24 -07007367 } else {
7368 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7369 spv::MemorySemanticsWorkgroupMemoryMask |
7370 spv::MemorySemanticsAcquireReleaseMask);
7371 }
John Kessenich140f3df2015-06-26 16:58:36 -06007372 return 0;
7373 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007374 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7375 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007376 return 0;
7377 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007378 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7379 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007380 return 0;
7381 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007382 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7383 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007384 return 0;
7385 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007386 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7387 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007388 return 0;
7389 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007390 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7391 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007392 return 0;
7393 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007394 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7395 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007396 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007397 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007398 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007399 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007400 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007401 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007402 case glslang::EOpDeviceMemoryBarrier:
7403 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7404 spv::MemorySemanticsImageMemoryMask |
7405 spv::MemorySemanticsAcquireReleaseMask);
7406 return 0;
7407 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7408 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7409 spv::MemorySemanticsImageMemoryMask |
7410 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007411 return 0;
7412 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007413 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7414 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007415 return 0;
7416 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007417 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7418 spv::MemorySemanticsWorkgroupMemoryMask |
7419 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007420 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007421 case glslang::EOpSubgroupBarrier:
7422 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7423 spv::MemorySemanticsAcquireReleaseMask);
7424 return spv::NoResult;
7425 case glslang::EOpSubgroupMemoryBarrier:
7426 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7427 spv::MemorySemanticsAcquireReleaseMask);
7428 return spv::NoResult;
7429 case glslang::EOpSubgroupMemoryBarrierBuffer:
7430 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7431 spv::MemorySemanticsAcquireReleaseMask);
7432 return spv::NoResult;
7433 case glslang::EOpSubgroupMemoryBarrierImage:
7434 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7435 spv::MemorySemanticsAcquireReleaseMask);
7436 return spv::NoResult;
7437 case glslang::EOpSubgroupMemoryBarrierShared:
7438 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7439 spv::MemorySemanticsAcquireReleaseMask);
7440 return spv::NoResult;
7441 case glslang::EOpSubgroupElect: {
7442 std::vector<spv::Id> operands;
7443 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7444 }
Rex Xu9d93a232016-05-05 12:30:44 +08007445#ifdef AMD_EXTENSIONS
7446 case glslang::EOpTime:
7447 {
7448 std::vector<spv::Id> args; // Dummy arguments
7449 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7450 return builder.setPrecision(id, precision);
7451 }
7452#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007453#ifdef NV_EXTENSIONS
7454 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007455 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007456 return 0;
7457 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007458 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007459 return 0;
7460#endif
Jeff Bolzc6f0ce82019-06-03 11:33:50 -05007461
7462 case glslang::EOpBeginInvocationInterlock:
7463 builder.createNoResultOp(spv::OpBeginInvocationInterlockEXT);
7464 return 0;
7465 case glslang::EOpEndInvocationInterlock:
7466 builder.createNoResultOp(spv::OpEndInvocationInterlockEXT);
7467 return 0;
7468
John Kessenich140f3df2015-06-26 16:58:36 -06007469 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007470 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007471 return 0;
7472 }
7473}
7474
7475spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7476{
John Kessenich2f273362015-07-18 22:34:27 -06007477 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007478 spv::Id id;
7479 if (symbolValues.end() != iter) {
7480 id = iter->second;
7481 return id;
7482 }
7483
7484 // it was not found, create it
7485 id = createSpvVariable(symbol);
7486 symbolValues[symbol->getId()] = id;
7487
Rex Xuc884b4a2016-06-29 15:03:44 +08007488 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007489 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7490 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7491 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007492#ifdef NV_EXTENSIONS
7493 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7494#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007495 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007496 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007497 if (symbol->getQualifier().hasIndex())
7498 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7499 if (symbol->getQualifier().hasComponent())
7500 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007501 // atomic counters use this:
7502 if (symbol->getQualifier().hasOffset())
7503 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007504 }
7505
scygan2c864272016-05-18 18:09:17 +02007506 if (symbol->getQualifier().hasLocation())
7507 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007508 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007509 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007510 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007511 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007512 }
John Kessenich140f3df2015-06-26 16:58:36 -06007513 if (symbol->getQualifier().hasSet())
7514 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007515 else if (IsDescriptorResource(symbol->getType())) {
7516 // default to 0
7517 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7518 }
John Kessenich140f3df2015-06-26 16:58:36 -06007519 if (symbol->getQualifier().hasBinding())
7520 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007521 else if (IsDescriptorResource(symbol->getType())) {
7522 // default to 0
7523 builder.addDecoration(id, spv::DecorationBinding, 0);
7524 }
John Kessenich6c292d32016-02-15 20:58:50 -07007525 if (symbol->getQualifier().hasAttachment())
7526 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007527 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007528 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007529 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007530 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007531 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7532 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7533 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7534 }
7535 if (symbol->getQualifier().hasXfbOffset())
7536 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007537 }
7538
Rex Xu1da878f2016-02-21 20:59:01 +08007539 if (symbol->getType().isImage()) {
7540 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007541 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007542 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007543 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007544 }
7545
John Kessenich140f3df2015-06-26 16:58:36 -06007546 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007547 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007548 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007549 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007550
John Kessenich5611c6d2018-04-05 11:25:02 -06007551 // nonuniform
7552 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7553
John Kessenichecba76f2017-01-06 00:34:48 -07007554#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007555 if (builtIn == spv::BuiltInSampleMask) {
7556 spv::Decoration decoration;
7557 // GL_NV_sample_mask_override_coverage extension
7558 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007559 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007560 else
7561 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007562 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007563 if (decoration != spv::DecorationMax) {
7564 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7565 }
7566 }
chaoc771d89f2017-01-13 01:10:53 -08007567 else if (builtIn == spv::BuiltInLayer) {
7568 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007569 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007570 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007571 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7572 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7573 }
John Kessenichb41bff62017-08-11 13:07:17 -06007574 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007575 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7576 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007577 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7578 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7579 }
7580 }
7581
chaoc6e5acae2016-12-20 13:28:52 -08007582 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007583 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007584 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007585 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7586 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007587 if (symbol->getQualifier().pervertexNV) {
7588 builder.addDecoration(id, spv::DecorationPerVertexNV);
7589 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7590 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7591 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007592#endif
7593
John Kessenich5d610ee2018-03-07 18:05:55 -07007594 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7595 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7596 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7597 symbol->getType().getQualifier().semanticName);
7598 }
7599
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007600 if (symbol->getBasicType() == glslang::EbtReference) {
7601 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7602 }
7603
John Kessenich140f3df2015-06-26 16:58:36 -06007604 return id;
7605}
7606
Chao Chen3c366992018-09-19 11:41:59 -07007607#ifdef NV_EXTENSIONS
7608// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7609void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7610{
7611 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007612 if (qualifier.perPrimitiveNV) {
7613 // Need to add capability/extension for fragment shader.
7614 // Mesh shader already adds this by default.
7615 if (glslangIntermediate->getStage() == EShLangFragment) {
7616 builder.addCapability(spv::CapabilityMeshShadingNV);
7617 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7618 }
Chao Chen3c366992018-09-19 11:41:59 -07007619 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007620 }
Chao Chen3c366992018-09-19 11:41:59 -07007621 if (qualifier.perViewNV)
7622 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7623 if (qualifier.perTaskNV)
7624 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7625 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007626 if (qualifier.perPrimitiveNV) {
7627 // Need to add capability/extension for fragment shader.
7628 // Mesh shader already adds this by default.
7629 if (glslangIntermediate->getStage() == EShLangFragment) {
7630 builder.addCapability(spv::CapabilityMeshShadingNV);
7631 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7632 }
Chao Chen3c366992018-09-19 11:41:59 -07007633 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007634 }
Chao Chen3c366992018-09-19 11:41:59 -07007635 if (qualifier.perViewNV)
7636 builder.addDecoration(id, spv::DecorationPerViewNV);
7637 if (qualifier.perTaskNV)
7638 builder.addDecoration(id, spv::DecorationPerTaskNV);
7639 }
7640}
7641#endif
7642
John Kessenich55e7d112015-11-15 21:33:39 -07007643// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007644// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007645//
7646// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7647//
7648// Recursively walk the nodes. The nodes form a tree whose leaves are
7649// regular constants, which themselves are trees that createSpvConstant()
7650// recursively walks. So, this function walks the "top" of the tree:
7651// - emit specialization constant-building instructions for specConstant
7652// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007653spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007654{
John Kessenich7cc0e282016-03-20 00:46:02 -06007655 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007656
qining4f4bb812016-04-03 23:55:17 -04007657 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007658 if (! node.getQualifier().specConstant) {
7659 // hand off to the non-spec-constant path
7660 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7661 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007662 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007663 nextConst, false);
7664 }
7665
7666 // We now know we have a specialization constant to build
7667
John Kessenichd94c0032016-05-30 19:29:40 -06007668 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007669 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7670 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7671 std::vector<spv::Id> dimConstId;
7672 for (int dim = 0; dim < 3; ++dim) {
7673 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7674 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007675 if (specConst) {
7676 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7677 glslangIntermediate->getLocalSizeSpecId(dim));
7678 }
qining4f4bb812016-04-03 23:55:17 -04007679 }
7680 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7681 }
7682
7683 // An AST node labelled as specialization constant should be a symbol node.
7684 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7685 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007686 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007687 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007688 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7689 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7690 // will set the builder into spec constant op instruction generating mode.
7691 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007692 result = accessChainLoad(sub_tree->getType());
7693 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007694 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007695 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007696 } else {
7697 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007698 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007699 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007700 builder.addName(result, sn->getName().c_str());
7701 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007702 }
qining4f4bb812016-04-03 23:55:17 -04007703
7704 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7705 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007706 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007707 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007708}
7709
John Kessenich140f3df2015-06-26 16:58:36 -06007710// Use 'consts' as the flattened glslang source of scalar constants to recursively
7711// build the aggregate SPIR-V constant.
7712//
7713// If there are not enough elements present in 'consts', 0 will be substituted;
7714// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7715//
qining08408382016-03-21 09:51:37 -04007716spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007717{
7718 // vector of constants for SPIR-V
7719 std::vector<spv::Id> spvConsts;
7720
7721 // Type is used for struct and array constants
7722 spv::Id typeId = convertGlslangToSpvType(glslangType);
7723
7724 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007725 glslang::TType elementType(glslangType, 0);
7726 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007727 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007728 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007729 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007730 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007731 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007732 } else if (glslangType.isCoopMat()) {
7733 glslang::TType componentType(glslangType.getBasicType());
7734 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007735 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007736 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7737 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007738 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007739 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007740 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7741 bool zero = nextConst >= consts.size();
7742 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007743 case glslang::EbtInt8:
7744 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7745 break;
7746 case glslang::EbtUint8:
7747 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7748 break;
7749 case glslang::EbtInt16:
7750 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7751 break;
7752 case glslang::EbtUint16:
7753 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7754 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007755 case glslang::EbtInt:
7756 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7757 break;
7758 case glslang::EbtUint:
7759 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7760 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007761 case glslang::EbtInt64:
7762 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7763 break;
7764 case glslang::EbtUint64:
7765 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7766 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007767 case glslang::EbtFloat:
7768 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7769 break;
7770 case glslang::EbtDouble:
7771 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7772 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007773 case glslang::EbtFloat16:
7774 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7775 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007776 case glslang::EbtBool:
7777 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7778 break;
7779 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007780 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007781 break;
7782 }
7783 ++nextConst;
7784 }
7785 } else {
7786 // we have a non-aggregate (scalar) constant
7787 bool zero = nextConst >= consts.size();
7788 spv::Id scalar = 0;
7789 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007790 case glslang::EbtInt8:
7791 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7792 break;
7793 case glslang::EbtUint8:
7794 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7795 break;
7796 case glslang::EbtInt16:
7797 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7798 break;
7799 case glslang::EbtUint16:
7800 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7801 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007802 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007803 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007804 break;
7805 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007806 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007807 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007808 case glslang::EbtInt64:
7809 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7810 break;
7811 case glslang::EbtUint64:
7812 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7813 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007814 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007815 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007816 break;
7817 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007818 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007819 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007820 case glslang::EbtFloat16:
7821 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7822 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007823 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007824 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007825 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007826 case glslang::EbtReference:
7827 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7828 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7829 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007830 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007831 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007832 break;
7833 }
7834 ++nextConst;
7835 return scalar;
7836 }
7837
7838 return builder.makeCompositeConstant(typeId, spvConsts);
7839}
7840
John Kessenich7c1aa102015-10-15 13:29:11 -06007841// Return true if the node is a constant or symbol whose reading has no
7842// non-trivial observable cost or effect.
7843bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7844{
7845 // don't know what this is
7846 if (node == nullptr)
7847 return false;
7848
7849 // a constant is safe
7850 if (node->getAsConstantUnion() != nullptr)
7851 return true;
7852
7853 // not a symbol means non-trivial
7854 if (node->getAsSymbolNode() == nullptr)
7855 return false;
7856
7857 // a symbol, depends on what's being read
7858 switch (node->getType().getQualifier().storage) {
7859 case glslang::EvqTemporary:
7860 case glslang::EvqGlobal:
7861 case glslang::EvqIn:
7862 case glslang::EvqInOut:
7863 case glslang::EvqConst:
7864 case glslang::EvqConstReadOnly:
7865 case glslang::EvqUniform:
7866 return true;
7867 default:
7868 return false;
7869 }
qining25262b32016-05-06 17:25:16 -04007870}
John Kessenich7c1aa102015-10-15 13:29:11 -06007871
7872// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007873// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007874// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007875// Return true if trivial.
7876bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7877{
7878 if (node == nullptr)
7879 return false;
7880
John Kessenich84cc15f2017-05-24 16:44:47 -06007881 // count non scalars as trivial, as well as anything coming from HLSL
7882 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007883 return true;
7884
John Kessenich7c1aa102015-10-15 13:29:11 -06007885 // symbols and constants are trivial
7886 if (isTrivialLeaf(node))
7887 return true;
7888
7889 // otherwise, it needs to be a simple operation or one or two leaf nodes
7890
7891 // not a simple operation
7892 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7893 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7894 if (binaryNode == nullptr && unaryNode == nullptr)
7895 return false;
7896
7897 // not on leaf nodes
7898 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7899 return false;
7900
7901 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7902 return false;
7903 }
7904
7905 switch (node->getAsOperator()->getOp()) {
7906 case glslang::EOpLogicalNot:
7907 case glslang::EOpConvIntToBool:
7908 case glslang::EOpConvUintToBool:
7909 case glslang::EOpConvFloatToBool:
7910 case glslang::EOpConvDoubleToBool:
7911 case glslang::EOpEqual:
7912 case glslang::EOpNotEqual:
7913 case glslang::EOpLessThan:
7914 case glslang::EOpGreaterThan:
7915 case glslang::EOpLessThanEqual:
7916 case glslang::EOpGreaterThanEqual:
7917 case glslang::EOpIndexDirect:
7918 case glslang::EOpIndexDirectStruct:
7919 case glslang::EOpLogicalXor:
7920 case glslang::EOpAny:
7921 case glslang::EOpAll:
7922 return true;
7923 default:
7924 return false;
7925 }
7926}
7927
7928// Emit short-circuiting code, where 'right' is never evaluated unless
7929// the left side is true (for &&) or false (for ||).
7930spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7931{
7932 spv::Id boolTypeId = builder.makeBoolType();
7933
7934 // emit left operand
7935 builder.clearAccessChain();
7936 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007937 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007938
7939 // Operands to accumulate OpPhi operands
7940 std::vector<spv::Id> phiOperands;
7941 // accumulate left operand's phi information
7942 phiOperands.push_back(leftId);
7943 phiOperands.push_back(builder.getBuildPoint()->getId());
7944
7945 // Make the two kinds of operation symmetric with a "!"
7946 // || => emit "if (! left) result = right"
7947 // && => emit "if ( left) result = right"
7948 //
7949 // TODO: this runtime "not" for || could be avoided by adding functionality
7950 // to 'builder' to have an "else" without an "then"
7951 if (op == glslang::EOpLogicalOr)
7952 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7953
7954 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007955 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007956
7957 // emit right operand as the "then" part of the "if"
7958 builder.clearAccessChain();
7959 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007960 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007961
7962 // accumulate left operand's phi information
7963 phiOperands.push_back(rightId);
7964 phiOperands.push_back(builder.getBuildPoint()->getId());
7965
7966 // finish the "if"
7967 ifBuilder.makeEndIf();
7968
7969 // phi together the two results
7970 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7971}
7972
Frank Henigman541f7bb2018-01-16 00:18:26 -05007973#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007974// Return type Id of the imported set of extended instructions corresponds to the name.
7975// Import this set if it has not been imported yet.
7976spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7977{
7978 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7979 return extBuiltinMap[name];
7980 else {
Rex Xu51596642016-09-21 18:56:12 +08007981 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007982 spv::Id extBuiltins = builder.import(name);
7983 extBuiltinMap[name] = extBuiltins;
7984 return extBuiltins;
7985 }
7986}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007987#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007988
John Kessenich140f3df2015-06-26 16:58:36 -06007989}; // end anonymous namespace
7990
7991namespace glslang {
7992
John Kessenich68d78fd2015-07-12 19:28:10 -06007993void GetSpirvVersion(std::string& version)
7994{
John Kessenich9e55f632015-07-15 10:03:39 -06007995 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007996 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007997 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007998 version = buf;
7999}
8000
John Kessenicha372a3e2017-11-02 22:32:14 -06008001// For low-order part of the generator's magic number. Bump up
8002// when there is a change in the style (e.g., if SSA form changes,
8003// or a different instruction sequence to do something gets used).
8004int GetSpirvGeneratorVersion()
8005{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07008006 // return 1; // start
8007 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07008008 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07008009 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07008010 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06008011 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
8012 // versions 4 and 6 each generate OpArrayLength as it has long been done
8013 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06008014}
8015
John Kessenich140f3df2015-06-26 16:58:36 -06008016// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008017void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06008018{
8019 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06008020 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008021 if (out.fail())
8022 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06008023 for (int i = 0; i < (int)spirv.size(); ++i) {
8024 unsigned int word = spirv[i];
8025 out.write((const char*)&word, 4);
8026 }
8027 out.close();
8028}
8029
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008030// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08008031void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008032{
8033 std::ofstream out;
8034 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07008035 if (out.fail())
8036 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07008037 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06008038 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07008039 std::endl;
Flavio15017db2017-02-15 14:29:33 -08008040 if (varName != nullptr) {
8041 out << "\t #pragma once" << std::endl;
8042 out << "const uint32_t " << varName << "[] = {" << std::endl;
8043 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008044 const int WORDS_PER_LINE = 8;
8045 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
8046 out << "\t";
8047 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
8048 const unsigned int word = spirv[i + j];
8049 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
8050 if (i + j + 1 < (int)spirv.size()) {
8051 out << ",";
8052 }
8053 }
8054 out << std::endl;
8055 }
Flavio15017db2017-02-15 14:29:33 -08008056 if (varName != nullptr) {
8057 out << "};";
8058 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05008059 out.close();
8060}
8061
John Kessenich140f3df2015-06-26 16:58:36 -06008062//
8063// Set up the glslang traversal
8064//
John Kessenich4e11b612018-08-30 16:56:59 -06008065void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06008066{
Lei Zhang17535f72016-05-04 15:55:59 -04008067 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008068 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008069}
8070
John Kessenich4e11b612018-08-30 16:56:59 -06008071void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008072 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008073{
John Kessenich140f3df2015-06-26 16:58:36 -06008074 TIntermNode* root = intermediate.getTreeRoot();
8075
8076 if (root == 0)
8077 return;
8078
John Kessenich4e11b612018-08-30 16:56:59 -06008079 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008080 if (options == nullptr)
8081 options = &defaultOptions;
8082
John Kessenich4e11b612018-08-30 16:56:59 -06008083 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008084
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008085 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008086 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008087 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008088 it.dumpSpv(spirv);
8089
GregFfb03a552018-03-29 11:49:14 -06008090#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008091 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8092 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06008093 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06008094 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06008095
John Kessenich4e11b612018-08-30 16:56:59 -06008096 if (options->validate)
8097 SpirvToolsValidate(intermediate, spirv, logger);
8098
John Kessenich717c80a2018-08-23 15:17:10 -06008099 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008100 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008101
GregFcd1f1692017-09-21 18:40:22 -06008102#endif
8103
John Kessenich4e11b612018-08-30 16:56:59 -06008104 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008105}
8106
8107}; // end namespace glslang