blob: c12f5bf5637072676ef5458d28c1a6f1933216f6 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
John Kessenichb23d2322018-12-14 10:47:35 -07003// Copyright (C) 2015-2018 Google, Inc.
John Kessenich66011cb2018-03-06 16:12:04 -07004// Copyright (C) 2017 ARM Limited.
John Kessenich140f3df2015-06-26 16:58:36 -06005//
John Kessenich927608b2017-01-06 12:34:14 -07006// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06007//
John Kessenich927608b2017-01-06 12:34:14 -07008// Redistribution and use in source and binary forms, with or without
9// modification, are permitted provided that the following conditions
10// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060011//
12// Redistributions of source code must retain the above copyright
13// notice, this list of conditions and the following disclaimer.
14//
15// Redistributions in binary form must reproduce the above
16// copyright notice, this list of conditions and the following
17// disclaimer in the documentation and/or other materials provided
18// with the distribution.
19//
20// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
21// contributors may be used to endorse or promote products derived
22// from this software without specific prior written permission.
23//
John Kessenich927608b2017-01-06 12:34:14 -070024// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
27// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
28// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
31// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
34// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060036
37//
John Kessenich140f3df2015-06-26 16:58:36 -060038// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080046 #include "GLSL.std.450.h"
47 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070048 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080050 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080051#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080052 #include "GLSL.ext.NV.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
qining4c912612016-04-01 10:35:16 -040071namespace {
72class SpecConstantOpModeGuard {
73public:
74 SpecConstantOpModeGuard(spv::Builder* builder)
75 : builder_(builder) {
76 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040077 }
78 ~SpecConstantOpModeGuard() {
79 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
80 : builder_->setToNormalCodeGenMode();
81 }
qining40887662016-04-03 22:20:42 -040082 void turnOnSpecConstantOpMode() {
83 builder_->setToSpecConstCodeGenMode();
84 }
qining4c912612016-04-01 10:35:16 -040085
86private:
87 spv::Builder* builder_;
88 bool previous_flag_;
89};
John Kessenichead86222018-03-28 18:01:20 -060090
91struct OpDecorations {
92 spv::Decoration precision;
93 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -060094 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -060095};
96
97} // namespace
qining4c912612016-04-01 10:35:16 -040098
John Kessenich140f3df2015-06-26 16:58:36 -060099//
100// The main holder of information for translating glslang to SPIR-V.
101//
102// Derives from the AST walking base class.
103//
104class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
105public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700106 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
107 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700108 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600109
110 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
111 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
112 void visitConstantUnion(glslang::TIntermConstantUnion*);
113 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
114 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
115 void visitSymbol(glslang::TIntermSymbol* symbol);
116 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
117 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
118 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
119
John Kessenichfca82622016-11-26 13:23:20 -0700120 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700121 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600122
123protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700124 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
125 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
126
Rex Xu17ff3432016-10-14 17:41:45 +0800127 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800128 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600129 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500130 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
131 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
132 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
133 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100134 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700135 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700136 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
137 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenich1f4d0462019-01-12 17:31:41 +0700138 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, std::vector<unsigned int>& operands) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600139 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600140 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich140f3df2015-06-26 16:58:36 -0600141 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
142 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600143 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
144 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
145 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600146 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly = false);
John Kessenichead86222018-03-28 18:01:20 -0600147 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600148 bool lastBufferBlockMember, bool forwardReferenceOnly = false);
John Kessenich0e737842017-03-24 18:38:16 -0600149 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600150 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
151 glslang::TLayoutPacking, const glslang::TQualifier&);
152 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
153 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700154 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700155 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800156 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600157 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700158 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700159 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
160 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700161 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
162 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100163 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600164
John Kessenich6fccb3c2016-09-19 16:01:41 -0600165 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600166 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600167 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600168 void makeFunctions(const glslang::TIntermSequence&);
169 void makeGlobalInitializers(const glslang::TIntermSequence&);
170 void visitFunctions(const glslang::TIntermSequence&);
171 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800172 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600173 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
174 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600175 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
176
John Kessenichead86222018-03-28 18:01:20 -0600177 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
178 glslang::TBasicType typeProxy, bool reduceComparison = true);
179 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
180 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
181 glslang::TBasicType typeProxy);
182 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
183 glslang::TBasicType typeProxy);
184 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
185 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600186 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600187 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800188 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800189 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800190 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700191 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600192 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800193 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600194 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700195#ifdef NV_EXTENSIONS
196 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
197#endif
qining08408382016-03-21 09:51:37 -0400198 spv::Id createSpvConstant(const glslang::TIntermTyped&);
199 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600200 bool isTrivialLeaf(const glslang::TIntermTyped* node);
201 bool isTrivial(const glslang::TIntermTyped* node);
202 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500203#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800204 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500205#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700206 void addPre13Extension(const char* ext)
207 {
208 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
209 builder.addExtension(ext);
210 }
John Kessenich140f3df2015-06-26 16:58:36 -0600211
John Kessenich121853f2017-05-31 17:11:16 -0600212 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600213 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600214 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700215 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600216 int sequenceDepth;
217
Lei Zhang17535f72016-05-04 15:55:59 -0400218 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400219
John Kessenich140f3df2015-06-26 16:58:36 -0600220 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
221 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700222 bool inEntryPoint;
223 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700224 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700225 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600226 const glslang::TIntermediate* glslangIntermediate;
227 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800228 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600229
John Kessenich2f273362015-07-18 22:34:27 -0600230 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600231 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600232 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700233 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700234 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
235 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600236 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700237 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
Jeff Bolz9f2aec42019-01-06 17:58:04 -0600238 // Map pointee types for EbtReference to their forward pointers
239 std::map<const glslang::TType *, spv::Id> forwardPointers;
John Kessenich140f3df2015-06-26 16:58:36 -0600240};
241
242//
243// Helper functions for translating glslang representations to SPIR-V enumerants.
244//
245
246// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700247spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600248{
John Kessenich66e2faf2016-03-12 18:34:36 -0700249 switch (source) {
250 case glslang::EShSourceGlsl:
251 switch (profile) {
252 case ENoProfile:
253 case ECoreProfile:
254 case ECompatibilityProfile:
255 return spv::SourceLanguageGLSL;
256 case EEsProfile:
257 return spv::SourceLanguageESSL;
258 default:
259 return spv::SourceLanguageUnknown;
260 }
261 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600262 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600263 default:
264 return spv::SourceLanguageUnknown;
265 }
266}
267
268// Translate glslang language (stage) to SPIR-V execution model.
269spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
270{
271 switch (stage) {
272 case EShLangVertex: return spv::ExecutionModelVertex;
273 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
274 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
275 case EShLangGeometry: return spv::ExecutionModelGeometry;
276 case EShLangFragment: return spv::ExecutionModelFragment;
277 case EShLangCompute: return spv::ExecutionModelGLCompute;
Chao Chen3c366992018-09-19 11:41:59 -0700278#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -0700279 case EShLangRayGenNV: return spv::ExecutionModelRayGenerationNV;
280 case EShLangIntersectNV: return spv::ExecutionModelIntersectionNV;
281 case EShLangAnyHitNV: return spv::ExecutionModelAnyHitNV;
282 case EShLangClosestHitNV: return spv::ExecutionModelClosestHitNV;
283 case EShLangMissNV: return spv::ExecutionModelMissNV;
284 case EShLangCallableNV: return spv::ExecutionModelCallableNV;
Chao Chen3c366992018-09-19 11:41:59 -0700285 case EShLangTaskNV: return spv::ExecutionModelTaskNV;
286 case EShLangMeshNV: return spv::ExecutionModelMeshNV;
287#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600288 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700289 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600290 return spv::ExecutionModelFragment;
291 }
292}
293
John Kessenich140f3df2015-06-26 16:58:36 -0600294// Translate glslang sampler type to SPIR-V dimensionality.
295spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
296{
297 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700298 case glslang::Esd1D: return spv::Dim1D;
299 case glslang::Esd2D: return spv::Dim2D;
300 case glslang::Esd3D: return spv::Dim3D;
301 case glslang::EsdCube: return spv::DimCube;
302 case glslang::EsdRect: return spv::DimRect;
303 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700304 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600305 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700306 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600307 return spv::Dim2D;
308 }
309}
310
John Kessenichf6640762016-08-01 19:44:00 -0600311// Translate glslang precision to SPIR-V precision decorations.
312spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600313{
John Kessenichf6640762016-08-01 19:44:00 -0600314 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700315 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600316 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600317 default:
318 return spv::NoPrecision;
319 }
320}
321
John Kessenichf6640762016-08-01 19:44:00 -0600322// Translate glslang type to SPIR-V precision decorations.
323spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
324{
325 return TranslatePrecisionDecoration(type.getQualifier().precision);
326}
327
John Kessenich140f3df2015-06-26 16:58:36 -0600328// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600329spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600330{
331 if (type.getBasicType() == glslang::EbtBlock) {
332 switch (type.getQualifier().storage) {
333 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600334 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600335 case glslang::EvqVaryingIn: return spv::DecorationBlock;
336 case glslang::EvqVaryingOut: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700337#ifdef NV_EXTENSIONS
338 case glslang::EvqPayloadNV: return spv::DecorationBlock;
339 case glslang::EvqPayloadInNV: return spv::DecorationBlock;
340 case glslang::EvqHitAttrNV: return spv::DecorationBlock;
Ashwin Leleff1783d2018-10-22 16:41:44 -0700341 case glslang::EvqCallableDataNV: return spv::DecorationBlock;
342 case glslang::EvqCallableDataInNV: return spv::DecorationBlock;
Chao Chenb50c02e2018-09-19 11:42:24 -0700343#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600344 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700345 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600346 break;
347 }
348 }
349
John Kessenich4016e382016-07-15 11:53:56 -0600350 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600351}
352
Rex Xu1da878f2016-02-21 20:59:01 +0800353// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500354void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800355{
Jeff Bolz36831c92018-09-05 10:11:41 -0500356 if (!useVulkanMemoryModel) {
357 if (qualifier.coherent)
358 memory.push_back(spv::DecorationCoherent);
359 if (qualifier.volatil) {
360 memory.push_back(spv::DecorationVolatile);
361 memory.push_back(spv::DecorationCoherent);
362 }
John Kessenich14b85d32018-06-04 15:36:03 -0600363 }
Rex Xu1da878f2016-02-21 20:59:01 +0800364 if (qualifier.restrict)
365 memory.push_back(spv::DecorationRestrict);
366 if (qualifier.readonly)
367 memory.push_back(spv::DecorationNonWritable);
368 if (qualifier.writeonly)
369 memory.push_back(spv::DecorationNonReadable);
370}
371
John Kessenich140f3df2015-06-26 16:58:36 -0600372// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700373spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600374{
375 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700376 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600377 case glslang::ElmRowMajor:
378 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700379 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600380 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700381 default:
382 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600383 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600384 }
385 } else {
386 switch (type.getBasicType()) {
387 default:
John Kessenich4016e382016-07-15 11:53:56 -0600388 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600389 break;
390 case glslang::EbtBlock:
391 switch (type.getQualifier().storage) {
392 case glslang::EvqUniform:
393 case glslang::EvqBuffer:
394 switch (type.getQualifier().layoutPacking) {
395 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600396 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
397 default:
John Kessenich4016e382016-07-15 11:53:56 -0600398 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600399 }
400 case glslang::EvqVaryingIn:
401 case glslang::EvqVaryingOut:
Chao Chen3c366992018-09-19 11:41:59 -0700402 if (type.getQualifier().isTaskMemory()) {
403 switch (type.getQualifier().layoutPacking) {
404 case glslang::ElpShared: return spv::DecorationGLSLShared;
405 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
406 default: break;
407 }
408 } else {
409 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
410 }
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
Chao Chenb50c02e2018-09-19 11:42:24 -0700412#ifdef NV_EXTENSIONS
413 case glslang::EvqPayloadNV:
414 case glslang::EvqPayloadInNV:
415 case glslang::EvqHitAttrNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700416 case glslang::EvqCallableDataNV:
417 case glslang::EvqCallableDataInNV:
Chao Chenb50c02e2018-09-19 11:42:24 -0700418 return spv::DecorationMax;
419#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600420 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700421 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600422 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600423 }
424 }
425 }
426}
427
428// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600429// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700430// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800431spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600432{
Rex Xubbceed72016-05-21 09:40:44 +0800433 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700434 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600435 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800436 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700437 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700438 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600439 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800440#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800441 else if (qualifier.explicitInterp) {
442 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800443 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800444 }
Rex Xu9d93a232016-05-05 12:30:44 +0800445#endif
Rex Xubbceed72016-05-21 09:40:44 +0800446 else
John Kessenich4016e382016-07-15 11:53:56 -0600447 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800448}
449
450// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600451// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800452// should be applied.
453spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
454{
455 if (qualifier.patch)
456 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700457 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600458 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700459 else if (qualifier.sample) {
460 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600461 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700462 } else
John Kessenich4016e382016-07-15 11:53:56 -0600463 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600464}
465
John Kessenich92187592016-02-01 13:45:25 -0700466// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700467spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600468{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700469 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600470 return spv::DecorationInvariant;
471 else
John Kessenich4016e382016-07-15 11:53:56 -0600472 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600473}
474
qining9220dbb2016-05-04 17:34:38 -0400475// If glslang type is noContraction, return SPIR-V NoContraction decoration.
476spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
477{
478 if (qualifier.noContraction)
479 return spv::DecorationNoContraction;
480 else
John Kessenich4016e382016-07-15 11:53:56 -0600481 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400482}
483
John Kessenich5611c6d2018-04-05 11:25:02 -0600484// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
485spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
486{
487 if (qualifier.isNonUniform()) {
488 builder.addExtension("SPV_EXT_descriptor_indexing");
489 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
490 return spv::DecorationNonUniformEXT;
491 } else
492 return spv::DecorationMax;
493}
494
Jeff Bolz36831c92018-09-05 10:11:41 -0500495spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
496{
497 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
498 return spv::MemoryAccessMaskNone;
499 }
500 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
501 if (coherentFlags.volatil ||
502 coherentFlags.coherent ||
503 coherentFlags.devicecoherent ||
504 coherentFlags.queuefamilycoherent ||
505 coherentFlags.workgroupcoherent ||
506 coherentFlags.subgroupcoherent) {
507 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
508 spv::MemoryAccessMakePointerVisibleKHRMask;
509 }
510 if (coherentFlags.nonprivate) {
511 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
512 }
513 if (coherentFlags.volatil) {
514 mask = mask | spv::MemoryAccessVolatileMask;
515 }
516 if (mask != spv::MemoryAccessMaskNone) {
517 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
518 }
519 return mask;
520}
521
522spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
523{
524 if (!glslangIntermediate->usingVulkanMemoryModel()) {
525 return spv::ImageOperandsMaskNone;
526 }
527 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
528 if (coherentFlags.volatil ||
529 coherentFlags.coherent ||
530 coherentFlags.devicecoherent ||
531 coherentFlags.queuefamilycoherent ||
532 coherentFlags.workgroupcoherent ||
533 coherentFlags.subgroupcoherent) {
534 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
535 spv::ImageOperandsMakeTexelVisibleKHRMask;
536 }
537 if (coherentFlags.nonprivate) {
538 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
539 }
540 if (coherentFlags.volatil) {
541 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
542 }
543 if (mask != spv::ImageOperandsMaskNone) {
544 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
545 }
546 return mask;
547}
548
549spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
550{
551 spv::Builder::AccessChain::CoherentFlags flags;
552 flags.coherent = type.getQualifier().coherent;
553 flags.devicecoherent = type.getQualifier().devicecoherent;
554 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
555 // shared variables are implicitly workgroupcoherent in GLSL.
556 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
557 type.getQualifier().storage == glslang::EvqShared;
558 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600559 flags.volatil = type.getQualifier().volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500560 // *coherent variables are implicitly nonprivate in GLSL
561 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500562 flags.subgroupcoherent ||
563 flags.workgroupcoherent ||
564 flags.queuefamilycoherent ||
565 flags.devicecoherent ||
Jeff Bolz38cbad12019-03-05 14:40:07 -0600566 flags.coherent ||
567 flags.volatil;
Jeff Bolz36831c92018-09-05 10:11:41 -0500568 flags.isImage = type.getBasicType() == glslang::EbtSampler;
569 return flags;
570}
571
572spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
573{
574 spv::Scope scope;
Jeff Bolz38cbad12019-03-05 14:40:07 -0600575 if (coherentFlags.volatil || coherentFlags.coherent) {
Jeff Bolz36831c92018-09-05 10:11:41 -0500576 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
577 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
578 } else if (coherentFlags.devicecoherent) {
579 scope = spv::ScopeDevice;
580 } else if (coherentFlags.queuefamilycoherent) {
581 scope = spv::ScopeQueueFamilyKHR;
582 } else if (coherentFlags.workgroupcoherent) {
583 scope = spv::ScopeWorkgroup;
584 } else if (coherentFlags.subgroupcoherent) {
585 scope = spv::ScopeSubgroup;
586 } else {
587 scope = spv::ScopeMax;
588 }
589 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
590 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
591 }
592 return scope;
593}
594
David Netoa901ffe2016-06-08 14:11:40 +0100595// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
596// associated capabilities when required. For some built-in variables, a capability
597// is generated only when using the variable in an executable instruction, but not when
598// just declaring a struct member variable with it. This is true for PointSize,
599// ClipDistance, and CullDistance.
600spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600601{
602 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700603 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600604 // Defer adding the capability until the built-in is actually used.
605 if (! memberDeclaration) {
606 switch (glslangIntermediate->getStage()) {
607 case EShLangGeometry:
608 builder.addCapability(spv::CapabilityGeometryPointSize);
609 break;
610 case EShLangTessControl:
611 case EShLangTessEvaluation:
612 builder.addCapability(spv::CapabilityTessellationPointSize);
613 break;
614 default:
615 break;
616 }
John Kessenich92187592016-02-01 13:45:25 -0700617 }
618 return spv::BuiltInPointSize;
619
John Kessenichebb50532016-05-16 19:22:05 -0600620 // These *Distance capabilities logically belong here, but if the member is declared and
621 // then never used, consumers of SPIR-V prefer the capability not be declared.
622 // They are now generated when used, rather than here when declared.
623 // Potentially, the specification should be more clear what the minimum
624 // use needed is to trigger the capability.
625 //
John Kessenich92187592016-02-01 13:45:25 -0700626 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100627 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800628 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700629 return spv::BuiltInClipDistance;
630
631 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100632 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800633 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700634 return spv::BuiltInCullDistance;
635
636 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600637 builder.addCapability(spv::CapabilityMultiViewport);
638 if (glslangIntermediate->getStage() == EShLangVertex ||
639 glslangIntermediate->getStage() == EShLangTessControl ||
640 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800641
John Kessenichba6a3c22017-09-13 13:22:50 -0600642 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
643 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800644 }
John Kessenich92187592016-02-01 13:45:25 -0700645 return spv::BuiltInViewportIndex;
646
John Kessenich5e801132016-02-15 11:09:46 -0700647 case glslang::EbvSampleId:
648 builder.addCapability(spv::CapabilitySampleRateShading);
649 return spv::BuiltInSampleId;
650
651 case glslang::EbvSamplePosition:
652 builder.addCapability(spv::CapabilitySampleRateShading);
653 return spv::BuiltInSamplePosition;
654
655 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700656 return spv::BuiltInSampleMask;
657
John Kessenich78a45572016-07-08 14:05:15 -0600658 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700659#ifdef NV_EXTENSIONS
660 if (glslangIntermediate->getStage() == EShLangMeshNV) {
661 return spv::BuiltInLayer;
662 }
663#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600664 builder.addCapability(spv::CapabilityGeometry);
665 if (glslangIntermediate->getStage() == EShLangVertex ||
666 glslangIntermediate->getStage() == EShLangTessControl ||
667 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800668
John Kessenichba6a3c22017-09-13 13:22:50 -0600669 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
670 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800671 }
John Kessenich78a45572016-07-08 14:05:15 -0600672 return spv::BuiltInLayer;
673
John Kessenich140f3df2015-06-26 16:58:36 -0600674 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600675 case glslang::EbvVertexId: return spv::BuiltInVertexId;
676 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700677 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
678 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800679
John Kessenichda581a22015-10-14 14:10:30 -0600680 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700681 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800682 builder.addCapability(spv::CapabilityDrawParameters);
683 return spv::BuiltInBaseVertex;
684
John Kessenichda581a22015-10-14 14:10:30 -0600685 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700686 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800687 builder.addCapability(spv::CapabilityDrawParameters);
688 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200689
John Kessenichda581a22015-10-14 14:10:30 -0600690 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700691 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800692 builder.addCapability(spv::CapabilityDrawParameters);
693 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200694
695 case glslang::EbvPrimitiveId:
696 if (glslangIntermediate->getStage() == EShLangFragment)
697 builder.addCapability(spv::CapabilityGeometry);
698 return spv::BuiltInPrimitiveId;
699
Rex Xu37cdcee2017-06-29 17:46:34 +0800700 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800701 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
702 builder.addCapability(spv::CapabilityStencilExportEXT);
703 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800704
John Kessenich140f3df2015-06-26 16:58:36 -0600705 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600706 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
707 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
708 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
709 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
710 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
711 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
712 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600713 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
714 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
715 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
716 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
717 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
718 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
719 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
720 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800721
Rex Xu574ab042016-04-14 16:53:07 +0800722 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800723 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800724 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
725 return spv::BuiltInSubgroupSize;
726
Rex Xu574ab042016-04-14 16:53:07 +0800727 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800728 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800729 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
730 return spv::BuiltInSubgroupLocalInvocationId;
731
Rex Xu574ab042016-04-14 16:53:07 +0800732 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800733 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
734 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
735 return spv::BuiltInSubgroupEqMaskKHR;
736
Rex Xu574ab042016-04-14 16:53:07 +0800737 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800738 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
739 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
740 return spv::BuiltInSubgroupGeMaskKHR;
741
Rex Xu574ab042016-04-14 16:53:07 +0800742 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800743 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
744 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
745 return spv::BuiltInSubgroupGtMaskKHR;
746
Rex Xu574ab042016-04-14 16:53:07 +0800747 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800748 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
749 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
750 return spv::BuiltInSubgroupLeMaskKHR;
751
Rex Xu574ab042016-04-14 16:53:07 +0800752 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800753 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
754 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
755 return spv::BuiltInSubgroupLtMaskKHR;
756
John Kessenich66011cb2018-03-06 16:12:04 -0700757 case glslang::EbvNumSubgroups:
758 builder.addCapability(spv::CapabilityGroupNonUniform);
759 return spv::BuiltInNumSubgroups;
760
761 case glslang::EbvSubgroupID:
762 builder.addCapability(spv::CapabilityGroupNonUniform);
763 return spv::BuiltInSubgroupId;
764
765 case glslang::EbvSubgroupSize2:
766 builder.addCapability(spv::CapabilityGroupNonUniform);
767 return spv::BuiltInSubgroupSize;
768
769 case glslang::EbvSubgroupInvocation2:
770 builder.addCapability(spv::CapabilityGroupNonUniform);
771 return spv::BuiltInSubgroupLocalInvocationId;
772
773 case glslang::EbvSubgroupEqMask2:
774 builder.addCapability(spv::CapabilityGroupNonUniform);
775 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
776 return spv::BuiltInSubgroupEqMask;
777
778 case glslang::EbvSubgroupGeMask2:
779 builder.addCapability(spv::CapabilityGroupNonUniform);
780 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
781 return spv::BuiltInSubgroupGeMask;
782
783 case glslang::EbvSubgroupGtMask2:
784 builder.addCapability(spv::CapabilityGroupNonUniform);
785 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
786 return spv::BuiltInSubgroupGtMask;
787
788 case glslang::EbvSubgroupLeMask2:
789 builder.addCapability(spv::CapabilityGroupNonUniform);
790 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
791 return spv::BuiltInSubgroupLeMask;
792
793 case glslang::EbvSubgroupLtMask2:
794 builder.addCapability(spv::CapabilityGroupNonUniform);
795 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
796 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800797#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800798 case glslang::EbvBaryCoordNoPersp:
799 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
800 return spv::BuiltInBaryCoordNoPerspAMD;
801
802 case glslang::EbvBaryCoordNoPerspCentroid:
803 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
804 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
805
806 case glslang::EbvBaryCoordNoPerspSample:
807 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
808 return spv::BuiltInBaryCoordNoPerspSampleAMD;
809
810 case glslang::EbvBaryCoordSmooth:
811 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
812 return spv::BuiltInBaryCoordSmoothAMD;
813
814 case glslang::EbvBaryCoordSmoothCentroid:
815 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
816 return spv::BuiltInBaryCoordSmoothCentroidAMD;
817
818 case glslang::EbvBaryCoordSmoothSample:
819 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
820 return spv::BuiltInBaryCoordSmoothSampleAMD;
821
822 case glslang::EbvBaryCoordPullModel:
823 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
824 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800825#endif
chaoc771d89f2017-01-13 01:10:53 -0800826
John Kessenich6c8aaac2017-02-27 01:20:51 -0700827 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700828 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700829 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700830 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700831
832 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700833 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700834 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700835 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700836
Daniel Koch5154db52018-11-26 10:01:58 -0500837 case glslang::EbvFragSizeEXT:
838 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
839 builder.addCapability(spv::CapabilityFragmentDensityEXT);
840 return spv::BuiltInFragSizeEXT;
841
842 case glslang::EbvFragInvocationCountEXT:
843 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
844 builder.addCapability(spv::CapabilityFragmentDensityEXT);
845 return spv::BuiltInFragInvocationCountEXT;
846
chaoc771d89f2017-01-13 01:10:53 -0800847#ifdef NV_EXTENSIONS
848 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800849 if (!memberDeclaration) {
850 builder.addExtension(spv::E_SPV_NV_viewport_array2);
851 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
852 }
chaoc771d89f2017-01-13 01:10:53 -0800853 return spv::BuiltInViewportMaskNV;
854 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800855 if (!memberDeclaration) {
856 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
857 builder.addCapability(spv::CapabilityShaderStereoViewNV);
858 }
chaoc771d89f2017-01-13 01:10:53 -0800859 return spv::BuiltInSecondaryPositionNV;
860 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800861 if (!memberDeclaration) {
862 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
863 builder.addCapability(spv::CapabilityShaderStereoViewNV);
864 }
chaoc771d89f2017-01-13 01:10:53 -0800865 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800866 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800867 if (!memberDeclaration) {
868 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
869 builder.addCapability(spv::CapabilityPerViewAttributesNV);
870 }
chaocdf3956c2017-02-14 14:52:34 -0800871 return spv::BuiltInPositionPerViewNV;
872 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800873 if (!memberDeclaration) {
874 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
875 builder.addCapability(spv::CapabilityPerViewAttributesNV);
876 }
chaocdf3956c2017-02-14 14:52:34 -0800877 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700878 case glslang::EbvFragFullyCoveredNV:
879 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
880 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
881 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700882 case glslang::EbvFragmentSizeNV:
883 builder.addExtension(spv::E_SPV_NV_shading_rate);
884 builder.addCapability(spv::CapabilityShadingRateNV);
885 return spv::BuiltInFragmentSizeNV;
886 case glslang::EbvInvocationsPerPixelNV:
887 builder.addExtension(spv::E_SPV_NV_shading_rate);
888 builder.addCapability(spv::CapabilityShadingRateNV);
889 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700890
891 // raytracing
892 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700893 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700894 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700895 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700896 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700897 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700898 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700899 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700900 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700901 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700902 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700903 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700904 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700905 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700906 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700907 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700908 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700909 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700910 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700911 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700912 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700913 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700914 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700915 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700916 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700917 return spv::BuiltInWorldToObjectNV;
918 case glslang::EbvIncomingRayFlagsNV:
919 return spv::BuiltInIncomingRayFlagsNV;
Chao Chen9eada4b2018-09-19 11:39:56 -0700920 case glslang::EbvBaryCoordNV:
921 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
922 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
923 return spv::BuiltInBaryCoordNV;
924 case glslang::EbvBaryCoordNoPerspNV:
925 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
926 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
927 return spv::BuiltInBaryCoordNoPerspNV;
Chao Chen3c366992018-09-19 11:41:59 -0700928 case glslang::EbvTaskCountNV:
929 return spv::BuiltInTaskCountNV;
930 case glslang::EbvPrimitiveCountNV:
931 return spv::BuiltInPrimitiveCountNV;
932 case glslang::EbvPrimitiveIndicesNV:
933 return spv::BuiltInPrimitiveIndicesNV;
934 case glslang::EbvClipDistancePerViewNV:
935 return spv::BuiltInClipDistancePerViewNV;
936 case glslang::EbvCullDistancePerViewNV:
937 return spv::BuiltInCullDistancePerViewNV;
938 case glslang::EbvLayerPerViewNV:
939 return spv::BuiltInLayerPerViewNV;
940 case glslang::EbvMeshViewCountNV:
941 return spv::BuiltInMeshViewCountNV;
942 case glslang::EbvMeshViewIndicesNV:
943 return spv::BuiltInMeshViewIndicesNV;
chaoc771d89f2017-01-13 01:10:53 -0800944#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800945 default:
946 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600947 }
948}
949
Rex Xufc618912015-09-09 16:42:49 +0800950// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700951spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800952{
953 assert(type.getBasicType() == glslang::EbtSampler);
954
John Kessenich5d0fa972016-02-15 11:57:00 -0700955 // Check for capabilities
956 switch (type.getQualifier().layoutFormat) {
957 case glslang::ElfRg32f:
958 case glslang::ElfRg16f:
959 case glslang::ElfR11fG11fB10f:
960 case glslang::ElfR16f:
961 case glslang::ElfRgba16:
962 case glslang::ElfRgb10A2:
963 case glslang::ElfRg16:
964 case glslang::ElfRg8:
965 case glslang::ElfR16:
966 case glslang::ElfR8:
967 case glslang::ElfRgba16Snorm:
968 case glslang::ElfRg16Snorm:
969 case glslang::ElfRg8Snorm:
970 case glslang::ElfR16Snorm:
971 case glslang::ElfR8Snorm:
972
973 case glslang::ElfRg32i:
974 case glslang::ElfRg16i:
975 case glslang::ElfRg8i:
976 case glslang::ElfR16i:
977 case glslang::ElfR8i:
978
979 case glslang::ElfRgb10a2ui:
980 case glslang::ElfRg32ui:
981 case glslang::ElfRg16ui:
982 case glslang::ElfRg8ui:
983 case glslang::ElfR16ui:
984 case glslang::ElfR8ui:
985 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
986 break;
987
988 default:
989 break;
990 }
991
992 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800993 switch (type.getQualifier().layoutFormat) {
994 case glslang::ElfNone: return spv::ImageFormatUnknown;
995 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
996 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
997 case glslang::ElfR32f: return spv::ImageFormatR32f;
998 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
999 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
1000 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1001 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1002 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1003 case glslang::ElfR16f: return spv::ImageFormatR16f;
1004 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1005 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1006 case glslang::ElfRg16: return spv::ImageFormatRg16;
1007 case glslang::ElfRg8: return spv::ImageFormatRg8;
1008 case glslang::ElfR16: return spv::ImageFormatR16;
1009 case glslang::ElfR8: return spv::ImageFormatR8;
1010 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1011 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1012 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1013 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1014 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1015 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1016 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1017 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1018 case glslang::ElfR32i: return spv::ImageFormatR32i;
1019 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1020 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1021 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1022 case glslang::ElfR16i: return spv::ImageFormatR16i;
1023 case glslang::ElfR8i: return spv::ImageFormatR8i;
1024 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1025 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1026 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1027 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1028 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1029 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1030 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1031 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1032 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1033 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001034 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001035 }
1036}
1037
John Kesseniche18fd202018-01-30 11:01:39 -07001038spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001039{
John Kesseniche18fd202018-01-30 11:01:39 -07001040 if (selectionNode.getFlatten())
1041 return spv::SelectionControlFlattenMask;
1042 if (selectionNode.getDontFlatten())
1043 return spv::SelectionControlDontFlattenMask;
1044 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001045}
1046
John Kesseniche18fd202018-01-30 11:01:39 -07001047spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001048{
John Kesseniche18fd202018-01-30 11:01:39 -07001049 if (switchNode.getFlatten())
1050 return spv::SelectionControlFlattenMask;
1051 if (switchNode.getDontFlatten())
1052 return spv::SelectionControlDontFlattenMask;
1053 return spv::SelectionControlMaskNone;
1054}
1055
John Kessenicha2858d92018-01-31 08:11:18 -07001056// return a non-0 dependency if the dependency argument must be set
1057spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
John Kessenich1f4d0462019-01-12 17:31:41 +07001058 std::vector<unsigned int>& operands) const
John Kesseniche18fd202018-01-30 11:01:39 -07001059{
1060 spv::LoopControlMask control = spv::LoopControlMaskNone;
1061
1062 if (loopNode.getDontUnroll())
1063 control = control | spv::LoopControlDontUnrollMask;
1064 if (loopNode.getUnroll())
1065 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001066 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001067 control = control | spv::LoopControlDependencyInfiniteMask;
1068 else if (loopNode.getLoopDependency() > 0) {
1069 control = control | spv::LoopControlDependencyLengthMask;
John Kessenich1f4d0462019-01-12 17:31:41 +07001070 operands.push_back((unsigned int)loopNode.getLoopDependency());
1071 }
1072 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
1073 if (loopNode.getMinIterations() > 0) {
1074 control = control | spv::LoopControlMinIterationsMask;
1075 operands.push_back(loopNode.getMinIterations());
1076 }
1077 if (loopNode.getMaxIterations() < glslang::TIntermLoop::iterationsInfinite) {
1078 control = control | spv::LoopControlMaxIterationsMask;
1079 operands.push_back(loopNode.getMaxIterations());
1080 }
1081 if (loopNode.getIterationMultiple() > 1) {
1082 control = control | spv::LoopControlIterationMultipleMask;
1083 operands.push_back(loopNode.getIterationMultiple());
1084 }
1085 if (loopNode.getPeelCount() > 0) {
1086 control = control | spv::LoopControlPeelCountMask;
1087 operands.push_back(loopNode.getPeelCount());
1088 }
1089 if (loopNode.getPartialCount() > 0) {
1090 control = control | spv::LoopControlPartialCountMask;
1091 operands.push_back(loopNode.getPartialCount());
1092 }
John Kessenicha2858d92018-01-31 08:11:18 -07001093 }
John Kesseniche18fd202018-01-30 11:01:39 -07001094
1095 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001096}
1097
John Kessenicha5c5fb62017-05-05 05:09:58 -06001098// Translate glslang type to SPIR-V storage class.
1099spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1100{
1101 if (type.getQualifier().isPipeInput())
1102 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001103 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001104 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001105
1106 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1107 type.getQualifier().storage == glslang::EvqUniform) {
1108 if (type.getBasicType() == glslang::EbtAtomicUint)
1109 return spv::StorageClassAtomicCounter;
1110 if (type.containsOpaque())
1111 return spv::StorageClassUniformConstant;
1112 }
1113
Jeff Bolz61a0cd12018-12-14 20:59:53 -06001114#ifdef NV_EXTENSIONS
1115 if (type.getQualifier().isUniformOrBuffer() &&
1116 type.getQualifier().layoutShaderRecordNV) {
1117 return spv::StorageClassShaderRecordBufferNV;
1118 }
1119#endif
1120
John Kessenichbed4e4f2017-09-08 02:38:07 -06001121 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001122 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001123 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001124 }
1125
1126 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001127 if (type.getQualifier().layoutPushConstant)
1128 return spv::StorageClassPushConstant;
1129 if (type.getBasicType() == glslang::EbtBlock)
1130 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001131 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001132 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001133
1134 switch (type.getQualifier().storage) {
1135 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1136 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1137 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1138 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001139#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001140 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1141 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1142 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1143 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1144 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001145#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001146 default:
1147 assert(0);
1148 break;
1149 }
1150
1151 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001152}
1153
John Kessenich5611c6d2018-04-05 11:25:02 -06001154// Add capabilities pertaining to how an array is indexed.
1155void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1156 const glslang::TType& indexType)
1157{
1158 if (indexType.getQualifier().isNonUniform()) {
1159 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001160 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001161 if (baseType.getBasicType() == glslang::EbtSampler) {
1162 if (baseType.getQualifier().hasAttachment())
1163 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1164 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1165 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1166 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1167 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1168 else if (baseType.isImage())
1169 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1170 else if (baseType.isTexture())
1171 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1172 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1173 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1174 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1175 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1176 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1177 }
1178 } else {
1179 // assume a dynamically uniform index
1180 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001181 if (baseType.getQualifier().hasAttachment()) {
1182 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001183 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001184 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1185 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001186 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001187 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1188 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001189 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001190 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001191 }
1192 }
1193}
1194
qining25262b32016-05-06 17:25:16 -04001195// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001196// descriptor set.
1197bool IsDescriptorResource(const glslang::TType& type)
1198{
John Kessenichf7497e22016-03-08 21:36:22 -07001199 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001200 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001201 return type.getQualifier().isUniformOrBuffer() &&
1202#ifdef NV_EXTENSIONS
1203 ! type.getQualifier().layoutShaderRecordNV &&
1204#endif
1205 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001206
1207 // non block...
1208 // basically samplerXXX/subpass/sampler/texture are all included
1209 // if they are the global-scope-class, not the function parameter
1210 // (or local, if they ever exist) class.
1211 if (type.getBasicType() == glslang::EbtSampler)
1212 return type.getQualifier().isUniformOrBuffer();
1213
1214 // None of the above.
1215 return false;
1216}
1217
John Kesseniche0b6cad2015-12-24 10:30:13 -07001218void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1219{
1220 if (child.layoutMatrix == glslang::ElmNone)
1221 child.layoutMatrix = parent.layoutMatrix;
1222
1223 if (parent.invariant)
1224 child.invariant = true;
1225 if (parent.nopersp)
1226 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001227#ifdef AMD_EXTENSIONS
1228 if (parent.explicitInterp)
1229 child.explicitInterp = true;
1230#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001231 if (parent.flat)
1232 child.flat = true;
1233 if (parent.centroid)
1234 child.centroid = true;
1235 if (parent.patch)
1236 child.patch = true;
1237 if (parent.sample)
1238 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001239 if (parent.coherent)
1240 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001241 if (parent.devicecoherent)
1242 child.devicecoherent = true;
1243 if (parent.queuefamilycoherent)
1244 child.queuefamilycoherent = true;
1245 if (parent.workgroupcoherent)
1246 child.workgroupcoherent = true;
1247 if (parent.subgroupcoherent)
1248 child.subgroupcoherent = true;
1249 if (parent.nonprivate)
1250 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001251 if (parent.volatil)
1252 child.volatil = true;
1253 if (parent.restrict)
1254 child.restrict = true;
1255 if (parent.readonly)
1256 child.readonly = true;
1257 if (parent.writeonly)
1258 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001259#ifdef NV_EXTENSIONS
1260 if (parent.perPrimitiveNV)
1261 child.perPrimitiveNV = true;
1262 if (parent.perViewNV)
1263 child.perViewNV = true;
1264 if (parent.perTaskNV)
1265 child.perTaskNV = true;
1266#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001267}
1268
John Kessenichf2b7f332016-09-01 17:05:23 -06001269bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001270{
John Kessenich7b9fa252016-01-21 18:56:57 -07001271 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001272 // - struct members might inherit from a struct declaration
1273 // (note that non-block structs don't explicitly inherit,
1274 // only implicitly, meaning no decoration involved)
1275 // - affect decorations on the struct members
1276 // (note smooth does not, and expecting something like volatile
1277 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001278 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001279 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001280}
1281
John Kessenich140f3df2015-06-26 16:58:36 -06001282//
1283// Implement the TGlslangToSpvTraverser class.
1284//
1285
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001286TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001287 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1288 : TIntermTraverser(true, false, true),
1289 options(options),
1290 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001291 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001292 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001293 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001294 glslangIntermediate(glslangIntermediate)
1295{
1296 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1297
1298 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001299 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1300 glslangIntermediate->getVersion());
1301
John Kessenich121853f2017-05-31 17:11:16 -06001302 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001303 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001304 builder.setSourceFile(glslangIntermediate->getSourceFile());
1305
1306 // Set the source shader's text. If for SPV version 1.0, include
1307 // a preamble in comments stating the OpModuleProcessed instructions.
1308 // Otherwise, emit those as actual instructions.
1309 std::string text;
1310 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1311 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001312 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001313 text.append("// OpModuleProcessed ");
1314 text.append(processes[p]);
1315 text.append("\n");
1316 } else
1317 builder.addModuleProcessed(processes[p]);
1318 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001319 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001320 text.append("#line 1\n");
1321 text.append(glslangIntermediate->getSourceText());
1322 builder.setSourceText(text);
Greg Fischerd445bb22018-12-06 11:13:15 -07001323 // Pass name and text for all included files
1324 const std::map<std::string, std::string>& include_txt = glslangIntermediate->getIncludeText();
1325 for (auto iItr = include_txt.begin(); iItr != include_txt.end(); ++iItr)
1326 builder.addInclude(iItr->first, iItr->second);
John Kessenich121853f2017-05-31 17:11:16 -06001327 }
John Kessenich140f3df2015-06-26 16:58:36 -06001328 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001329
1330 spv::AddressingModel addressingModel = spv::AddressingModelLogical;
1331 spv::MemoryModel memoryModel = spv::MemoryModelGLSL450;
1332
1333 if (glslangIntermediate->usingPhysicalStorageBuffer()) {
1334 addressingModel = spv::AddressingModelPhysicalStorageBuffer64EXT;
1335 builder.addExtension(spv::E_SPV_EXT_physical_storage_buffer);
1336 builder.addCapability(spv::CapabilityPhysicalStorageBufferAddressesEXT);
1337 };
Jeff Bolz36831c92018-09-05 10:11:41 -05001338 if (glslangIntermediate->usingVulkanMemoryModel()) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001339 memoryModel = spv::MemoryModelVulkanKHR;
1340 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
Jeff Bolz36831c92018-09-05 10:11:41 -05001341 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
Jeff Bolz36831c92018-09-05 10:11:41 -05001342 }
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001343 builder.setMemoryModel(addressingModel, memoryModel);
1344
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001345 if (glslangIntermediate->usingVariablePointers()) {
1346 builder.addCapability(spv::CapabilityVariablePointers);
1347 }
1348
John Kessenicheee9d532016-09-19 18:09:30 -06001349 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1350 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001351
1352 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001353 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1354 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001355 builder.addSourceExtension(it->c_str());
1356
1357 // Add the top-level modes for this shader.
1358
John Kessenich92187592016-02-01 13:45:25 -07001359 if (glslangIntermediate->getXfbMode()) {
1360 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001361 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001362 }
John Kessenich140f3df2015-06-26 16:58:36 -06001363
1364 unsigned int mode;
1365 switch (glslangIntermediate->getStage()) {
1366 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001367 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001368 break;
1369
steve-lunarge7412492017-03-23 11:56:07 -06001370 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001371 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001372 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001373
steve-lunarge7412492017-03-23 11:56:07 -06001374 glslang::TLayoutGeometry primitive;
1375
1376 if (glslangIntermediate->getStage() == EShLangTessControl) {
1377 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1378 primitive = glslangIntermediate->getOutputPrimitive();
1379 } else {
1380 primitive = glslangIntermediate->getInputPrimitive();
1381 }
1382
1383 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001384 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1385 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1386 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001387 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001388 }
John Kessenich4016e382016-07-15 11:53:56 -06001389 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001390 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1391
John Kesseniche6903322015-10-13 16:29:02 -06001392 switch (glslangIntermediate->getVertexSpacing()) {
1393 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1394 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1395 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001396 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001397 }
John Kessenich4016e382016-07-15 11:53:56 -06001398 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001399 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1400
1401 switch (glslangIntermediate->getVertexOrder()) {
1402 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1403 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001404 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001405 }
John Kessenich4016e382016-07-15 11:53:56 -06001406 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001407 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1408
1409 if (glslangIntermediate->getPointMode())
1410 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001411 break;
1412
1413 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001414 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001415 switch (glslangIntermediate->getInputPrimitive()) {
1416 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1417 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1418 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001419 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001420 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001421 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001422 }
John Kessenich4016e382016-07-15 11:53:56 -06001423 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001424 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001425
John Kessenich140f3df2015-06-26 16:58:36 -06001426 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1427
1428 switch (glslangIntermediate->getOutputPrimitive()) {
1429 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1430 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1431 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001432 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001433 }
John Kessenich4016e382016-07-15 11:53:56 -06001434 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001435 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1436 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1437 break;
1438
1439 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001440 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001441 if (glslangIntermediate->getPixelCenterInteger())
1442 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001443
John Kessenich140f3df2015-06-26 16:58:36 -06001444 if (glslangIntermediate->getOriginUpperLeft())
1445 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001446 else
1447 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001448
1449 if (glslangIntermediate->getEarlyFragmentTests())
1450 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1451
chaocc1204522017-06-30 17:14:30 -07001452 if (glslangIntermediate->getPostDepthCoverage()) {
1453 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1454 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1455 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1456 }
1457
John Kesseniche6903322015-10-13 16:29:02 -06001458 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001459 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1460 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001461 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001462 }
John Kessenich4016e382016-07-15 11:53:56 -06001463 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001464 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1465
1466 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1467 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001468 break;
1469
1470 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001471 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001472 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1473 glslangIntermediate->getLocalSize(1),
1474 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001475#ifdef NV_EXTENSIONS
1476 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1477 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1478 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1479 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1480 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1481 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1482 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1483 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1484 }
1485#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001486 break;
1487
Chao Chen3c366992018-09-19 11:41:59 -07001488#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001489 case EShLangRayGenNV:
1490 case EShLangIntersectNV:
1491 case EShLangAnyHitNV:
1492 case EShLangClosestHitNV:
1493 case EShLangMissNV:
1494 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001495 builder.addCapability(spv::CapabilityRayTracingNV);
1496 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001497 break;
Chao Chen3c366992018-09-19 11:41:59 -07001498 case EShLangTaskNV:
1499 case EShLangMeshNV:
1500 builder.addCapability(spv::CapabilityMeshShadingNV);
1501 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1502 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1503 glslangIntermediate->getLocalSize(1),
1504 glslangIntermediate->getLocalSize(2));
1505 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1506 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1507 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1508
1509 switch (glslangIntermediate->getOutputPrimitive()) {
1510 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1511 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1512 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1513 default: mode = spv::ExecutionModeMax; break;
1514 }
1515 if (mode != spv::ExecutionModeMax)
1516 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1517 }
1518 break;
1519#endif
1520
John Kessenich140f3df2015-06-26 16:58:36 -06001521 default:
1522 break;
1523 }
John Kessenich140f3df2015-06-26 16:58:36 -06001524}
1525
John Kessenichfca82622016-11-26 13:23:20 -07001526// Finish creating SPV, after the traversal is complete.
1527void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001528{
John Kessenichf04c51b2018-08-03 15:56:12 -06001529 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001530 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001531 builder.setBuildPoint(shaderEntry->getLastBlock());
1532 builder.leaveFunction();
1533 }
1534
John Kessenich7ba63412015-12-20 17:37:07 -07001535 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001536 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1537 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001538
John Kessenichf04c51b2018-08-03 15:56:12 -06001539 // Add capabilities, extensions, remove unneeded decorations, etc.,
1540 // based on the resulting SPIR-V.
1541 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001542}
1543
John Kessenichfca82622016-11-26 13:23:20 -07001544// Write the SPV into 'out'.
1545void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001546{
John Kessenichfca82622016-11-26 13:23:20 -07001547 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001548}
1549
1550//
1551// Implement the traversal functions.
1552//
1553// Return true from interior nodes to have the external traversal
1554// continue on to children. Return false if children were
1555// already processed.
1556//
1557
1558//
qining25262b32016-05-06 17:25:16 -04001559// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001560// - uniform/input reads
1561// - output writes
1562// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1563// - something simple that degenerates into the last bullet
1564//
1565void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1566{
qining75d1d802016-04-06 14:42:01 -04001567 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1568 if (symbol->getType().getQualifier().isSpecConstant())
1569 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1570
John Kessenich140f3df2015-06-26 16:58:36 -06001571 // getSymbolId() will set up all the IO decorations on the first call.
1572 // Formal function parameters were mapped during makeFunctions().
1573 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001574
1575 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1576 if (builder.isPointer(id)) {
John Kessenich7c7731e2019-01-04 16:47:06 +07001577 // Consider adding to the OpEntryPoint interface list.
1578 // Only looking at structures if they have at least one member.
1579 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0) {
1580 spv::StorageClass sc = builder.getStorageClass(id);
1581 // Before SPIR-V 1.4, we only want to include Input and Output.
1582 // Starting with SPIR-V 1.4, we want all globals.
1583 if ((glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4 && sc != spv::StorageClassFunction) ||
1584 (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)) {
John Kessenich5f77d862017-09-19 11:09:59 -06001585 iOSet.insert(id);
John Kessenich7c7731e2019-01-04 16:47:06 +07001586 }
John Kessenich5f77d862017-09-19 11:09:59 -06001587 }
John Kessenich7ba63412015-12-20 17:37:07 -07001588 }
1589
1590 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001591 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001592 // Prepare to generate code for the access
1593
1594 // L-value chains will be computed left to right. We're on the symbol now,
1595 // which is the left-most part of the access chain, so now is "clear" time,
1596 // followed by setting the base.
1597 builder.clearAccessChain();
1598
1599 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001600 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001601 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001602 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001603 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001604 // These are also pure R-values.
1605 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001606 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001607 builder.setAccessChainRValue(id);
1608 else
1609 builder.setAccessChainLValue(id);
1610 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001611
1612 // Process linkage-only nodes for any special additional interface work.
1613 if (linkageOnly) {
1614 if (glslangIntermediate->getHlslFunctionality1()) {
1615 // Map implicit counter buffers to their originating buffers, which should have been
1616 // seen by now, given earlier pruning of unused counters, and preservation of order
1617 // of declaration.
1618 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1619 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1620 // Save possible originating buffers for counter buffers, keyed by
1621 // making the potential counter-buffer name.
1622 std::string keyName = symbol->getName().c_str();
1623 keyName = glslangIntermediate->addCounterBufferName(keyName);
1624 counterOriginator[keyName] = symbol;
1625 } else {
1626 // Handle a counter buffer, by finding the saved originating buffer.
1627 std::string keyName = symbol->getName().c_str();
1628 auto it = counterOriginator.find(keyName);
1629 if (it != counterOriginator.end()) {
1630 id = getSymbolId(it->second);
1631 if (id != spv::NoResult) {
1632 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001633 if (counterId != spv::NoResult) {
1634 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001635 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001636 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001637 }
1638 }
1639 }
1640 }
1641 }
1642 }
John Kessenich140f3df2015-06-26 16:58:36 -06001643}
1644
1645bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1646{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001647 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001648
qining40887662016-04-03 22:20:42 -04001649 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1650 if (node->getType().getQualifier().isSpecConstant())
1651 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1652
John Kessenich140f3df2015-06-26 16:58:36 -06001653 // First, handle special cases
1654 switch (node->getOp()) {
1655 case glslang::EOpAssign:
1656 case glslang::EOpAddAssign:
1657 case glslang::EOpSubAssign:
1658 case glslang::EOpMulAssign:
1659 case glslang::EOpVectorTimesMatrixAssign:
1660 case glslang::EOpVectorTimesScalarAssign:
1661 case glslang::EOpMatrixTimesScalarAssign:
1662 case glslang::EOpMatrixTimesMatrixAssign:
1663 case glslang::EOpDivAssign:
1664 case glslang::EOpModAssign:
1665 case glslang::EOpAndAssign:
1666 case glslang::EOpInclusiveOrAssign:
1667 case glslang::EOpExclusiveOrAssign:
1668 case glslang::EOpLeftShiftAssign:
1669 case glslang::EOpRightShiftAssign:
1670 // A bin-op assign "a += b" means the same thing as "a = a + b"
1671 // where a is evaluated before b. For a simple assignment, GLSL
1672 // says to evaluate the left before the right. So, always, left
1673 // node then right node.
1674 {
1675 // get the left l-value, save it away
1676 builder.clearAccessChain();
1677 node->getLeft()->traverse(this);
1678 spv::Builder::AccessChain lValue = builder.getAccessChain();
1679
1680 // evaluate the right
1681 builder.clearAccessChain();
1682 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001683 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001684
1685 if (node->getOp() != glslang::EOpAssign) {
1686 // the left is also an r-value
1687 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001688 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001689
1690 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001691 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001692 TranslateNoContractionDecoration(node->getType().getQualifier()),
1693 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001694 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001695 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1696 node->getType().getBasicType());
1697
1698 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001699 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001700 }
1701
1702 // store the result
1703 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001704 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001705
1706 // assignments are expressions having an rValue after they are evaluated...
1707 builder.clearAccessChain();
1708 builder.setAccessChainRValue(rValue);
1709 }
1710 return false;
1711 case glslang::EOpIndexDirect:
1712 case glslang::EOpIndexDirectStruct:
1713 {
1714 // Get the left part of the access chain.
1715 node->getLeft()->traverse(this);
1716
1717 // Add the next element in the chain
1718
David Netoa901ffe2016-06-08 14:11:40 +01001719 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001720 if (! node->getLeft()->getType().isArray() &&
1721 node->getLeft()->getType().isVector() &&
1722 node->getOp() == glslang::EOpIndexDirect) {
1723 // This is essentially a hard-coded vector swizzle of size 1,
1724 // so short circuit the access-chain stuff with a swizzle.
1725 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001726 swizzle.push_back(glslangIndex);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001727 int dummySize;
1728 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1729 TranslateCoherent(node->getLeft()->getType()),
1730 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001731 } else {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001732
1733 // Load through a block reference is performed with a dot operator that
1734 // is mapped to EOpIndexDirectStruct. When we get to the actual reference,
1735 // do a load and reset the access chain.
1736 if (node->getLeft()->getBasicType() == glslang::EbtReference &&
1737 !node->getLeft()->getType().isArray() &&
1738 node->getOp() == glslang::EOpIndexDirectStruct)
1739 {
1740 spv::Id left = accessChainLoad(node->getLeft()->getType());
1741 builder.clearAccessChain();
1742 builder.setAccessChainLValue(left);
1743 }
1744
David Netoa901ffe2016-06-08 14:11:40 +01001745 int spvIndex = glslangIndex;
1746 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1747 node->getOp() == glslang::EOpIndexDirectStruct)
1748 {
1749 // This may be, e.g., an anonymous block-member selection, which generally need
1750 // index remapping due to hidden members in anonymous blocks.
1751 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1752 assert(remapper.size() > 0);
1753 spvIndex = remapper[glslangIndex];
1754 }
John Kessenichebb50532016-05-16 19:22:05 -06001755
David Netoa901ffe2016-06-08 14:11:40 +01001756 // normal case for indexing array or structure or block
Jeff Bolz7895e472019-03-06 13:34:10 -06001757 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
David Netoa901ffe2016-06-08 14:11:40 +01001758
1759 // Add capabilities here for accessing PointSize and clip/cull distance.
1760 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001761 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001762 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001763 }
1764 }
1765 return false;
1766 case glslang::EOpIndexIndirect:
1767 {
1768 // Structure or array or vector indirection.
1769 // Will use native SPIR-V access-chain for struct and array indirection;
1770 // matrices are arrays of vectors, so will also work for a matrix.
1771 // Will use the access chain's 'component' for variable index into a vector.
1772
1773 // This adapter is building access chains left to right.
1774 // Set up the access chain to the left.
1775 node->getLeft()->traverse(this);
1776
1777 // save it so that computing the right side doesn't trash it
1778 spv::Builder::AccessChain partial = builder.getAccessChain();
1779
1780 // compute the next index in the chain
1781 builder.clearAccessChain();
1782 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001783 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001784
John Kessenich5611c6d2018-04-05 11:25:02 -06001785 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1786
John Kessenich140f3df2015-06-26 16:58:36 -06001787 // restore the saved access chain
1788 builder.setAccessChain(partial);
1789
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001790 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector()) {
1791 int dummySize;
1792 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()),
1793 TranslateCoherent(node->getLeft()->getType()),
1794 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
1795 } else
Jeff Bolz7895e472019-03-06 13:34:10 -06001796 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()), node->getLeft()->getType().getBufferReferenceAlignment());
John Kessenich140f3df2015-06-26 16:58:36 -06001797 }
1798 return false;
1799 case glslang::EOpVectorSwizzle:
1800 {
1801 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001802 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001803 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06001804 int dummySize;
1805 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()),
1806 TranslateCoherent(node->getLeft()->getType()),
1807 glslangIntermediate->getBaseAlignmentScalar(node->getLeft()->getType(), dummySize));
John Kessenich140f3df2015-06-26 16:58:36 -06001808 }
1809 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001810 case glslang::EOpMatrixSwizzle:
1811 logger->missingFunctionality("matrix swizzle");
1812 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001813 case glslang::EOpLogicalOr:
1814 case glslang::EOpLogicalAnd:
1815 {
1816
1817 // These may require short circuiting, but can sometimes be done as straight
1818 // binary operations. The right operand must be short circuited if it has
1819 // side effects, and should probably be if it is complex.
1820 if (isTrivial(node->getRight()->getAsTyped()))
1821 break; // handle below as a normal binary operation
1822 // otherwise, we need to do dynamic short circuiting on the right operand
1823 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1824 builder.clearAccessChain();
1825 builder.setAccessChainRValue(result);
1826 }
1827 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001828 default:
1829 break;
1830 }
1831
1832 // Assume generic binary op...
1833
John Kessenich32cfd492016-02-02 12:37:46 -07001834 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001835 builder.clearAccessChain();
1836 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001837 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001838
John Kessenich32cfd492016-02-02 12:37:46 -07001839 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001840 builder.clearAccessChain();
1841 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001842 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001843
John Kessenich32cfd492016-02-02 12:37:46 -07001844 // get result
John Kessenichead86222018-03-28 18:01:20 -06001845 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001846 TranslateNoContractionDecoration(node->getType().getQualifier()),
1847 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001848 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001849 convertGlslangToSpvType(node->getType()), left, right,
1850 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001851
John Kessenich50e57562015-12-21 21:21:11 -07001852 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001853 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001854 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001855 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001856 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001857 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001858 return false;
1859 }
John Kessenich140f3df2015-06-26 16:58:36 -06001860}
1861
1862bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1863{
greg-lunarg5d43c4a2018-12-07 17:36:33 -07001864 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06001865
qining40887662016-04-03 22:20:42 -04001866 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1867 if (node->getType().getQualifier().isSpecConstant())
1868 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1869
John Kessenichfc51d282015-08-19 13:34:18 -06001870 spv::Id result = spv::NoResult;
1871
1872 // try texturing first
1873 result = createImageTextureFunctionCall(node);
1874 if (result != spv::NoResult) {
1875 builder.clearAccessChain();
1876 builder.setAccessChainRValue(result);
1877
1878 return false; // done with this node
1879 }
1880
1881 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001882
1883 if (node->getOp() == glslang::EOpArrayLength) {
1884 // Quite special; won't want to evaluate the operand.
1885
John Kessenich5611c6d2018-04-05 11:25:02 -06001886 // Currently, the front-end does not allow .length() on an array until it is sized,
1887 // except for the last block membeor of an SSBO.
1888 // TODO: If this changes, link-time sized arrays might show up here, and need their
1889 // size extracted.
1890
John Kessenichc9a80832015-09-12 12:17:44 -06001891 // Normal .length() would have been constant folded by the front-end.
1892 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001893 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001894
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001895 spv::Id length;
1896 if (node->getOperand()->getType().isCoopMat()) {
1897 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1898
1899 spv::Id typeId = convertGlslangToSpvType(node->getOperand()->getType());
1900 assert(builder.isCooperativeMatrixType(typeId));
1901
1902 length = builder.createCooperativeMatrixLength(typeId);
1903 } else {
1904 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1905 block->traverse(this);
1906 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1907 length = builder.createArrayLength(builder.accessChainGetLValue(), member);
1908 }
John Kessenichc9a80832015-09-12 12:17:44 -06001909
John Kessenich8c869672018-11-28 07:01:37 -07001910 // GLSL semantics say the result of .length() is an int, while SPIR-V says
1911 // signedness must be 0. So, convert from SPIR-V unsigned back to GLSL's
1912 // AST expectation of a signed result.
Jeff Bolz4605e2e2019-02-19 13:10:32 -06001913 if (glslangIntermediate->getSource() == glslang::EShSourceGlsl) {
1914 if (builder.isInSpecConstCodeGenMode()) {
1915 length = builder.createBinOp(spv::OpIAdd, builder.makeIntType(32), length, builder.makeIntConstant(0));
1916 } else {
1917 length = builder.createUnaryOp(spv::OpBitcast, builder.makeIntType(32), length);
1918 }
1919 }
John Kessenich8c869672018-11-28 07:01:37 -07001920
John Kessenichc9a80832015-09-12 12:17:44 -06001921 builder.clearAccessChain();
1922 builder.setAccessChainRValue(length);
1923
1924 return false;
1925 }
1926
John Kessenichfc51d282015-08-19 13:34:18 -06001927 // Start by evaluating the operand
1928
John Kessenich8c8505c2016-07-26 12:50:38 -06001929 // Does it need a swizzle inversion? If so, evaluation is inverted;
1930 // operate first on the swizzle base, then apply the swizzle.
1931 spv::Id invertedType = spv::NoType;
1932 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1933 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1934 invertedType = getInvertedSwizzleType(*node->getOperand());
1935
John Kessenich140f3df2015-06-26 16:58:36 -06001936 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001937 if (invertedType != spv::NoType)
1938 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1939 else
1940 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001941
Rex Xufc618912015-09-09 16:42:49 +08001942 spv::Id operand = spv::NoResult;
1943
1944 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1945 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001946 node->getOp() == glslang::EOpAtomicCounter ||
1947 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001948 operand = builder.accessChainGetLValue(); // Special case l-value operands
1949 else
John Kessenich32cfd492016-02-02 12:37:46 -07001950 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001951
John Kessenichead86222018-03-28 18:01:20 -06001952 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001953 TranslateNoContractionDecoration(node->getType().getQualifier()),
1954 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001955
1956 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001957 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001958 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001959
1960 // if not, then possibly an operation
1961 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001962 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001963
1964 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001965 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001966 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001967 builder.addDecoration(result, decorations.nonUniform);
1968 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001969
John Kessenich140f3df2015-06-26 16:58:36 -06001970 builder.clearAccessChain();
1971 builder.setAccessChainRValue(result);
1972
1973 return false; // done with this node
1974 }
1975
1976 // it must be a special case, check...
1977 switch (node->getOp()) {
1978 case glslang::EOpPostIncrement:
1979 case glslang::EOpPostDecrement:
1980 case glslang::EOpPreIncrement:
1981 case glslang::EOpPreDecrement:
1982 {
1983 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001984 spv::Id one = 0;
1985 if (node->getBasicType() == glslang::EbtFloat)
1986 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001987 else if (node->getBasicType() == glslang::EbtDouble)
1988 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001989 else if (node->getBasicType() == glslang::EbtFloat16)
1990 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001991 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1992 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001993 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1994 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001995 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1996 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001997 else
1998 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001999 glslang::TOperator op;
2000 if (node->getOp() == glslang::EOpPreIncrement ||
2001 node->getOp() == glslang::EOpPostIncrement)
2002 op = glslang::EOpAdd;
2003 else
2004 op = glslang::EOpSub;
2005
John Kessenichead86222018-03-28 18:01:20 -06002006 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08002007 convertGlslangToSpvType(node->getType()), operand, one,
2008 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07002009 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002010
2011 // The result of operation is always stored, but conditionally the
2012 // consumed result. The consumed result is always an r-value.
2013 builder.accessChainStore(result);
2014 builder.clearAccessChain();
2015 if (node->getOp() == glslang::EOpPreIncrement ||
2016 node->getOp() == glslang::EOpPreDecrement)
2017 builder.setAccessChainRValue(result);
2018 else
2019 builder.setAccessChainRValue(operand);
2020 }
2021
2022 return false;
2023
2024 case glslang::EOpEmitStreamVertex:
2025 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
2026 return false;
2027 case glslang::EOpEndStreamPrimitive:
2028 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
2029 return false;
2030
2031 default:
Lei Zhang17535f72016-05-04 15:55:59 -04002032 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07002033 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06002034 }
John Kessenich140f3df2015-06-26 16:58:36 -06002035}
2036
2037bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
2038{
qining27e04a02016-04-14 16:40:20 -04002039 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2040 if (node->getType().getQualifier().isSpecConstant())
2041 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2042
John Kessenichfc51d282015-08-19 13:34:18 -06002043 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06002044 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
2045 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06002046
2047 // try texturing
2048 result = createImageTextureFunctionCall(node);
2049 if (result != spv::NoResult) {
2050 builder.clearAccessChain();
2051 builder.setAccessChainRValue(result);
2052
2053 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05002054 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08002055#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05002056 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08002057#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05002058 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08002059 // "imageStore" is a special case, which has no result
2060 return false;
2061 }
John Kessenichfc51d282015-08-19 13:34:18 -06002062
John Kessenich140f3df2015-06-26 16:58:36 -06002063 glslang::TOperator binOp = glslang::EOpNull;
2064 bool reduceComparison = true;
2065 bool isMatrix = false;
2066 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06002067 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002068
2069 assert(node->getOp());
2070
John Kessenichf6640762016-08-01 19:44:00 -06002071 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06002072
2073 switch (node->getOp()) {
2074 case glslang::EOpSequence:
2075 {
2076 if (preVisit)
2077 ++sequenceDepth;
2078 else
2079 --sequenceDepth;
2080
2081 if (sequenceDepth == 1) {
2082 // If this is the parent node of all the functions, we want to see them
2083 // early, so all call points have actual SPIR-V functions to reference.
2084 // In all cases, still let the traverser visit the children for us.
2085 makeFunctions(node->getAsAggregate()->getSequence());
2086
John Kessenich6fccb3c2016-09-19 16:01:41 -06002087 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06002088 // anything else gets there, so visit out of order, doing them all now.
2089 makeGlobalInitializers(node->getAsAggregate()->getSequence());
2090
John Kessenich6a60c2f2016-12-08 21:01:59 -07002091 // 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 -06002092 // so do them manually.
2093 visitFunctions(node->getAsAggregate()->getSequence());
2094
2095 return false;
2096 }
2097
2098 return true;
2099 }
2100 case glslang::EOpLinkerObjects:
2101 {
2102 if (visit == glslang::EvPreVisit)
2103 linkageOnly = true;
2104 else
2105 linkageOnly = false;
2106
2107 return true;
2108 }
2109 case glslang::EOpComma:
2110 {
2111 // processing from left to right naturally leaves the right-most
2112 // lying around in the access chain
2113 glslang::TIntermSequence& glslangOperands = node->getSequence();
2114 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2115 glslangOperands[i]->traverse(this);
2116
2117 return false;
2118 }
2119 case glslang::EOpFunction:
2120 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002121 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002122 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002123 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002124 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002125 } else {
2126 handleFunctionEntry(node);
2127 }
2128 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002129 if (inEntryPoint)
2130 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002131 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002132 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002133 }
2134
2135 return true;
2136 case glslang::EOpParameters:
2137 // Parameters will have been consumed by EOpFunction processing, but not
2138 // the body, so we still visited the function node's children, making this
2139 // child redundant.
2140 return false;
2141 case glslang::EOpFunctionCall:
2142 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002143 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002144 if (node->isUserDefined())
2145 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002146 // 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 -07002147 if (result) {
2148 builder.clearAccessChain();
2149 builder.setAccessChainRValue(result);
2150 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002151 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002152
2153 return false;
2154 }
2155 case glslang::EOpConstructMat2x2:
2156 case glslang::EOpConstructMat2x3:
2157 case glslang::EOpConstructMat2x4:
2158 case glslang::EOpConstructMat3x2:
2159 case glslang::EOpConstructMat3x3:
2160 case glslang::EOpConstructMat3x4:
2161 case glslang::EOpConstructMat4x2:
2162 case glslang::EOpConstructMat4x3:
2163 case glslang::EOpConstructMat4x4:
2164 case glslang::EOpConstructDMat2x2:
2165 case glslang::EOpConstructDMat2x3:
2166 case glslang::EOpConstructDMat2x4:
2167 case glslang::EOpConstructDMat3x2:
2168 case glslang::EOpConstructDMat3x3:
2169 case glslang::EOpConstructDMat3x4:
2170 case glslang::EOpConstructDMat4x2:
2171 case glslang::EOpConstructDMat4x3:
2172 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002173 case glslang::EOpConstructIMat2x2:
2174 case glslang::EOpConstructIMat2x3:
2175 case glslang::EOpConstructIMat2x4:
2176 case glslang::EOpConstructIMat3x2:
2177 case glslang::EOpConstructIMat3x3:
2178 case glslang::EOpConstructIMat3x4:
2179 case glslang::EOpConstructIMat4x2:
2180 case glslang::EOpConstructIMat4x3:
2181 case glslang::EOpConstructIMat4x4:
2182 case glslang::EOpConstructUMat2x2:
2183 case glslang::EOpConstructUMat2x3:
2184 case glslang::EOpConstructUMat2x4:
2185 case glslang::EOpConstructUMat3x2:
2186 case glslang::EOpConstructUMat3x3:
2187 case glslang::EOpConstructUMat3x4:
2188 case glslang::EOpConstructUMat4x2:
2189 case glslang::EOpConstructUMat4x3:
2190 case glslang::EOpConstructUMat4x4:
2191 case glslang::EOpConstructBMat2x2:
2192 case glslang::EOpConstructBMat2x3:
2193 case glslang::EOpConstructBMat2x4:
2194 case glslang::EOpConstructBMat3x2:
2195 case glslang::EOpConstructBMat3x3:
2196 case glslang::EOpConstructBMat3x4:
2197 case glslang::EOpConstructBMat4x2:
2198 case glslang::EOpConstructBMat4x3:
2199 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002200 case glslang::EOpConstructF16Mat2x2:
2201 case glslang::EOpConstructF16Mat2x3:
2202 case glslang::EOpConstructF16Mat2x4:
2203 case glslang::EOpConstructF16Mat3x2:
2204 case glslang::EOpConstructF16Mat3x3:
2205 case glslang::EOpConstructF16Mat3x4:
2206 case glslang::EOpConstructF16Mat4x2:
2207 case glslang::EOpConstructF16Mat4x3:
2208 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002209 isMatrix = true;
2210 // fall through
2211 case glslang::EOpConstructFloat:
2212 case glslang::EOpConstructVec2:
2213 case glslang::EOpConstructVec3:
2214 case glslang::EOpConstructVec4:
2215 case glslang::EOpConstructDouble:
2216 case glslang::EOpConstructDVec2:
2217 case glslang::EOpConstructDVec3:
2218 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002219 case glslang::EOpConstructFloat16:
2220 case glslang::EOpConstructF16Vec2:
2221 case glslang::EOpConstructF16Vec3:
2222 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002223 case glslang::EOpConstructBool:
2224 case glslang::EOpConstructBVec2:
2225 case glslang::EOpConstructBVec3:
2226 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002227 case glslang::EOpConstructInt8:
2228 case glslang::EOpConstructI8Vec2:
2229 case glslang::EOpConstructI8Vec3:
2230 case glslang::EOpConstructI8Vec4:
2231 case glslang::EOpConstructUint8:
2232 case glslang::EOpConstructU8Vec2:
2233 case glslang::EOpConstructU8Vec3:
2234 case glslang::EOpConstructU8Vec4:
2235 case glslang::EOpConstructInt16:
2236 case glslang::EOpConstructI16Vec2:
2237 case glslang::EOpConstructI16Vec3:
2238 case glslang::EOpConstructI16Vec4:
2239 case glslang::EOpConstructUint16:
2240 case glslang::EOpConstructU16Vec2:
2241 case glslang::EOpConstructU16Vec3:
2242 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002243 case glslang::EOpConstructInt:
2244 case glslang::EOpConstructIVec2:
2245 case glslang::EOpConstructIVec3:
2246 case glslang::EOpConstructIVec4:
2247 case glslang::EOpConstructUint:
2248 case glslang::EOpConstructUVec2:
2249 case glslang::EOpConstructUVec3:
2250 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002251 case glslang::EOpConstructInt64:
2252 case glslang::EOpConstructI64Vec2:
2253 case glslang::EOpConstructI64Vec3:
2254 case glslang::EOpConstructI64Vec4:
2255 case glslang::EOpConstructUint64:
2256 case glslang::EOpConstructU64Vec2:
2257 case glslang::EOpConstructU64Vec3:
2258 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002259 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002260 case glslang::EOpConstructTextureSampler:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06002261 case glslang::EOpConstructReference:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002262 case glslang::EOpConstructCooperativeMatrix:
John Kessenich140f3df2015-06-26 16:58:36 -06002263 {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002264 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich140f3df2015-06-26 16:58:36 -06002265 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002266 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002267 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002268 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002269 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002270 else if (node->getOp() == glslang::EOpConstructStruct ||
2271 node->getOp() == glslang::EOpConstructCooperativeMatrix ||
2272 node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002273 std::vector<spv::Id> constituents;
2274 for (int c = 0; c < (int)arguments.size(); ++c)
2275 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002276 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002277 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002278 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002279 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002280 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002281
2282 builder.clearAccessChain();
2283 builder.setAccessChainRValue(constructed);
2284
2285 return false;
2286 }
2287
2288 // These six are component-wise compares with component-wise results.
2289 // Forward on to createBinaryOperation(), requesting a vector result.
2290 case glslang::EOpLessThan:
2291 case glslang::EOpGreaterThan:
2292 case glslang::EOpLessThanEqual:
2293 case glslang::EOpGreaterThanEqual:
2294 case glslang::EOpVectorEqual:
2295 case glslang::EOpVectorNotEqual:
2296 {
2297 // Map the operation to a binary
2298 binOp = node->getOp();
2299 reduceComparison = false;
2300 switch (node->getOp()) {
2301 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2302 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2303 default: binOp = node->getOp(); break;
2304 }
2305
2306 break;
2307 }
2308 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002309 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002310 binOp = glslang::EOpMul;
2311 break;
2312 case glslang::EOpOuterProduct:
2313 // two vectors multiplied to make a matrix
2314 binOp = glslang::EOpOuterProduct;
2315 break;
2316 case glslang::EOpDot:
2317 {
qining25262b32016-05-06 17:25:16 -04002318 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002319 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002320 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002321 binOp = glslang::EOpMul;
2322 break;
2323 }
2324 case glslang::EOpMod:
2325 // when an aggregate, this is the floating-point mod built-in function,
2326 // which can be emitted by the one in createBinaryOperation()
2327 binOp = glslang::EOpMod;
2328 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002329 case glslang::EOpEmitVertex:
2330 case glslang::EOpEndPrimitive:
2331 case glslang::EOpBarrier:
2332 case glslang::EOpMemoryBarrier:
2333 case glslang::EOpMemoryBarrierAtomicCounter:
2334 case glslang::EOpMemoryBarrierBuffer:
2335 case glslang::EOpMemoryBarrierImage:
2336 case glslang::EOpMemoryBarrierShared:
2337 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002338 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002339 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002340 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002341 case glslang::EOpWorkgroupMemoryBarrier:
2342 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002343 case glslang::EOpSubgroupBarrier:
2344 case glslang::EOpSubgroupMemoryBarrier:
2345 case glslang::EOpSubgroupMemoryBarrierBuffer:
2346 case glslang::EOpSubgroupMemoryBarrierImage:
2347 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002348 noReturnValue = true;
2349 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2350 break;
2351
Jeff Bolz36831c92018-09-05 10:11:41 -05002352 case glslang::EOpAtomicStore:
2353 noReturnValue = true;
2354 // fallthrough
2355 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002356 case glslang::EOpAtomicAdd:
2357 case glslang::EOpAtomicMin:
2358 case glslang::EOpAtomicMax:
2359 case glslang::EOpAtomicAnd:
2360 case glslang::EOpAtomicOr:
2361 case glslang::EOpAtomicXor:
2362 case glslang::EOpAtomicExchange:
2363 case glslang::EOpAtomicCompSwap:
2364 atomic = true;
2365 break;
2366
John Kessenich0d0c6d32017-07-23 16:08:26 -06002367 case glslang::EOpAtomicCounterAdd:
2368 case glslang::EOpAtomicCounterSubtract:
2369 case glslang::EOpAtomicCounterMin:
2370 case glslang::EOpAtomicCounterMax:
2371 case glslang::EOpAtomicCounterAnd:
2372 case glslang::EOpAtomicCounterOr:
2373 case glslang::EOpAtomicCounterXor:
2374 case glslang::EOpAtomicCounterExchange:
2375 case glslang::EOpAtomicCounterCompSwap:
2376 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2377 builder.addCapability(spv::CapabilityAtomicStorageOps);
2378 atomic = true;
2379 break;
2380
Chao Chen3c366992018-09-19 11:41:59 -07002381#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002382 case glslang::EOpIgnoreIntersectionNV:
2383 case glslang::EOpTerminateRayNV:
2384 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002385 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002386 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2387 noReturnValue = true;
2388 break;
2389#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002390 case glslang::EOpCooperativeMatrixLoad:
2391 case glslang::EOpCooperativeMatrixStore:
2392 noReturnValue = true;
2393 break;
Chao Chen3c366992018-09-19 11:41:59 -07002394
John Kessenich140f3df2015-06-26 16:58:36 -06002395 default:
2396 break;
2397 }
2398
2399 //
2400 // See if it maps to a regular operation.
2401 //
John Kessenich140f3df2015-06-26 16:58:36 -06002402 if (binOp != glslang::EOpNull) {
2403 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2404 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2405 assert(left && right);
2406
2407 builder.clearAccessChain();
2408 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002409 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002410
2411 builder.clearAccessChain();
2412 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002413 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002414
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002415 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenichead86222018-03-28 18:01:20 -06002416 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002417 TranslateNoContractionDecoration(node->getType().getQualifier()),
2418 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002419 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002420 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002421 left->getType().getBasicType(), reduceComparison);
2422
2423 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002424 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002425 builder.clearAccessChain();
2426 builder.setAccessChainRValue(result);
2427
2428 return false;
2429 }
2430
John Kessenich426394d2015-07-23 10:22:48 -06002431 //
2432 // Create the list of operands.
2433 //
John Kessenich140f3df2015-06-26 16:58:36 -06002434 glslang::TIntermSequence& glslangOperands = node->getSequence();
2435 std::vector<spv::Id> operands;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002436 std::vector<spv::IdImmediate> memoryAccessOperands;
John Kessenich140f3df2015-06-26 16:58:36 -06002437 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002438 // special case l-value operands; there are just a few
2439 bool lvalue = false;
2440 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002441 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002442 case glslang::EOpModf:
2443 if (arg == 1)
2444 lvalue = true;
2445 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002446 case glslang::EOpInterpolateAtSample:
2447 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002448#ifdef AMD_EXTENSIONS
2449 case glslang::EOpInterpolateAtVertex:
2450#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002451 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002452 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002453
2454 // Does it need a swizzle inversion? If so, evaluation is inverted;
2455 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002456 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002457 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2458 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2459 }
Rex Xu7a26c172015-12-08 17:12:09 +08002460 break;
Rex Xud4782c12015-09-06 16:30:11 +08002461 case glslang::EOpAtomicAdd:
2462 case glslang::EOpAtomicMin:
2463 case glslang::EOpAtomicMax:
2464 case glslang::EOpAtomicAnd:
2465 case glslang::EOpAtomicOr:
2466 case glslang::EOpAtomicXor:
2467 case glslang::EOpAtomicExchange:
2468 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002469 case glslang::EOpAtomicLoad:
2470 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002471 case glslang::EOpAtomicCounterAdd:
2472 case glslang::EOpAtomicCounterSubtract:
2473 case glslang::EOpAtomicCounterMin:
2474 case glslang::EOpAtomicCounterMax:
2475 case glslang::EOpAtomicCounterAnd:
2476 case glslang::EOpAtomicCounterOr:
2477 case glslang::EOpAtomicCounterXor:
2478 case glslang::EOpAtomicCounterExchange:
2479 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002480 if (arg == 0)
2481 lvalue = true;
2482 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002483 case glslang::EOpAddCarry:
2484 case glslang::EOpSubBorrow:
2485 if (arg == 2)
2486 lvalue = true;
2487 break;
2488 case glslang::EOpUMulExtended:
2489 case glslang::EOpIMulExtended:
2490 if (arg >= 2)
2491 lvalue = true;
2492 break;
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002493 case glslang::EOpCooperativeMatrixLoad:
2494 if (arg == 0 || arg == 1)
2495 lvalue = true;
2496 break;
2497 case glslang::EOpCooperativeMatrixStore:
2498 if (arg == 1)
2499 lvalue = true;
2500 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002501 default:
2502 break;
2503 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002504 builder.clearAccessChain();
2505 if (invertedType != spv::NoType && arg == 0)
2506 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2507 else
2508 glslangOperands[arg]->traverse(this);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002509
2510 if (node->getOp() == glslang::EOpCooperativeMatrixLoad ||
2511 node->getOp() == glslang::EOpCooperativeMatrixStore) {
2512
2513 if (arg == 1) {
2514 // fold "element" parameter into the access chain
2515 spv::Builder::AccessChain save = builder.getAccessChain();
2516 builder.clearAccessChain();
2517 glslangOperands[2]->traverse(this);
2518
2519 spv::Id elementId = accessChainLoad(glslangOperands[2]->getAsTyped()->getType());
2520
2521 builder.setAccessChain(save);
2522
2523 // Point to the first element of the array.
2524 builder.accessChainPush(elementId, TranslateCoherent(glslangOperands[arg]->getAsTyped()->getType()),
Jeff Bolz7895e472019-03-06 13:34:10 -06002525 glslangOperands[arg]->getAsTyped()->getType().getBufferReferenceAlignment());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002526
2527 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
2528 unsigned int alignment = builder.getAccessChain().alignment;
2529
2530 int memoryAccess = TranslateMemoryAccess(coherentFlags);
2531 if (node->getOp() == glslang::EOpCooperativeMatrixLoad)
2532 memoryAccess &= ~spv::MemoryAccessMakePointerAvailableKHRMask;
2533 if (node->getOp() == glslang::EOpCooperativeMatrixStore)
2534 memoryAccess &= ~spv::MemoryAccessMakePointerVisibleKHRMask;
2535 if (builder.getStorageClass(builder.getAccessChain().base) == spv::StorageClassPhysicalStorageBufferEXT) {
2536 memoryAccess = (spv::MemoryAccessMask)(memoryAccess | spv::MemoryAccessAlignedMask);
2537 }
2538
2539 memoryAccessOperands.push_back(spv::IdImmediate(false, memoryAccess));
2540
2541 if (memoryAccess & spv::MemoryAccessAlignedMask) {
2542 memoryAccessOperands.push_back(spv::IdImmediate(false, alignment));
2543 }
2544
2545 if (memoryAccess & (spv::MemoryAccessMakePointerAvailableKHRMask | spv::MemoryAccessMakePointerVisibleKHRMask)) {
2546 memoryAccessOperands.push_back(spv::IdImmediate(true, builder.makeUintConstant(TranslateMemoryScope(coherentFlags))));
2547 }
2548 } else if (arg == 2) {
2549 continue;
2550 }
2551 }
2552
John Kessenich140f3df2015-06-26 16:58:36 -06002553 if (lvalue)
2554 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002555 else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002556 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kessenich32cfd492016-02-02 12:37:46 -07002557 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002558 }
John Kessenich140f3df2015-06-26 16:58:36 -06002559 }
John Kessenich426394d2015-07-23 10:22:48 -06002560
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002561 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Jeff Bolz4605e2e2019-02-19 13:10:32 -06002562 if (node->getOp() == glslang::EOpCooperativeMatrixLoad) {
2563 std::vector<spv::IdImmediate> idImmOps;
2564
2565 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2566 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2567 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2568 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2569 // get the pointee type
2570 spv::Id typeId = builder.getContainedTypeId(builder.getTypeId(operands[0]));
2571 assert(builder.isCooperativeMatrixType(typeId));
2572 // do the op
2573 spv::Id result = builder.createOp(spv::OpCooperativeMatrixLoadNV, typeId, idImmOps);
2574 // store the result to the pointer (out param 'm')
2575 builder.createStore(result, operands[0]);
2576 result = 0;
2577 } else if (node->getOp() == glslang::EOpCooperativeMatrixStore) {
2578 std::vector<spv::IdImmediate> idImmOps;
2579
2580 idImmOps.push_back(spv::IdImmediate(true, operands[1])); // buf
2581 idImmOps.push_back(spv::IdImmediate(true, operands[0])); // object
2582 idImmOps.push_back(spv::IdImmediate(true, operands[2])); // stride
2583 idImmOps.push_back(spv::IdImmediate(true, operands[3])); // colMajor
2584 idImmOps.insert(idImmOps.end(), memoryAccessOperands.begin(), memoryAccessOperands.end());
2585
2586 builder.createNoResultOp(spv::OpCooperativeMatrixStoreNV, idImmOps);
2587 result = 0;
2588 } else if (atomic) {
John Kessenich426394d2015-07-23 10:22:48 -06002589 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002590 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002591 } else {
2592 // Pass through to generic operations.
2593 switch (glslangOperands.size()) {
2594 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002595 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002596 break;
2597 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002598 {
2599 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002600 TranslateNoContractionDecoration(node->getType().getQualifier()),
2601 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002602 result = createUnaryOperation(
2603 node->getOp(), decorations,
2604 resultType(), operands.front(),
2605 glslangOperands[0]->getAsTyped()->getBasicType());
2606 }
John Kessenich426394d2015-07-23 10:22:48 -06002607 break;
2608 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002609 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002610 break;
2611 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002612 if (invertedType)
2613 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002614 }
2615
2616 if (noReturnValue)
2617 return false;
2618
2619 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002620 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002621 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002622 } else {
2623 builder.clearAccessChain();
2624 builder.setAccessChainRValue(result);
2625 return false;
2626 }
2627}
2628
John Kessenich433e9ff2017-01-26 20:31:11 -07002629// This path handles both if-then-else and ?:
2630// The if-then-else has a node type of void, while
2631// ?: has either a void or a non-void node type
2632//
2633// Leaving the result, when not void:
2634// GLSL only has r-values as the result of a :?, but
2635// if we have an l-value, that can be more efficient if it will
2636// become the base of a complex r-value expression, because the
2637// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002638bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2639{
John Kessenich0c1e71a2019-01-10 18:23:06 +07002640 // see if OpSelect can handle it
2641 const auto isOpSelectable = [&]() {
2642 if (node->getBasicType() == glslang::EbtVoid)
2643 return false;
2644 // OpSelect can do all other types starting with SPV 1.4
2645 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4) {
2646 // pre-1.4, only scalars and vectors can be handled
2647 if ((!node->getType().isScalar() && !node->getType().isVector()))
2648 return false;
2649 }
2650 return true;
2651 };
2652
John Kessenich4bee5312018-02-20 21:29:05 -07002653 // See if it simple and safe, or required, to execute both sides.
2654 // Crucially, side effects must be either semantically required or avoided,
2655 // and there are performance trade-offs.
2656 // Return true if required or a good idea (and safe) to execute both sides,
2657 // false otherwise.
2658 const auto bothSidesPolicy = [&]() -> bool {
2659 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002660 if (node->getTrueBlock() == nullptr ||
2661 node->getFalseBlock() == nullptr)
2662 return false;
2663
John Kessenich4bee5312018-02-20 21:29:05 -07002664 // required? (unless we write additional code to look for side effects
2665 // and make performance trade-offs if none are present)
2666 if (!node->getShortCircuit())
2667 return true;
2668
2669 // if not required to execute both, decide based on performance/practicality...
2670
John Kessenich0c1e71a2019-01-10 18:23:06 +07002671 if (!isOpSelectable())
John Kessenich4bee5312018-02-20 21:29:05 -07002672 return false;
2673
John Kessenich433e9ff2017-01-26 20:31:11 -07002674 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2675 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2676
2677 // return true if a single operand to ? : is okay for OpSelect
2678 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002679 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002680 };
2681
2682 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2683 operandOkay(node->getFalseBlock()->getAsTyped());
2684 };
2685
John Kessenich4bee5312018-02-20 21:29:05 -07002686 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2687 // emit the condition before doing anything with selection
2688 node->getCondition()->traverse(this);
2689 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2690
2691 // Find a way of executing both sides and selecting the right result.
2692 const auto executeBothSides = [&]() -> void {
2693 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002694 node->getTrueBlock()->traverse(this);
2695 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2696 node->getFalseBlock()->traverse(this);
2697 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2698
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002699 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002700
John Kessenich4bee5312018-02-20 21:29:05 -07002701 // done if void
2702 if (node->getBasicType() == glslang::EbtVoid)
2703 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002704
John Kessenich4bee5312018-02-20 21:29:05 -07002705 // emit code to select between trueValue and falseValue
2706
2707 // see if OpSelect can handle it
John Kessenich0c1e71a2019-01-10 18:23:06 +07002708 if (isOpSelectable()) {
John Kessenich4bee5312018-02-20 21:29:05 -07002709 // Emit OpSelect for this selection.
2710
2711 // smear condition to vector, if necessary (AST is always scalar)
John Kessenich0c1e71a2019-01-10 18:23:06 +07002712 // Before 1.4, smear like for mix(), starting with 1.4, keep it scalar
2713 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_4 && builder.isVector(trueValue)) {
John Kessenich4bee5312018-02-20 21:29:05 -07002714 condition = builder.smearScalar(spv::NoPrecision, condition,
2715 builder.makeVectorType(builder.makeBoolType(),
2716 builder.getNumComponents(trueValue)));
John Kessenich0c1e71a2019-01-10 18:23:06 +07002717 }
John Kessenich4bee5312018-02-20 21:29:05 -07002718
2719 // OpSelect
2720 result = builder.createTriOp(spv::OpSelect,
2721 convertGlslangToSpvType(node->getType()), condition,
2722 trueValue, falseValue);
2723
2724 builder.clearAccessChain();
2725 builder.setAccessChainRValue(result);
2726 } else {
2727 // We need control flow to select the result.
2728 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2729 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2730
2731 // Selection control:
2732 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2733
2734 // make an "if" based on the value created by the condition
2735 spv::Builder::If ifBuilder(condition, control, builder);
2736
2737 // emit the "then" statement
2738 builder.createStore(trueValue, result);
2739 ifBuilder.makeBeginElse();
2740 // emit the "else" statement
2741 builder.createStore(falseValue, result);
2742
2743 // finish off the control flow
2744 ifBuilder.makeEndIf();
2745
2746 builder.clearAccessChain();
2747 builder.setAccessChainLValue(result);
2748 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002749 };
2750
John Kessenich4bee5312018-02-20 21:29:05 -07002751 // Execute the one side needed, as per the condition
2752 const auto executeOneSide = [&]() {
2753 // Always emit control flow.
2754 if (node->getBasicType() != glslang::EbtVoid)
2755 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002756
John Kessenich4bee5312018-02-20 21:29:05 -07002757 // Selection control:
2758 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2759
2760 // make an "if" based on the value created by the condition
2761 spv::Builder::If ifBuilder(condition, control, builder);
2762
2763 // emit the "then" statement
2764 if (node->getTrueBlock() != nullptr) {
2765 node->getTrueBlock()->traverse(this);
2766 if (result != spv::NoResult)
2767 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2768 }
2769
2770 if (node->getFalseBlock() != nullptr) {
2771 ifBuilder.makeBeginElse();
2772 // emit the "else" statement
2773 node->getFalseBlock()->traverse(this);
2774 if (result != spv::NoResult)
2775 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2776 }
2777
2778 // finish off the control flow
2779 ifBuilder.makeEndIf();
2780
2781 if (result != spv::NoResult) {
2782 builder.clearAccessChain();
2783 builder.setAccessChainLValue(result);
2784 }
2785 };
2786
2787 // Try for OpSelect (or a requirement to execute both sides)
2788 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002789 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2790 if (node->getType().getQualifier().isSpecConstant())
2791 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002792 executeBothSides();
2793 } else
2794 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002795
2796 return false;
2797}
2798
2799bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2800{
2801 // emit and get the condition before doing anything with switch
2802 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002803 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002804
Rex Xu57e65922017-07-04 23:23:40 +08002805 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002806 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002807
John Kessenich140f3df2015-06-26 16:58:36 -06002808 // browse the children to sort out code segments
2809 int defaultSegment = -1;
2810 std::vector<TIntermNode*> codeSegments;
2811 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2812 std::vector<int> caseValues;
2813 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2814 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2815 TIntermNode* child = *c;
2816 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002817 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002818 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002819 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002820 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2821 } else
2822 codeSegments.push_back(child);
2823 }
2824
qining25262b32016-05-06 17:25:16 -04002825 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002826 // statements between the last case and the end of the switch statement
2827 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2828 (int)codeSegments.size() == defaultSegment)
2829 codeSegments.push_back(nullptr);
2830
2831 // make the switch statement
2832 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002833 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002834
2835 // emit all the code in the segments
2836 breakForLoop.push(false);
2837 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2838 builder.nextSwitchSegment(segmentBlocks, s);
2839 if (codeSegments[s])
2840 codeSegments[s]->traverse(this);
2841 else
2842 builder.addSwitchBreak();
2843 }
2844 breakForLoop.pop();
2845
2846 builder.endSwitch(segmentBlocks);
2847
2848 return false;
2849}
2850
2851void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2852{
2853 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002854 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002855
2856 builder.clearAccessChain();
2857 builder.setAccessChainRValue(constant);
2858}
2859
2860bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2861{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002862 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002863 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002864
2865 // Loop control:
John Kessenich1f4d0462019-01-12 17:31:41 +07002866 std::vector<unsigned int> operands;
2867 const spv::LoopControlMask control = TranslateLoopControl(*node, operands);
steve-lunargf1709e72017-05-02 20:14:50 -06002868
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002869 // Spec requires back edges to target header blocks, and every header block
2870 // must dominate its merge block. Make a header block first to ensure these
2871 // conditions are met. By definition, it will contain OpLoopMerge, followed
2872 // by a block-ending branch. But we don't want to put any other body/test
2873 // instructions in it, since the body/test may have arbitrary instructions,
2874 // including merges of its own.
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002875 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002876 builder.setBuildPoint(&blocks.head);
John Kessenich1f4d0462019-01-12 17:31:41 +07002877 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, operands);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002878 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002879 spv::Block& test = builder.makeNewBlock();
2880 builder.createBranch(&test);
2881
2882 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002883 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002884 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002885 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2886
2887 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002888 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002889 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002890 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002891 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002892 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002893
2894 builder.setBuildPoint(&blocks.continue_target);
2895 if (node->getTerminal())
2896 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002897 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002898 } else {
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002899 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002900 builder.createBranch(&blocks.body);
2901
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002902 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002903 builder.setBuildPoint(&blocks.body);
2904 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002905 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002906 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002907 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002908
2909 builder.setBuildPoint(&blocks.continue_target);
2910 if (node->getTerminal())
2911 node->getTerminal()->traverse(this);
2912 if (node->getTest()) {
2913 node->getTest()->traverse(this);
2914 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002915 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002916 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002917 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002918 // TODO: unless there was a break/return/discard instruction
2919 // somewhere in the body, this is an infinite loop, so we should
2920 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002921 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002922 }
John Kessenich140f3df2015-06-26 16:58:36 -06002923 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002924 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002925 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002926 return false;
2927}
2928
2929bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2930{
2931 if (node->getExpression())
2932 node->getExpression()->traverse(this);
2933
greg-lunarg5d43c4a2018-12-07 17:36:33 -07002934 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06002935
John Kessenich140f3df2015-06-26 16:58:36 -06002936 switch (node->getFlowOp()) {
2937 case glslang::EOpKill:
2938 builder.makeDiscard();
2939 break;
2940 case glslang::EOpBreak:
2941 if (breakForLoop.top())
2942 builder.createLoopExit();
2943 else
2944 builder.addSwitchBreak();
2945 break;
2946 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002947 builder.createLoopContinue();
2948 break;
2949 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002950 if (node->getExpression()) {
2951 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2952 spv::Id returnId = accessChainLoad(glslangReturnType);
2953 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2954 builder.clearAccessChain();
2955 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2956 builder.setAccessChainLValue(copyId);
2957 multiTypeStore(glslangReturnType, returnId);
2958 returnId = builder.createLoad(copyId);
2959 }
2960 builder.makeReturn(false, returnId);
2961 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002962 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002963
2964 builder.clearAccessChain();
2965 break;
2966
2967 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002968 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002969 break;
2970 }
2971
2972 return false;
2973}
2974
2975spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2976{
qining25262b32016-05-06 17:25:16 -04002977 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002978 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002979 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002980 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05002981 spv::Id result = createSpvConstant(*node);
2982 if (result != spv::NoResult)
2983 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06002984 }
2985
2986 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002987 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002988 spv::Id spvType = convertGlslangToSpvType(node->getType());
2989
Rex Xucabbb782017-03-24 13:41:14 +08002990 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2991 node->getType().containsBasicType(glslang::EbtInt16) ||
2992 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002993 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002994 switch (storageClass) {
2995 case spv::StorageClassInput:
2996 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002997 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002998 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002999 break;
3000 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07003001 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003002 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06003003 break;
3004 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07003005 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08003006 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
3007 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06003008 else
3009 builder.addCapability(spv::CapabilityStorageUniform16);
3010 break;
3011 case spv::StorageClassStorageBuffer:
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003012 case spv::StorageClassPhysicalStorageBufferEXT:
John Kessenich18310872018-05-14 22:08:53 -06003013 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
3014 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
3015 break;
3016 default:
3017 break;
Rex Xuf89ad982017-04-07 23:22:33 +08003018 }
3019 }
Rex Xuf89ad982017-04-07 23:22:33 +08003020
John Kessenich312dcfb2018-07-03 13:19:51 -06003021 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
3022 node->getType().containsBasicType(glslang::EbtUint8);
3023 if (contains8BitType) {
3024 if (storageClass == spv::StorageClassPushConstant) {
3025 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3026 builder.addCapability(spv::CapabilityStoragePushConstant8);
3027 } else if (storageClass == spv::StorageClassUniform) {
3028 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3029 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01003030 } else if (storageClass == spv::StorageClassStorageBuffer) {
3031 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
3032 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
John Kessenich312dcfb2018-07-03 13:19:51 -06003033 }
3034 }
3035
John Kessenich140f3df2015-06-26 16:58:36 -06003036 const char* name = node->getName().c_str();
3037 if (glslang::IsAnonymous(name))
3038 name = "";
3039
3040 return builder.createVariable(storageClass, spvType, name);
3041}
3042
3043// Return type Id of the sampled type.
3044spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
3045{
3046 switch (sampler.type) {
3047 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08003048#ifdef AMD_EXTENSIONS
3049 case glslang::EbtFloat16:
3050 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
3051 builder.addCapability(spv::CapabilityFloat16ImageAMD);
3052 return builder.makeFloatType(16);
3053#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003054 case glslang::EbtInt: return builder.makeIntType(32);
3055 case glslang::EbtUint: return builder.makeUintType(32);
3056 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003057 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003058 return builder.makeFloatType(32);
3059 }
3060}
3061
John Kessenich8c8505c2016-07-26 12:50:38 -06003062// If node is a swizzle operation, return the type that should be used if
3063// the swizzle base is first consumed by another operation, before the swizzle
3064// is applied.
3065spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
3066{
John Kessenichecba76f2017-01-06 00:34:48 -07003067 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06003068 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
3069 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
3070 else
3071 return spv::NoType;
3072}
3073
3074// When inverting a swizzle with a parent op, this function
3075// will apply the swizzle operation to a completed parent operation.
3076spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
3077{
3078 std::vector<unsigned> swizzle;
3079 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
3080 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
3081}
3082
John Kessenich8c8505c2016-07-26 12:50:38 -06003083// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
3084void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
3085{
3086 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
3087 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
3088 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
3089}
3090
John Kessenich3ac051e2015-12-20 11:29:16 -07003091// Convert from a glslang type to an SPV type, by calling into a
3092// recursive version of this function. This establishes the inherited
3093// layout state rooted from the top-level type.
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003094spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool forwardReferenceOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003095{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003096 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false, forwardReferenceOnly);
John Kessenich31ed4832015-09-09 17:51:38 -06003097}
3098
3099// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07003100// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06003101// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06003102spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003103 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier,
3104 bool lastBufferBlockMember, bool forwardReferenceOnly)
John Kessenich31ed4832015-09-09 17:51:38 -06003105{
John Kesseniche0b6cad2015-12-24 10:30:13 -07003106 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003107
3108 switch (type.getBasicType()) {
3109 case glslang::EbtVoid:
3110 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07003111 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06003112 break;
3113 case glslang::EbtFloat:
3114 spvType = builder.makeFloatType(32);
3115 break;
3116 case glslang::EbtDouble:
3117 spvType = builder.makeFloatType(64);
3118 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003119 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003120 spvType = builder.makeFloatType(16);
3121 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003122 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07003123 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
3124 // a 32-bit int where non-0 means true.
3125 if (explicitLayout != glslang::ElpNone)
3126 spvType = builder.makeUintType(32);
3127 else
3128 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06003129 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003130 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07003131 spvType = builder.makeIntType(8);
3132 break;
3133 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07003134 spvType = builder.makeUintType(8);
3135 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06003136 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07003137 spvType = builder.makeIntType(16);
3138 break;
3139 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07003140 spvType = builder.makeUintType(16);
3141 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003142 case glslang::EbtInt:
3143 spvType = builder.makeIntType(32);
3144 break;
3145 case glslang::EbtUint:
3146 spvType = builder.makeUintType(32);
3147 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003148 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003149 spvType = builder.makeIntType(64);
3150 break;
3151 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08003152 spvType = builder.makeUintType(64);
3153 break;
John Kessenich426394d2015-07-23 10:22:48 -06003154 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06003155 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06003156 spvType = builder.makeUintType(32);
3157 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07003158#ifdef NV_EXTENSIONS
3159 case glslang::EbtAccStructNV:
3160 spvType = builder.makeAccelerationStructureNVType();
3161 break;
3162#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003163 case glslang::EbtSampler:
3164 {
3165 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07003166 if (sampler.sampler) {
3167 // pure sampler
3168 spvType = builder.makeSamplerType();
3169 } else {
3170 // an image is present, make its type
3171 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
3172 sampler.image ? 2 : 1, TranslateImageFormat(type));
3173 if (sampler.combined) {
3174 // already has both image and sampler, make the combined type
3175 spvType = builder.makeSampledImageType(spvType);
3176 }
John Kessenich55e7d112015-11-15 21:33:39 -07003177 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07003178 }
John Kessenich140f3df2015-06-26 16:58:36 -06003179 break;
3180 case glslang::EbtStruct:
3181 case glslang::EbtBlock:
3182 {
3183 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06003184 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07003185
3186 // Try to share structs for different layouts, but not yet for other
3187 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06003188 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003189 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07003190 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06003191 break;
3192
3193 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06003194 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003195 memberRemapper[glslangMembers].resize(glslangMembers->size());
3196 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003197 }
3198 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003199 case glslang::EbtReference:
3200 {
3201 // Make the forward pointer, then recurse to convert the structure type, then
3202 // patch up the forward pointer with a real pointer type.
3203 if (forwardPointers.find(type.getReferentType()) == forwardPointers.end()) {
3204 spv::Id forwardId = builder.makeForwardPointer(spv::StorageClassPhysicalStorageBufferEXT);
3205 forwardPointers[type.getReferentType()] = forwardId;
3206 }
3207 spvType = forwardPointers[type.getReferentType()];
3208 if (!forwardReferenceOnly) {
3209 spv::Id referentType = convertGlslangToSpvType(*type.getReferentType());
3210 builder.makePointerFromForwardPointer(spv::StorageClassPhysicalStorageBufferEXT,
3211 forwardPointers[type.getReferentType()],
3212 referentType);
3213 }
3214 }
3215 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003216 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003217 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003218 break;
3219 }
3220
3221 if (type.isMatrix())
3222 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3223 else {
3224 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3225 if (type.getVectorSize() > 1)
3226 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3227 }
3228
Jeff Bolz4605e2e2019-02-19 13:10:32 -06003229 if (type.isCoopMat()) {
3230 builder.addCapability(spv::CapabilityCooperativeMatrixNV);
3231 builder.addExtension(spv::E_SPV_NV_cooperative_matrix);
3232 if (type.getBasicType() == glslang::EbtFloat16)
3233 builder.addCapability(spv::CapabilityFloat16);
3234
3235 spv::Id scope = makeArraySizeId(*type.getTypeParameters(), 1);
3236 spv::Id rows = makeArraySizeId(*type.getTypeParameters(), 2);
3237 spv::Id cols = makeArraySizeId(*type.getTypeParameters(), 3);
3238
3239 spvType = builder.makeCooperativeMatrixType(spvType, scope, rows, cols);
3240 }
3241
John Kessenich140f3df2015-06-26 16:58:36 -06003242 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003243 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3244
John Kessenichc9a80832015-09-12 12:17:44 -06003245 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003246 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003247 // We need to decorate array strides for types needing explicit layout, except blocks.
3248 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003249 // Use a dummy glslang type for querying internal strides of
3250 // arrays of arrays, but using just a one-dimensional array.
3251 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003252 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3253 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003254
3255 // Will compute the higher-order strides here, rather than making a whole
3256 // pile of types and doing repetitive recursion on their contents.
3257 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3258 }
John Kessenichf8842e52016-01-04 19:22:56 -07003259
3260 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003261 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003262 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003263 if (stride > 0)
3264 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003265 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003266 }
3267 } else {
3268 // single-dimensional array, and don't yet have stride
3269
John Kessenichf8842e52016-01-04 19:22:56 -07003270 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003271 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3272 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003273 }
John Kessenich31ed4832015-09-09 17:51:38 -06003274
John Kessenichead86222018-03-28 18:01:20 -06003275 // Do the outer dimension, which might not be known for a runtime-sized array.
3276 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3277 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003278 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003279 else {
3280 if (!lastBufferBlockMember) {
3281 builder.addExtension("SPV_EXT_descriptor_indexing");
3282 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3283 }
John Kessenichead86222018-03-28 18:01:20 -06003284 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003285 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003286 if (stride > 0)
3287 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003288 }
3289
3290 return spvType;
3291}
3292
John Kessenich0e737842017-03-24 18:38:16 -06003293// TODO: this functionality should exist at a higher level, in creating the AST
3294//
3295// Identify interface members that don't have their required extension turned on.
3296//
3297bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3298{
Chao Chen3c366992018-09-19 11:41:59 -07003299#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003300 auto& extensions = glslangIntermediate->getRequestedExtensions();
3301
Rex Xubcf291a2017-03-29 23:01:36 +08003302 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3303 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3304 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003305 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3306 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3307 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003308
3309 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3310 if (member.getFieldName() == "gl_ViewportMask" &&
3311 extensions.find("GL_NV_viewport_array2") == extensions.end())
3312 return true;
3313 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3314 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3315 return true;
3316 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3317 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3318 return true;
3319 }
3320#endif
John Kessenich0e737842017-03-24 18:38:16 -06003321
3322 return false;
3323};
3324
John Kessenich6090df02016-06-30 21:18:02 -06003325// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3326// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3327// Mutually recursive with convertGlslangToSpvType().
3328spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3329 const glslang::TTypeList* glslangMembers,
3330 glslang::TLayoutPacking explicitLayout,
3331 const glslang::TQualifier& qualifier)
3332{
3333 // Create a vector of struct types for SPIR-V to consume
3334 std::vector<spv::Id> spvMembers;
3335 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 -06003336 std::vector<std::pair<glslang::TType*, glslang::TQualifier> > deferredForwardPointers;
John Kessenich6090df02016-06-30 21:18:02 -06003337 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3338 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3339 if (glslangMember.hiddenMember()) {
3340 ++memberDelta;
3341 if (type.getBasicType() == glslang::EbtBlock)
3342 memberRemapper[glslangMembers][i] = -1;
3343 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003344 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003345 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003346 if (filterMember(glslangMember))
3347 continue;
3348 }
John Kessenich6090df02016-06-30 21:18:02 -06003349 // modify just this child's view of the qualifier
3350 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3351 InheritQualifiers(memberQualifier, qualifier);
3352
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003353 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003354 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003355 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003356
3357 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003358 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3359 i == (int)glslangMembers->size() - 1;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003360
3361 // Make forward pointers for any pointer members, and create a list of members to
3362 // convert to spirv types after creating the struct.
3363 if (glslangMember.getBasicType() == glslang::EbtReference) {
3364 if (forwardPointers.find(glslangMember.getReferentType()) == forwardPointers.end()) {
3365 deferredForwardPointers.push_back(std::make_pair(&glslangMember, memberQualifier));
3366 }
3367 spvMembers.push_back(
3368 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, true));
3369 } else {
3370 spvMembers.push_back(
3371 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember, false));
3372 }
John Kessenich6090df02016-06-30 21:18:02 -06003373 }
3374 }
3375
3376 // Make the SPIR-V type
3377 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003378 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003379 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3380
3381 // Decorate it
3382 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3383
John Kessenichd72f4882019-01-16 14:55:37 +07003384 for (int i = 0; i < (int)deferredForwardPointers.size(); ++i) {
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003385 auto it = deferredForwardPointers[i];
3386 convertGlslangToSpvType(*it.first, explicitLayout, it.second, false);
3387 }
3388
John Kessenich6090df02016-06-30 21:18:02 -06003389 return spvType;
3390}
3391
3392void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3393 const glslang::TTypeList* glslangMembers,
3394 glslang::TLayoutPacking explicitLayout,
3395 const glslang::TQualifier& qualifier,
3396 spv::Id spvType)
3397{
3398 // Name and decorate the non-hidden members
3399 int offset = -1;
3400 int locationOffset = 0; // for use within the members of this struct
3401 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3402 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3403 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003404 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003405 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003406 if (filterMember(glslangMember))
3407 continue;
3408 }
John Kessenich6090df02016-06-30 21:18:02 -06003409
3410 // modify just this child's view of the qualifier
3411 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3412 InheritQualifiers(memberQualifier, qualifier);
3413
3414 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003415 if (member < 0)
3416 continue;
3417
3418 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3419 builder.addMemberDecoration(spvType, member,
3420 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3421 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3422 // Add interpolation and auxiliary storage decorations only to
3423 // top-level members of Input and Output storage classes
3424 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3425 type.getQualifier().storage == glslang::EvqVaryingOut) {
3426 if (type.getBasicType() == glslang::EbtBlock ||
3427 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3428 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3429 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003430#ifdef NV_EXTENSIONS
3431 addMeshNVDecoration(spvType, member, memberQualifier);
3432#endif
John Kessenich6090df02016-06-30 21:18:02 -06003433 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003434 }
3435 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003436
John Kessenich5d610ee2018-03-07 18:05:55 -07003437 if (type.getBasicType() == glslang::EbtBlock &&
3438 qualifier.storage == glslang::EvqBuffer) {
3439 // Add memory decorations only to top-level members of shader storage block
3440 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003441 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003442 for (unsigned int i = 0; i < memory.size(); ++i)
3443 builder.addMemberDecoration(spvType, member, memory[i]);
3444 }
John Kessenich6090df02016-06-30 21:18:02 -06003445
John Kessenich5d610ee2018-03-07 18:05:55 -07003446 // Location assignment was already completed correctly by the front end,
3447 // just track whether a member needs to be decorated.
3448 // Ignore member locations if the container is an array, as that's
3449 // ill-specified and decisions have been made to not allow this.
3450 if (! type.isArray() && memberQualifier.hasLocation())
3451 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003452
John Kessenich5d610ee2018-03-07 18:05:55 -07003453 if (qualifier.hasLocation()) // track for upcoming inheritance
3454 locationOffset += glslangIntermediate->computeTypeLocationSize(
3455 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003456
John Kessenich5d610ee2018-03-07 18:05:55 -07003457 // component, XFB, others
3458 if (glslangMember.getQualifier().hasComponent())
3459 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3460 glslangMember.getQualifier().layoutComponent);
3461 if (glslangMember.getQualifier().hasXfbOffset())
3462 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3463 glslangMember.getQualifier().layoutXfbOffset);
3464 else if (explicitLayout != glslang::ElpNone) {
3465 // figure out what to do with offset, which is accumulating
3466 int nextOffset;
3467 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3468 if (offset >= 0)
3469 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3470 offset = nextOffset;
3471 }
John Kessenich6090df02016-06-30 21:18:02 -06003472
John Kessenich5d610ee2018-03-07 18:05:55 -07003473 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3474 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3475 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003476
John Kessenich5d610ee2018-03-07 18:05:55 -07003477 // built-in variable decorations
3478 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3479 if (builtIn != spv::BuiltInMax)
3480 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003481
John Kessenich5611c6d2018-04-05 11:25:02 -06003482 // nonuniform
3483 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3484
John Kessenichead86222018-03-28 18:01:20 -06003485 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3486 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3487 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3488 memberQualifier.semanticName);
3489 }
3490
chaoc771d89f2017-01-13 01:10:53 -08003491#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003492 if (builtIn == spv::BuiltInLayer) {
3493 // SPV_NV_viewport_array2 extension
3494 if (glslangMember.getQualifier().layoutViewportRelative){
3495 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3496 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3497 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003498 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003499 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3500 builder.addMemberDecoration(spvType, member,
3501 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3502 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3503 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3504 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003505 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003506 }
3507 if (glslangMember.getQualifier().layoutPassthrough) {
3508 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3509 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3510 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3511 }
chaoc771d89f2017-01-13 01:10:53 -08003512#endif
John Kessenich6090df02016-06-30 21:18:02 -06003513 }
3514
3515 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003516 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3517 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003518}
3519
John Kessenich6c292d32016-02-15 20:58:50 -07003520// Turn the expression forming the array size into an id.
3521// This is not quite trivial, because of specialization constants.
3522// Sometimes, a raw constant is turned into an Id, and sometimes
3523// a specialization constant expression is.
3524spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3525{
3526 // First, see if this is sized with a node, meaning a specialization constant:
3527 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3528 if (specNode != nullptr) {
3529 builder.clearAccessChain();
3530 specNode->traverse(this);
3531 return accessChainLoad(specNode->getAsTyped()->getType());
3532 }
qining25262b32016-05-06 17:25:16 -04003533
John Kessenich6c292d32016-02-15 20:58:50 -07003534 // Otherwise, need a compile-time (front end) size, get it:
3535 int size = arraySizes.getDimSize(dim);
3536 assert(size > 0);
3537 return builder.makeUintConstant(size);
3538}
3539
John Kessenich103bef92016-02-08 21:38:15 -07003540// Wrap the builder's accessChainLoad to:
3541// - localize handling of RelaxedPrecision
3542// - use the SPIR-V inferred type instead of another conversion of the glslang type
3543// (avoids unnecessary work and possible type punning for structures)
3544// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003545spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3546{
John Kessenich103bef92016-02-08 21:38:15 -07003547 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003548
3549 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3550 coherentFlags |= TranslateCoherent(type);
3551
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003552 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003553 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003554
John Kessenich5611c6d2018-04-05 11:25:02 -06003555 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003556 TranslateNonUniformDecoration(type.getQualifier()),
3557 nominalTypeId,
3558 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003559 TranslateMemoryScope(coherentFlags),
3560 alignment);
John Kessenich103bef92016-02-08 21:38:15 -07003561
3562 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003563 if (type.getBasicType() == glslang::EbtBool) {
3564 if (builder.isScalarType(nominalTypeId)) {
3565 // Conversion for bool
3566 spv::Id boolType = builder.makeBoolType();
3567 if (nominalTypeId != boolType)
3568 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3569 } else if (builder.isVectorType(nominalTypeId)) {
3570 // Conversion for bvec
3571 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3572 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3573 if (nominalTypeId != bvecType)
3574 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3575 }
3576 }
John Kessenich103bef92016-02-08 21:38:15 -07003577
3578 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003579}
3580
Rex Xu27253232016-02-23 17:51:09 +08003581// Wrap the builder's accessChainStore to:
3582// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003583//
3584// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003585void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3586{
3587 // Need to convert to abstract types when necessary
3588 if (type.getBasicType() == glslang::EbtBool) {
3589 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3590
3591 if (builder.isScalarType(nominalTypeId)) {
3592 // Conversion for bool
3593 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003594 if (nominalTypeId != boolType) {
3595 // keep these outside arguments, for determinant order-of-evaluation
3596 spv::Id one = builder.makeUintConstant(1);
3597 spv::Id zero = builder.makeUintConstant(0);
3598 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3599 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003600 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003601 } else if (builder.isVectorType(nominalTypeId)) {
3602 // Conversion for bvec
3603 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3604 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003605 if (nominalTypeId != bvecType) {
3606 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003607 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3608 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3609 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003610 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003611 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3612 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003613 }
3614 }
3615
Jeff Bolz36831c92018-09-05 10:11:41 -05003616 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3617 coherentFlags |= TranslateCoherent(type);
3618
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003619 unsigned int alignment = builder.getAccessChain().alignment;
Jeff Bolz7895e472019-03-06 13:34:10 -06003620 alignment |= type.getBufferReferenceAlignment();
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003621
Jeff Bolz36831c92018-09-05 10:11:41 -05003622 builder.accessChainStore(rvalue,
3623 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003624 TranslateMemoryScope(coherentFlags), alignment);
Rex Xu27253232016-02-23 17:51:09 +08003625}
3626
John Kessenich4bf71552016-09-02 11:20:21 -06003627// For storing when types match at the glslang level, but not might match at the
3628// SPIR-V level.
3629//
3630// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003631// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003632// as in a member-decorated way.
3633//
3634// NOTE: This function can handle any store request; if it's not special it
3635// simplifies to a simple OpStore.
3636//
3637// Implicitly uses the existing builder.accessChain as the storage target.
3638void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3639{
John Kessenichb3e24e42016-09-11 12:33:43 -06003640 // we only do the complex path here if it's an aggregate
3641 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003642 accessChainStore(type, rValue);
3643 return;
3644 }
3645
John Kessenichb3e24e42016-09-11 12:33:43 -06003646 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003647 spv::Id rType = builder.getTypeId(rValue);
3648 spv::Id lValue = builder.accessChainGetLValue();
3649 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3650 if (lType == rType) {
3651 accessChainStore(type, rValue);
3652 return;
3653 }
3654
John Kessenichb3e24e42016-09-11 12:33:43 -06003655 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003656 // where the two types were the same type in GLSL. This requires member
3657 // by member copy, recursively.
3658
John Kessenichfbb6bdf2019-01-15 21:48:27 +07003659 // SPIR-V 1.4 added an instruction to do help do this.
3660 if (glslangIntermediate->getSpv().spv >= glslang::EShTargetSpv_1_4) {
3661 // However, bool in uniform space is changed to int, so
3662 // OpCopyLogical does not work for that.
3663 // TODO: It would be more robust to do a full recursive verification of the types satisfying SPIR-V rules.
3664 bool rBool = builder.containsType(builder.getTypeId(rValue), spv::OpTypeBool, 0);
3665 bool lBool = builder.containsType(lType, spv::OpTypeBool, 0);
3666 if (lBool == rBool) {
3667 spv::Id logicalCopy = builder.createUnaryOp(spv::OpCopyLogical, lType, rValue);
3668 accessChainStore(type, logicalCopy);
3669 return;
3670 }
3671 }
3672
John Kessenichb3e24e42016-09-11 12:33:43 -06003673 // If an array, copy element by element.
3674 if (type.isArray()) {
3675 glslang::TType glslangElementType(type, 0);
3676 spv::Id elementRType = builder.getContainedTypeId(rType);
3677 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3678 // get the source member
3679 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003680
John Kessenichb3e24e42016-09-11 12:33:43 -06003681 // set up the target storage
3682 builder.clearAccessChain();
3683 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003684 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenich4bf71552016-09-02 11:20:21 -06003685
John Kessenichb3e24e42016-09-11 12:33:43 -06003686 // store the member
3687 multiTypeStore(glslangElementType, elementRValue);
3688 }
3689 } else {
3690 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003691
John Kessenichb3e24e42016-09-11 12:33:43 -06003692 // loop over structure members
3693 const glslang::TTypeList& members = *type.getStruct();
3694 for (int m = 0; m < (int)members.size(); ++m) {
3695 const glslang::TType& glslangMemberType = *members[m].type;
3696
3697 // get the source member
3698 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3699 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3700
3701 // set up the target storage
3702 builder.clearAccessChain();
3703 builder.setAccessChainLValue(lValue);
Jeff Bolz7895e472019-03-06 13:34:10 -06003704 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type), type.getBufferReferenceAlignment());
John Kessenichb3e24e42016-09-11 12:33:43 -06003705
3706 // store the member
3707 multiTypeStore(glslangMemberType, memberRValue);
3708 }
John Kessenich4bf71552016-09-02 11:20:21 -06003709 }
3710}
3711
John Kessenichf85e8062015-12-19 13:57:10 -07003712// Decide whether or not this type should be
3713// decorated with offsets and strides, and if so
3714// whether std140 or std430 rules should be applied.
3715glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003716{
John Kessenichf85e8062015-12-19 13:57:10 -07003717 // has to be a block
3718 if (type.getBasicType() != glslang::EbtBlock)
3719 return glslang::ElpNone;
3720
Chao Chen3c366992018-09-19 11:41:59 -07003721 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003722 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003723 type.getQualifier().storage != glslang::EvqBuffer &&
3724 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003725 return glslang::ElpNone;
3726
3727 // return the layout to use
3728 switch (type.getQualifier().layoutPacking) {
3729 case glslang::ElpStd140:
3730 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003731 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003732 return type.getQualifier().layoutPacking;
3733 default:
3734 return glslang::ElpNone;
3735 }
John Kessenich31ed4832015-09-09 17:51:38 -06003736}
3737
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003738// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003739int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003740{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003741 int size;
John Kessenich49987892015-12-29 17:11:44 -07003742 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003743 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003744
3745 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003746}
3747
John Kessenich49987892015-12-29 17:11:44 -07003748// 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 -07003749// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003750int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003751{
John Kessenich49987892015-12-29 17:11:44 -07003752 glslang::TType elementType;
3753 elementType.shallowCopy(matrixType);
3754 elementType.clearArraySizes();
3755
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003756 int size;
John Kessenich49987892015-12-29 17:11:44 -07003757 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003758 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003759
3760 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003761}
3762
John Kessenich5e4b1242015-08-06 22:53:06 -06003763// Given a member type of a struct, realign the current offset for it, and compute
3764// the next (not yet aligned) offset for the next member, which will get aligned
3765// on the next call.
3766// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3767// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3768// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003769void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003770 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003771{
3772 // this will get a positive value when deemed necessary
3773 nextOffset = -1;
3774
John Kessenich5e4b1242015-08-06 22:53:06 -06003775 // override anything in currentOffset with user-set offset
3776 if (memberType.getQualifier().hasOffset())
3777 currentOffset = memberType.getQualifier().layoutOffset;
3778
3779 // It could be that current linker usage in glslang updated all the layoutOffset,
3780 // in which case the following code does not matter. But, that's not quite right
3781 // once cross-compilation unit GLSL validation is done, as the original user
3782 // settings are needed in layoutOffset, and then the following will come into play.
3783
John Kessenichf85e8062015-12-19 13:57:10 -07003784 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003785 if (! memberType.getQualifier().hasOffset())
3786 currentOffset = -1;
3787
3788 return;
3789 }
3790
John Kessenichf85e8062015-12-19 13:57:10 -07003791 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003792 if (currentOffset < 0)
3793 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003794
John Kessenich5e4b1242015-08-06 22:53:06 -06003795 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3796 // but possibly not yet correctly aligned.
3797
3798 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003799 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003800 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003801
3802 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003803 // TODO: make this consistent in early phases of code:
3804 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3805 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3806 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003807 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003808 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003809 int dummySize;
3810 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3811 if (componentAlignment <= 4)
3812 memberAlignment = componentAlignment;
3813 }
3814
3815 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003816 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003817
3818 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003819 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003820 glslang::RoundToPow2(currentOffset, 16);
3821
John Kessenich5e4b1242015-08-06 22:53:06 -06003822 nextOffset = currentOffset + memberSize;
3823}
3824
David Netoa901ffe2016-06-08 14:11:40 +01003825void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003826{
David Netoa901ffe2016-06-08 14:11:40 +01003827 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3828 switch (glslangBuiltIn)
3829 {
3830 case glslang::EbvClipDistance:
3831 case glslang::EbvCullDistance:
3832 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003833#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003834 case glslang::EbvViewportMaskNV:
3835 case glslang::EbvSecondaryPositionNV:
3836 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003837 case glslang::EbvPositionPerViewNV:
3838 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003839 case glslang::EbvTaskCountNV:
3840 case glslang::EbvPrimitiveCountNV:
3841 case glslang::EbvPrimitiveIndicesNV:
3842 case glslang::EbvClipDistancePerViewNV:
3843 case glslang::EbvCullDistancePerViewNV:
3844 case glslang::EbvLayerPerViewNV:
3845 case glslang::EbvMeshViewCountNV:
3846 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003847#endif
David Netoa901ffe2016-06-08 14:11:40 +01003848 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3849 // Alternately, we could just call this for any glslang built-in, since the
3850 // capability already guards against duplicates.
3851 TranslateBuiltInDecoration(glslangBuiltIn, false);
3852 break;
3853 default:
3854 // Capabilities were already generated when the struct was declared.
3855 break;
3856 }
John Kessenichebb50532016-05-16 19:22:05 -06003857}
3858
John Kessenich6fccb3c2016-09-19 16:01:41 -06003859bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003860{
John Kessenicheee9d532016-09-19 18:09:30 -06003861 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003862}
3863
John Kessenichd41993d2017-09-10 15:21:05 -06003864// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003865// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3866// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003867bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003868{
John Kessenich6a14f782017-12-04 02:48:10 -07003869 assert(qualifier == glslang::EvqIn ||
3870 qualifier == glslang::EvqOut ||
3871 qualifier == glslang::EvqInOut ||
3872 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003873 return qualifier != glslang::EvqConstReadOnly;
3874}
3875
3876// Is parameter pass-by-original?
3877bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3878 bool implicitThisParam)
3879{
3880 if (implicitThisParam) // implicit this
3881 return true;
3882 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003883 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003884 return paramType.containsOpaque() || // sampler, etc.
3885 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3886}
3887
John Kessenich140f3df2015-06-26 16:58:36 -06003888// Make all the functions, skeletally, without actually visiting their bodies.
3889void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3890{
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003891 const auto getParamDecorations = [&](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003892 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3893 if (paramPrecision != spv::NoPrecision)
3894 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003895 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
Jeff Bolz9f2aec42019-01-06 17:58:04 -06003896 if (type.getBasicType() == glslang::EbtReference) {
3897 // Original and non-writable params pass the pointer directly and
3898 // use restrict/aliased, others are stored to a pointer in Function
3899 // memory and use RestrictPointer/AliasedPointer.
3900 if (originalParam(type.getQualifier().storage, type, false) ||
3901 !writableParam(type.getQualifier().storage)) {
3902 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrict : spv::DecorationAliased);
3903 } else {
3904 decorations.push_back(type.getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
3905 }
3906 }
John Kessenichfad62972017-07-18 02:35:46 -06003907 };
3908
John Kessenich140f3df2015-06-26 16:58:36 -06003909 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3910 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003911 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003912 continue;
3913
3914 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003915 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003916 //
qining25262b32016-05-06 17:25:16 -04003917 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003918 // function. What it is an address of varies:
3919 //
John Kessenich4bf71552016-09-02 11:20:21 -06003920 // - "in" parameters not marked as "const" can be written to without modifying the calling
3921 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003922 //
3923 // - "const in" parameters can just be the r-value, as no writes need occur.
3924 //
John Kessenich4bf71552016-09-02 11:20:21 -06003925 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3926 // 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 -06003927
3928 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003929 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003930 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3931
John Kessenichfad62972017-07-18 02:35:46 -06003932 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3933 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003934
John Kessenichfad62972017-07-18 02:35:46 -06003935 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003936 for (int p = 0; p < (int)parameters.size(); ++p) {
3937 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3938 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003939 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003940 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003941 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003942 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3943 else
John Kessenich4bf71552016-09-02 11:20:21 -06003944 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003945 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003946 paramTypes.push_back(typeId);
3947 }
3948
3949 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003950 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3951 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003952 glslFunction->getName().c_str(), paramTypes,
3953 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003954 if (implicitThis)
3955 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003956
3957 // Track function to emit/call later
3958 functionMap[glslFunction->getName().c_str()] = function;
3959
3960 // Set the parameter id's
3961 for (int p = 0; p < (int)parameters.size(); ++p) {
3962 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3963 // give a name too
3964 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3965 }
3966 }
3967}
3968
3969// Process all the initializers, while skipping the functions and link objects
3970void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3971{
3972 builder.setBuildPoint(shaderEntry->getLastBlock());
3973 for (int i = 0; i < (int)initializers.size(); ++i) {
3974 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3975 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3976
3977 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003978 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003979 initializer->traverse(this);
3980 }
3981 }
3982}
3983
3984// Process all the functions, while skipping initializers.
3985void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3986{
3987 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3988 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003989 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003990 node->traverse(this);
3991 }
3992}
3993
3994void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3995{
qining25262b32016-05-06 17:25:16 -04003996 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003997 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003998 currentFunction = functionMap[node->getName().c_str()];
3999 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06004000 builder.setBuildPoint(functionBlock);
4001}
4002
Rex Xu04db3f52015-09-16 11:44:02 +08004003void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004004{
Rex Xufc618912015-09-09 16:42:49 +08004005 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08004006
4007 glslang::TSampler sampler = {};
4008 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004009#ifdef AMD_EXTENSIONS
4010 bool f16ShadowCompare = false;
4011#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004012 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08004013 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
4014 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004015#ifdef AMD_EXTENSIONS
4016 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
4017#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004018 }
4019
John Kessenich140f3df2015-06-26 16:58:36 -06004020 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
4021 builder.clearAccessChain();
4022 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08004023
4024 // Special case l-value operands
4025 bool lvalue = false;
4026 switch (node.getOp()) {
4027 case glslang::EOpImageAtomicAdd:
4028 case glslang::EOpImageAtomicMin:
4029 case glslang::EOpImageAtomicMax:
4030 case glslang::EOpImageAtomicAnd:
4031 case glslang::EOpImageAtomicOr:
4032 case glslang::EOpImageAtomicXor:
4033 case glslang::EOpImageAtomicExchange:
4034 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05004035 case glslang::EOpImageAtomicLoad:
4036 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08004037 if (i == 0)
4038 lvalue = true;
4039 break;
Rex Xu5eafa472016-02-19 22:24:03 +08004040 case glslang::EOpSparseImageLoad:
4041 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
4042 lvalue = true;
4043 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004044#ifdef AMD_EXTENSIONS
4045 case glslang::EOpSparseTexture:
4046 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
4047 lvalue = true;
4048 break;
4049 case glslang::EOpSparseTextureClamp:
4050 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
4051 lvalue = true;
4052 break;
4053 case glslang::EOpSparseTextureLod:
4054 case glslang::EOpSparseTextureOffset:
4055 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
4056 lvalue = true;
4057 break;
4058#else
Rex Xu48edadf2015-12-31 16:11:41 +08004059 case glslang::EOpSparseTexture:
4060 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
4061 lvalue = true;
4062 break;
4063 case glslang::EOpSparseTextureClamp:
4064 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
4065 lvalue = true;
4066 break;
4067 case glslang::EOpSparseTextureLod:
4068 case glslang::EOpSparseTextureOffset:
4069 if (i == 3)
4070 lvalue = true;
4071 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004072#endif
Rex Xu48edadf2015-12-31 16:11:41 +08004073 case glslang::EOpSparseTextureFetch:
4074 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
4075 lvalue = true;
4076 break;
4077 case glslang::EOpSparseTextureFetchOffset:
4078 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
4079 lvalue = true;
4080 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004081#ifdef AMD_EXTENSIONS
4082 case glslang::EOpSparseTextureLodOffset:
4083 case glslang::EOpSparseTextureGrad:
4084 case glslang::EOpSparseTextureOffsetClamp:
4085 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
4086 lvalue = true;
4087 break;
4088 case glslang::EOpSparseTextureGradOffset:
4089 case glslang::EOpSparseTextureGradClamp:
4090 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
4091 lvalue = true;
4092 break;
4093 case glslang::EOpSparseTextureGradOffsetClamp:
4094 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
4095 lvalue = true;
4096 break;
4097#else
Rex Xu48edadf2015-12-31 16:11:41 +08004098 case glslang::EOpSparseTextureLodOffset:
4099 case glslang::EOpSparseTextureGrad:
4100 case glslang::EOpSparseTextureOffsetClamp:
4101 if (i == 4)
4102 lvalue = true;
4103 break;
4104 case glslang::EOpSparseTextureGradOffset:
4105 case glslang::EOpSparseTextureGradClamp:
4106 if (i == 5)
4107 lvalue = true;
4108 break;
4109 case glslang::EOpSparseTextureGradOffsetClamp:
4110 if (i == 6)
4111 lvalue = true;
4112 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08004113#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004114 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08004115 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
4116 lvalue = true;
4117 break;
4118 case glslang::EOpSparseTextureGatherOffset:
4119 case glslang::EOpSparseTextureGatherOffsets:
4120 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
4121 lvalue = true;
4122 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004123#ifdef AMD_EXTENSIONS
4124 case glslang::EOpSparseTextureGatherLod:
4125 if (i == 3)
4126 lvalue = true;
4127 break;
4128 case glslang::EOpSparseTextureGatherLodOffset:
4129 case glslang::EOpSparseTextureGatherLodOffsets:
4130 if (i == 4)
4131 lvalue = true;
4132 break;
Rex Xu129799a2017-07-05 17:23:28 +08004133 case glslang::EOpSparseImageLoadLod:
4134 if (i == 3)
4135 lvalue = true;
4136 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08004137#endif
Chao Chen3a137962018-09-19 11:41:27 -07004138#ifdef NV_EXTENSIONS
4139 case glslang::EOpImageSampleFootprintNV:
4140 if (i == 4)
4141 lvalue = true;
4142 break;
4143 case glslang::EOpImageSampleFootprintClampNV:
4144 case glslang::EOpImageSampleFootprintLodNV:
4145 if (i == 5)
4146 lvalue = true;
4147 break;
4148 case glslang::EOpImageSampleFootprintGradNV:
4149 if (i == 6)
4150 lvalue = true;
4151 break;
4152 case glslang::EOpImageSampleFootprintGradClampNV:
4153 if (i == 7)
4154 lvalue = true;
4155 break;
4156#endif
Rex Xufc618912015-09-09 16:42:49 +08004157 default:
4158 break;
4159 }
4160
Rex Xu6b86d492015-09-16 17:48:22 +08004161 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08004162 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08004163 else
John Kessenich32cfd492016-02-02 12:37:46 -07004164 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004165 }
4166}
4167
John Kessenichfc51d282015-08-19 13:34:18 -06004168void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06004169{
John Kessenichfc51d282015-08-19 13:34:18 -06004170 builder.clearAccessChain();
4171 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07004172 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06004173}
John Kessenich140f3df2015-06-26 16:58:36 -06004174
John Kessenichfc51d282015-08-19 13:34:18 -06004175spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
4176{
John Kesseniche485c7a2017-05-31 18:50:53 -06004177 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06004178 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06004179
greg-lunarg5d43c4a2018-12-07 17:36:33 -07004180 builder.setLine(node->getLoc().line, node->getLoc().getFilename());
John Kesseniche485c7a2017-05-31 18:50:53 -06004181
John Kessenichfc51d282015-08-19 13:34:18 -06004182 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05004183
4184 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
4185 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
4186 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08004187#ifdef AMD_EXTENSIONS
4188 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
4189 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
4190 : false;
4191#endif
4192
John Kessenichfc51d282015-08-19 13:34:18 -06004193 std::vector<spv::Id> arguments;
4194 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08004195 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06004196 else
4197 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06004198 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06004199
4200 spv::Builder::TextureParameters params = { };
4201 params.sampler = arguments[0];
4202
Rex Xu04db3f52015-09-16 11:44:02 +08004203 glslang::TCrackedTextureOp cracked;
4204 node->crackTexture(sampler, cracked);
4205
amhagan05506bb2017-06-13 16:53:02 -04004206 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004207
John Kessenichfc51d282015-08-19 13:34:18 -06004208 // Check for queries
4209 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004210 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
4211 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07004212 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02004213
John Kessenichfc51d282015-08-19 13:34:18 -06004214 switch (node->getOp()) {
4215 case glslang::EOpImageQuerySize:
4216 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06004217 if (arguments.size() > 1) {
4218 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004219 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06004220 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004221 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004222 case glslang::EOpImageQuerySamples:
4223 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004224 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004225 case glslang::EOpTextureQueryLod:
4226 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004227 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06004228 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07004229 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08004230 case glslang::EOpSparseTexelsResident:
4231 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06004232 default:
4233 assert(0);
4234 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004235 }
John Kessenich140f3df2015-06-26 16:58:36 -06004236 }
4237
LoopDawg4425f242018-02-18 11:40:01 -07004238 int components = node->getType().getVectorSize();
4239
4240 if (node->getOp() == glslang::EOpTextureFetch) {
4241 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
4242 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
4243 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
4244 // here around e.g. which ones return scalars or other types.
4245 components = 4;
4246 }
4247
4248 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
4249
4250 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
4251
Rex Xufc618912015-09-09 16:42:49 +08004252 // Check for image functions other than queries
4253 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06004254 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06004255 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06004256 spv::IdImmediate image = { true, *(opIt++) };
4257 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07004258
4259 // Handle subpass operations
4260 // TODO: GLSL should change to have the "MS" only on the type rather than the
4261 // built-in function.
4262 if (cracked.subpass) {
4263 // add on the (0,0) coordinate
4264 spv::Id zero = builder.makeIntConstant(0);
4265 std::vector<spv::Id> comps;
4266 comps.push_back(zero);
4267 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06004268 spv::IdImmediate coord = { true,
4269 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4270 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07004271 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06004272 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
4273 operands.push_back(imageOperands);
4274 spv::IdImmediate imageOperand = { true, *(opIt++) };
4275 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07004276 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004277 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4278 builder.setPrecision(result, precision);
4279 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004280 }
4281
John Kessenich149afc32018-08-14 13:31:43 -06004282 spv::IdImmediate coord = { true, *(opIt++) };
4283 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004284#ifdef AMD_EXTENSIONS
4285 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4286#else
John Kessenich56bab042015-09-16 10:54:31 -06004287 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004288#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004289 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004290 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004291 mask = mask | spv::ImageOperandsSampleMask;
4292 }
Rex Xu129799a2017-07-05 17:23:28 +08004293#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004294 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004295 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4296 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004297 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004298 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004299#endif
4300 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4301 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4302 if (mask) {
4303 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4304 operands.push_back(imageOperands);
4305 }
4306 if (mask & spv::ImageOperandsSampleMask) {
4307 spv::IdImmediate imageOperand = { true, *opIt++ };
4308 operands.push_back(imageOperand);
4309 }
4310#ifdef AMD_EXTENSIONS
4311 if (mask & spv::ImageOperandsLodMask) {
4312 spv::IdImmediate imageOperand = { true, *opIt++ };
4313 operands.push_back(imageOperand);
4314 }
4315#endif
4316 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4317 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4318 operands.push_back(imageOperand);
4319 }
4320
John Kessenich149afc32018-08-14 13:31:43 -06004321 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004322 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004323
John Kessenich149afc32018-08-14 13:31:43 -06004324 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004325 builder.setPrecision(result[0], precision);
4326
4327 // If needed, add a conversion constructor to the proper size.
4328 if (components != node->getType().getVectorSize())
4329 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4330
4331 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004332#ifdef AMD_EXTENSIONS
4333 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4334#else
John Kessenich56bab042015-09-16 10:54:31 -06004335 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004336#endif
Rex Xu129799a2017-07-05 17:23:28 +08004337
Jeff Bolz36831c92018-09-05 10:11:41 -05004338 // Push the texel value before the operands
4339#ifdef AMD_EXTENSIONS
4340 if (sampler.ms || cracked.lod) {
4341#else
4342 if (sampler.ms) {
4343#endif
John Kessenich149afc32018-08-14 13:31:43 -06004344 spv::IdImmediate texel = { true, *(opIt + 1) };
4345 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004346 } else {
4347 spv::IdImmediate texel = { true, *opIt };
4348 operands.push_back(texel);
4349 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004350
4351 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4352 if (sampler.ms) {
4353 mask = mask | spv::ImageOperandsSampleMask;
4354 }
4355#ifdef AMD_EXTENSIONS
4356 if (cracked.lod) {
4357 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4358 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4359 mask = mask | spv::ImageOperandsLodMask;
4360 }
4361#endif
4362 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4363 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
4364 if (mask) {
4365 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4366 operands.push_back(imageOperands);
4367 }
4368 if (mask & spv::ImageOperandsSampleMask) {
4369 spv::IdImmediate imageOperand = { true, *opIt++ };
4370 operands.push_back(imageOperand);
4371 }
4372#ifdef AMD_EXTENSIONS
4373 if (mask & spv::ImageOperandsLodMask) {
4374 spv::IdImmediate imageOperand = { true, *opIt++ };
4375 operands.push_back(imageOperand);
4376 }
4377#endif
4378 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
4379 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4380 operands.push_back(imageOperand);
4381 }
4382
John Kessenich56bab042015-09-16 10:54:31 -06004383 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004384 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004385 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004386 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004387#ifdef AMD_EXTENSIONS
4388 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
4389#else
Rex Xu5eafa472016-02-19 22:24:03 +08004390 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004391#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004392 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004393 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004394 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4395
Jeff Bolz36831c92018-09-05 10:11:41 -05004396 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004397 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004398 mask = mask | spv::ImageOperandsSampleMask;
4399 }
Rex Xu129799a2017-07-05 17:23:28 +08004400#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004401 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004402 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4403 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4404
Jeff Bolz36831c92018-09-05 10:11:41 -05004405 mask = mask | spv::ImageOperandsLodMask;
4406 }
4407#endif
4408 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4409 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4410 if (mask) {
4411 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004412 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004413 }
4414 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004415 spv::IdImmediate imageOperand = { true, *opIt++ };
4416 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004417 }
4418#ifdef AMD_EXTENSIONS
4419 if (mask & spv::ImageOperandsLodMask) {
4420 spv::IdImmediate imageOperand = { true, *opIt++ };
4421 operands.push_back(imageOperand);
4422 }
Rex Xu129799a2017-07-05 17:23:28 +08004423#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004424 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4425 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4426 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004427 }
4428
4429 // Create the return type that was a special structure
4430 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004431 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004432 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4433 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4434
4435 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4436
4437 // Decode the return type
4438 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4439 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004440 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004441 // Process image atomic operations
4442
4443 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4444 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004445 // For non-MS, the sample value should be 0
4446 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4447 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004448
Jeff Bolz36831c92018-09-05 10:11:41 -05004449 spv::Id resultTypeId;
4450 // imageAtomicStore has a void return type so base the pointer type on
4451 // the type of the value operand.
4452 if (node->getOp() == glslang::EOpImageAtomicStore) {
4453 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4454 } else {
4455 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4456 }
John Kessenich56bab042015-09-16 10:54:31 -06004457 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004458
4459 std::vector<spv::Id> operands;
4460 operands.push_back(pointer);
4461 for (; opIt != arguments.end(); ++opIt)
4462 operands.push_back(*opIt);
4463
John Kessenich8c8505c2016-07-26 12:50:38 -06004464 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004465 }
4466 }
4467
amhagan05506bb2017-06-13 16:53:02 -04004468#ifdef AMD_EXTENSIONS
4469 // Check for fragment mask functions other than queries
4470 if (cracked.fragMask) {
4471 assert(sampler.ms);
4472
4473 auto opIt = arguments.begin();
4474 std::vector<spv::Id> operands;
4475
4476 // Extract the image if necessary
4477 if (builder.isSampledImage(params.sampler))
4478 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4479
4480 operands.push_back(params.sampler);
4481 ++opIt;
4482
4483 if (sampler.isSubpass()) {
4484 // add on the (0,0) coordinate
4485 spv::Id zero = builder.makeIntConstant(0);
4486 std::vector<spv::Id> comps;
4487 comps.push_back(zero);
4488 comps.push_back(zero);
4489 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4490 }
4491
4492 for (; opIt != arguments.end(); ++opIt)
4493 operands.push_back(*opIt);
4494
4495 spv::Op fragMaskOp = spv::OpNop;
4496 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4497 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4498 else if (node->getOp() == glslang::EOpFragmentFetch)
4499 fragMaskOp = spv::OpFragmentFetchAMD;
4500
4501 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4502 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4503 return builder.createOp(fragMaskOp, resultType(), operands);
4504 }
4505#endif
4506
Rex Xufc618912015-09-09 16:42:49 +08004507 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004508 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004509#ifdef NV_EXTENSIONS
4510 bool imageFootprint = node->isImageFootprint();
4511#endif
4512
Rex Xu71519fe2015-11-11 15:35:47 +08004513 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4514
John Kessenichfc51d282015-08-19 13:34:18 -06004515 // check for bias argument
4516 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004517#ifdef AMD_EXTENSIONS
4518 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4519#else
Rex Xu71519fe2015-11-11 15:35:47 +08004520 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004521#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004522 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004523#ifdef AMD_EXTENSIONS
4524 if (cracked.gather)
4525 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004526
4527 if (f16ShadowCompare)
4528 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004529#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004530 if (cracked.offset)
4531 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004532#ifdef AMD_EXTENSIONS
4533 else if (cracked.offsets)
4534 ++nonBiasArgCount;
4535#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004536 if (cracked.grad)
4537 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004538 if (cracked.lodClamp)
4539 ++nonBiasArgCount;
4540 if (sparse)
4541 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004542#ifdef NV_EXTENSIONS
4543 if (imageFootprint)
4544 //Following three extra arguments
4545 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4546 nonBiasArgCount += 3;
4547#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004548 if ((int)arguments.size() > nonBiasArgCount)
4549 bias = true;
4550 }
4551
John Kessenicha5c33d62016-06-02 23:45:21 -06004552 // See if the sampler param should really be just the SPV image part
4553 if (cracked.fetch) {
4554 // a fetch needs to have the image extracted first
4555 if (builder.isSampledImage(params.sampler))
4556 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4557 }
4558
Rex Xu225e0fc2016-11-17 17:47:59 +08004559#ifdef AMD_EXTENSIONS
4560 if (cracked.gather) {
4561 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4562 if (bias || cracked.lod ||
4563 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4564 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004565 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004566 }
4567 }
4568#endif
4569
John Kessenichfc51d282015-08-19 13:34:18 -06004570 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004571
John Kessenichfc51d282015-08-19 13:34:18 -06004572 params.coords = arguments[1];
4573 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004574 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004575
4576 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004577#ifdef AMD_EXTENSIONS
4578 if (cubeCompare || f16ShadowCompare) {
4579#else
Rex Xu48edadf2015-12-31 16:11:41 +08004580 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004581#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004582 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004583 ++extraArgs;
4584 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004585 params.Dref = arguments[2];
4586 ++extraArgs;
4587 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004588 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004589 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004590 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004591 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004592 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004593 dRefComp = builder.getNumComponents(params.coords) - 1;
4594 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004595 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4596 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004597
4598 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004599 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004600 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004601 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004602 } else if (glslangIntermediate->getStage() != EShLangFragment
4603#ifdef NV_EXTENSIONS
4604 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4605 && !(glslangIntermediate->getStage() == EShLangCompute &&
4606 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4607#endif
4608 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004609 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4610 noImplicitLod = true;
4611 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004612
4613 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004614 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004615 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004616 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004617 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004618
4619 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004620 if (cracked.grad) {
4621 params.gradX = arguments[2 + extraArgs];
4622 params.gradY = arguments[3 + extraArgs];
4623 extraArgs += 2;
4624 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004625
4626 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004627 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004628 params.offset = arguments[2 + extraArgs];
4629 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004630 } else if (cracked.offsets) {
4631 params.offsets = arguments[2 + extraArgs];
4632 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004633 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004634
4635 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004636 if (cracked.lodClamp) {
4637 params.lodClamp = arguments[2 + extraArgs];
4638 ++extraArgs;
4639 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004640 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004641 if (sparse) {
4642 params.texelOut = arguments[2 + extraArgs];
4643 ++extraArgs;
4644 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004645
John Kessenich76d4dfc2016-06-16 12:43:23 -06004646 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004647 if (cracked.gather && ! sampler.shadow) {
4648 // default component is 0, if missing, otherwise an argument
4649 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004650 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004651 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004652 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004653 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004654 }
Chao Chen3a137962018-09-19 11:41:27 -07004655#ifdef NV_EXTENSIONS
4656 spv::Id resultStruct = spv::NoResult;
4657 if (imageFootprint) {
4658 //Following three extra arguments
4659 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4660 params.granularity = arguments[2 + extraArgs];
4661 params.coarse = arguments[3 + extraArgs];
4662 resultStruct = arguments[4 + extraArgs];
4663 extraArgs += 3;
4664 }
4665#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004666 // bias
4667 if (bias) {
4668 params.bias = arguments[2 + extraArgs];
4669 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004670 }
John Kessenichfc51d282015-08-19 13:34:18 -06004671
Chao Chen3a137962018-09-19 11:41:27 -07004672#ifdef NV_EXTENSIONS
4673 if (imageFootprint) {
4674 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4675 builder.addCapability(spv::CapabilityImageFootprintNV);
4676
4677
4678 //resultStructType(OpenGL type) contains 5 elements:
4679 //struct gl_TextureFootprint2DNV {
4680 // uvec2 anchor;
4681 // uvec2 offset;
4682 // uvec2 mask;
4683 // uint lod;
4684 // uint granularity;
4685 //};
4686 //or
4687 //struct gl_TextureFootprint3DNV {
4688 // uvec3 anchor;
4689 // uvec3 offset;
4690 // uvec2 mask;
4691 // uint lod;
4692 // uint granularity;
4693 //};
4694 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4695 assert(builder.isStructType(resultStructType));
4696
4697 //resType (SPIR-V type) contains 6 elements:
4698 //Member 0 must be a Boolean type scalar(LOD),
4699 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4700 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4701 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4702 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4703 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4704 std::vector<spv::Id> members;
4705 members.push_back(resultType());
4706 for (int i = 0; i < 5; i++) {
4707 members.push_back(builder.getContainedTypeId(resultStructType, i));
4708 }
4709 spv::Id resType = builder.makeStructType(members, "ResType");
4710
4711 //call ImageFootprintNV
4712 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
4713
4714 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4715 for (int i = 0; i < 5; i++) {
4716 builder.clearAccessChain();
4717 builder.setAccessChainLValue(resultStruct);
4718
4719 //Accessing to a struct we created, no coherent flag is set
4720 spv::Builder::AccessChain::CoherentFlags flags;
4721 flags.clear();
4722
Jeff Bolz9f2aec42019-01-06 17:58:04 -06004723 builder.accessChainPush(builder.makeIntConstant(i), flags, 0);
Chao Chen3a137962018-09-19 11:41:27 -07004724 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4725 }
4726 return builder.createCompositeExtract(res, resultType(), 0);
4727 }
4728#endif
4729
John Kessenich65336482016-06-16 14:06:26 -06004730 // projective component (might not to move)
4731 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4732 // are divided by the last component of P."
4733 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4734 // unused components will appear after all used components."
4735 if (cracked.proj) {
4736 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4737 int projTargetComp;
4738 switch (sampler.dim) {
4739 case glslang::Esd1D: projTargetComp = 1; break;
4740 case glslang::Esd2D: projTargetComp = 2; break;
4741 case glslang::EsdRect: projTargetComp = 2; break;
4742 default: projTargetComp = projSourceComp; break;
4743 }
4744 // copy the projective coordinate if we have to
4745 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004746 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004747 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4748 projSourceComp);
4749 params.coords = builder.createCompositeInsert(projComp, params.coords,
4750 builder.getTypeId(params.coords), projTargetComp);
4751 }
4752 }
4753
Jeff Bolz36831c92018-09-05 10:11:41 -05004754 // nonprivate
4755 if (imageType.getQualifier().nonprivate) {
4756 params.nonprivate = true;
4757 }
4758
4759 // volatile
4760 if (imageType.getQualifier().volatil) {
4761 params.volatil = true;
4762 }
4763
St0fFa1184dd2018-04-09 21:08:14 +02004764 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004765 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004766 );
LoopDawg4425f242018-02-18 11:40:01 -07004767
4768 if (components != node->getType().getVectorSize())
4769 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4770
4771 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004772}
4773
4774spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4775{
4776 // Grab the function's pointer from the previously created function
4777 spv::Function* function = functionMap[node->getName().c_str()];
4778 if (! function)
4779 return 0;
4780
4781 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4782 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4783
4784 // See comments in makeFunctions() for details about the semantics for parameter passing.
4785 //
4786 // These imply we need a four step process:
4787 // 1. Evaluate the arguments
4788 // 2. Allocate and make copies of in, out, and inout arguments
4789 // 3. Make the call
4790 // 4. Copy back the results
4791
John Kessenichd3ed90b2018-05-04 11:43:03 -06004792 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004793 std::vector<spv::Builder::AccessChain> lValues;
4794 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004795 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004796 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004797 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004798 // build l-value
4799 builder.clearAccessChain();
4800 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004801 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004802 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004803 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004804 // save l-value
4805 lValues.push_back(builder.getAccessChain());
4806 } else {
4807 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004808 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004809 }
4810 }
4811
4812 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4813 // copy the original into that space.
4814 //
4815 // Also, build up the list of actual arguments to pass in for the call
4816 int lValueCount = 0;
4817 int rValueCount = 0;
4818 std::vector<spv::Id> spvArgs;
4819 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4820 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004821 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004822 builder.setAccessChain(lValues[lValueCount]);
4823 arg = builder.accessChainGetLValue();
4824 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004825 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004826 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004827 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004828 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4829 // need to copy the input into output space
4830 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004831 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004832 builder.clearAccessChain();
4833 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004834 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004835 }
4836 ++lValueCount;
4837 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004838 // process r-value, which involves a copy for a type mismatch
4839 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4840 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4841 builder.clearAccessChain();
4842 builder.setAccessChainLValue(argCopy);
4843 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4844 arg = builder.createLoad(argCopy);
4845 } else
4846 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004847 ++rValueCount;
4848 }
4849 spvArgs.push_back(arg);
4850 }
4851
4852 // 3. Make the call.
4853 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004854 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004855
4856 // 4. Copy back out an "out" arguments.
4857 lValueCount = 0;
4858 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004859 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004860 ++lValueCount;
4861 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004862 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4863 spv::Id copy = builder.createLoad(spvArgs[a]);
4864 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004865 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004866 }
4867 ++lValueCount;
4868 }
4869 }
4870
4871 return result;
4872}
4873
4874// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004875spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004876 spv::Id typeId, spv::Id left, spv::Id right,
4877 glslang::TBasicType typeProxy, bool reduceComparison)
4878{
John Kessenich66011cb2018-03-06 16:12:04 -07004879 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4880 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004881 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004882
4883 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004884 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004885 bool comparison = false;
4886
4887 switch (op) {
4888 case glslang::EOpAdd:
4889 case glslang::EOpAddAssign:
4890 if (isFloat)
4891 binOp = spv::OpFAdd;
4892 else
4893 binOp = spv::OpIAdd;
4894 break;
4895 case glslang::EOpSub:
4896 case glslang::EOpSubAssign:
4897 if (isFloat)
4898 binOp = spv::OpFSub;
4899 else
4900 binOp = spv::OpISub;
4901 break;
4902 case glslang::EOpMul:
4903 case glslang::EOpMulAssign:
4904 if (isFloat)
4905 binOp = spv::OpFMul;
4906 else
4907 binOp = spv::OpIMul;
4908 break;
4909 case glslang::EOpVectorTimesScalar:
4910 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004911 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004912 if (builder.isVector(right))
4913 std::swap(left, right);
4914 assert(builder.isScalar(right));
4915 needMatchingVectors = false;
4916 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01004917 } else if (isFloat)
4918 binOp = spv::OpFMul;
4919 else
John Kessenichec43d0a2015-07-04 17:17:31 -06004920 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004921 break;
4922 case glslang::EOpVectorTimesMatrix:
4923 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004924 binOp = spv::OpVectorTimesMatrix;
4925 break;
4926 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004927 binOp = spv::OpMatrixTimesVector;
4928 break;
4929 case glslang::EOpMatrixTimesScalar:
4930 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004931 binOp = spv::OpMatrixTimesScalar;
4932 break;
4933 case glslang::EOpMatrixTimesMatrix:
4934 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004935 binOp = spv::OpMatrixTimesMatrix;
4936 break;
4937 case glslang::EOpOuterProduct:
4938 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004939 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004940 break;
4941
4942 case glslang::EOpDiv:
4943 case glslang::EOpDivAssign:
4944 if (isFloat)
4945 binOp = spv::OpFDiv;
4946 else if (isUnsigned)
4947 binOp = spv::OpUDiv;
4948 else
4949 binOp = spv::OpSDiv;
4950 break;
4951 case glslang::EOpMod:
4952 case glslang::EOpModAssign:
4953 if (isFloat)
4954 binOp = spv::OpFMod;
4955 else if (isUnsigned)
4956 binOp = spv::OpUMod;
4957 else
4958 binOp = spv::OpSMod;
4959 break;
4960 case glslang::EOpRightShift:
4961 case glslang::EOpRightShiftAssign:
4962 if (isUnsigned)
4963 binOp = spv::OpShiftRightLogical;
4964 else
4965 binOp = spv::OpShiftRightArithmetic;
4966 break;
4967 case glslang::EOpLeftShift:
4968 case glslang::EOpLeftShiftAssign:
4969 binOp = spv::OpShiftLeftLogical;
4970 break;
4971 case glslang::EOpAnd:
4972 case glslang::EOpAndAssign:
4973 binOp = spv::OpBitwiseAnd;
4974 break;
4975 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004976 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004977 binOp = spv::OpLogicalAnd;
4978 break;
4979 case glslang::EOpInclusiveOr:
4980 case glslang::EOpInclusiveOrAssign:
4981 binOp = spv::OpBitwiseOr;
4982 break;
4983 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004984 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004985 binOp = spv::OpLogicalOr;
4986 break;
4987 case glslang::EOpExclusiveOr:
4988 case glslang::EOpExclusiveOrAssign:
4989 binOp = spv::OpBitwiseXor;
4990 break;
4991 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004992 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004993 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004994 break;
4995
4996 case glslang::EOpLessThan:
4997 case glslang::EOpGreaterThan:
4998 case glslang::EOpLessThanEqual:
4999 case glslang::EOpGreaterThanEqual:
5000 case glslang::EOpEqual:
5001 case glslang::EOpNotEqual:
5002 case glslang::EOpVectorEqual:
5003 case glslang::EOpVectorNotEqual:
5004 comparison = true;
5005 break;
5006 default:
5007 break;
5008 }
5009
John Kessenich7c1aa102015-10-15 13:29:11 -06005010 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06005011 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06005012 assert(comparison == false);
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005013 if (builder.isMatrix(left) || builder.isMatrix(right) ||
5014 builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06005015 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005016
5017 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06005018 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06005019 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06005020
qining25262b32016-05-06 17:25:16 -04005021 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005022 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005023 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005024 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005025 }
5026
5027 if (! comparison)
5028 return 0;
5029
John Kessenich7c1aa102015-10-15 13:29:11 -06005030 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06005031
John Kessenich4583b612016-08-07 19:14:22 -06005032 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06005033 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
5034 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06005035 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005036 return result;
5037 }
John Kessenich140f3df2015-06-26 16:58:36 -06005038
5039 switch (op) {
5040 case glslang::EOpLessThan:
5041 if (isFloat)
5042 binOp = spv::OpFOrdLessThan;
5043 else if (isUnsigned)
5044 binOp = spv::OpULessThan;
5045 else
5046 binOp = spv::OpSLessThan;
5047 break;
5048 case glslang::EOpGreaterThan:
5049 if (isFloat)
5050 binOp = spv::OpFOrdGreaterThan;
5051 else if (isUnsigned)
5052 binOp = spv::OpUGreaterThan;
5053 else
5054 binOp = spv::OpSGreaterThan;
5055 break;
5056 case glslang::EOpLessThanEqual:
5057 if (isFloat)
5058 binOp = spv::OpFOrdLessThanEqual;
5059 else if (isUnsigned)
5060 binOp = spv::OpULessThanEqual;
5061 else
5062 binOp = spv::OpSLessThanEqual;
5063 break;
5064 case glslang::EOpGreaterThanEqual:
5065 if (isFloat)
5066 binOp = spv::OpFOrdGreaterThanEqual;
5067 else if (isUnsigned)
5068 binOp = spv::OpUGreaterThanEqual;
5069 else
5070 binOp = spv::OpSGreaterThanEqual;
5071 break;
5072 case glslang::EOpEqual:
5073 case glslang::EOpVectorEqual:
5074 if (isFloat)
5075 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005076 else if (isBool)
5077 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005078 else
5079 binOp = spv::OpIEqual;
5080 break;
5081 case glslang::EOpNotEqual:
5082 case glslang::EOpVectorNotEqual:
5083 if (isFloat)
5084 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08005085 else if (isBool)
5086 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06005087 else
5088 binOp = spv::OpINotEqual;
5089 break;
5090 default:
5091 break;
5092 }
5093
qining25262b32016-05-06 17:25:16 -04005094 if (binOp != spv::OpNop) {
5095 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005096 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005097 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005098 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005099 }
John Kessenich140f3df2015-06-26 16:58:36 -06005100
5101 return 0;
5102}
5103
John Kessenich04bb8a02015-12-12 12:28:14 -07005104//
5105// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
5106// These can be any of:
5107//
5108// matrix * scalar
5109// scalar * matrix
5110// matrix * matrix linear algebraic
5111// matrix * vector
5112// vector * matrix
5113// matrix * matrix componentwise
5114// matrix op matrix op in {+, -, /}
5115// matrix op scalar op in {+, -, /}
5116// scalar op matrix op in {+, -, /}
5117//
John Kessenichead86222018-03-28 18:01:20 -06005118spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5119 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07005120{
5121 bool firstClass = true;
5122
5123 // First, handle first-class matrix operations (* and matrix/scalar)
5124 switch (op) {
5125 case spv::OpFDiv:
5126 if (builder.isMatrix(left) && builder.isScalar(right)) {
5127 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01005128 spv::Id resultType = builder.getTypeId(right);
5129 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07005130 op = spv::OpMatrixTimesScalar;
5131 } else
5132 firstClass = false;
5133 break;
5134 case spv::OpMatrixTimesScalar:
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005135 if (builder.isMatrix(right) || builder.isCooperativeMatrix(right))
John Kessenich04bb8a02015-12-12 12:28:14 -07005136 std::swap(left, right);
5137 assert(builder.isScalar(right));
5138 break;
5139 case spv::OpVectorTimesMatrix:
5140 assert(builder.isVector(left));
5141 assert(builder.isMatrix(right));
5142 break;
5143 case spv::OpMatrixTimesVector:
5144 assert(builder.isMatrix(left));
5145 assert(builder.isVector(right));
5146 break;
5147 case spv::OpMatrixTimesMatrix:
5148 assert(builder.isMatrix(left));
5149 assert(builder.isMatrix(right));
5150 break;
5151 default:
5152 firstClass = false;
5153 break;
5154 }
5155
Jeff Bolz4605e2e2019-02-19 13:10:32 -06005156 if (builder.isCooperativeMatrix(left) || builder.isCooperativeMatrix(right))
5157 firstClass = true;
5158
qining25262b32016-05-06 17:25:16 -04005159 if (firstClass) {
5160 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06005161 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005162 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005163 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04005164 }
John Kessenich04bb8a02015-12-12 12:28:14 -07005165
LoopDawg592860c2016-06-09 08:57:35 -06005166 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07005167 // The result type of all of them is the same type as the (a) matrix operand.
5168 // The algorithm is to:
5169 // - break the matrix(es) into vectors
5170 // - smear any scalar to a vector
5171 // - do vector operations
5172 // - make a matrix out the vector results
5173 switch (op) {
5174 case spv::OpFAdd:
5175 case spv::OpFSub:
5176 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06005177 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07005178 case spv::OpFMul:
5179 {
5180 // one time set up...
5181 bool leftMat = builder.isMatrix(left);
5182 bool rightMat = builder.isMatrix(right);
5183 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
5184 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
5185 spv::Id scalarType = builder.getScalarTypeId(typeId);
5186 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
5187 std::vector<spv::Id> results;
5188 spv::Id smearVec = spv::NoResult;
5189 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06005190 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005191 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06005192 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07005193
5194 // do each vector op
5195 for (unsigned int c = 0; c < numCols; ++c) {
5196 std::vector<unsigned int> indexes;
5197 indexes.push_back(c);
5198 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
5199 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04005200 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06005201 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005202 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005203 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07005204 }
5205
5206 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005207 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005208 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005209 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07005210 }
5211 default:
5212 assert(0);
5213 return spv::NoResult;
5214 }
5215}
5216
John Kessenichead86222018-03-28 18:01:20 -06005217spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
5218 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005219{
5220 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005221 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005222 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07005223 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5224 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005225
5226 switch (op) {
5227 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07005228 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06005229 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07005230 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06005231 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07005232 } else
John Kessenich140f3df2015-06-26 16:58:36 -06005233 unaryOp = spv::OpSNegate;
5234 break;
5235
5236 case glslang::EOpLogicalNot:
5237 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06005238 unaryOp = spv::OpLogicalNot;
5239 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005240 case glslang::EOpBitwiseNot:
5241 unaryOp = spv::OpNot;
5242 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06005243
John Kessenich140f3df2015-06-26 16:58:36 -06005244 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06005245 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06005246 break;
5247 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06005248 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06005249 break;
5250 case glslang::EOpTranspose:
5251 unaryOp = spv::OpTranspose;
5252 break;
5253
5254 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06005255 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06005256 break;
5257 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06005258 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06005259 break;
5260 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005261 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06005262 break;
5263 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005264 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06005265 break;
5266 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005267 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06005268 break;
5269 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06005270 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06005271 break;
5272 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005273 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005274 break;
5275 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005276 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005277 break;
5278
5279 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005280 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005281 break;
5282 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005283 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005284 break;
5285 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005286 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005287 break;
5288 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005289 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005290 break;
5291 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005292 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005293 break;
5294 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005295 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005296 break;
5297
5298 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005299 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005300 break;
5301 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005302 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005303 break;
5304
5305 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005306 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005307 break;
5308 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005309 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005310 break;
5311 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005312 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005313 break;
5314 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005315 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005316 break;
5317 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005318 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005319 break;
5320 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005321 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005322 break;
5323
5324 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005325 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005326 break;
5327 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005328 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005329 break;
5330 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005331 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005332 break;
5333 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005334 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005335 break;
5336 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005337 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005338 break;
5339 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005340 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005341 break;
5342
5343 case glslang::EOpIsNan:
5344 unaryOp = spv::OpIsNan;
5345 break;
5346 case glslang::EOpIsInf:
5347 unaryOp = spv::OpIsInf;
5348 break;
LoopDawg592860c2016-06-09 08:57:35 -06005349 case glslang::EOpIsFinite:
5350 unaryOp = spv::OpIsFinite;
5351 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005352
Rex Xucbc426e2015-12-15 16:03:10 +08005353 case glslang::EOpFloatBitsToInt:
5354 case glslang::EOpFloatBitsToUint:
5355 case glslang::EOpIntBitsToFloat:
5356 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005357 case glslang::EOpDoubleBitsToInt64:
5358 case glslang::EOpDoubleBitsToUint64:
5359 case glslang::EOpInt64BitsToDouble:
5360 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005361 case glslang::EOpFloat16BitsToInt16:
5362 case glslang::EOpFloat16BitsToUint16:
5363 case glslang::EOpInt16BitsToFloat16:
5364 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005365 unaryOp = spv::OpBitcast;
5366 break;
5367
John Kessenich140f3df2015-06-26 16:58:36 -06005368 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005369 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005370 break;
5371 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005372 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005373 break;
5374 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005375 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005376 break;
5377 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005378 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005379 break;
5380 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005381 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005382 break;
5383 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005384 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005385 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005386 case glslang::EOpPackSnorm4x8:
5387 libCall = spv::GLSLstd450PackSnorm4x8;
5388 break;
5389 case glslang::EOpUnpackSnorm4x8:
5390 libCall = spv::GLSLstd450UnpackSnorm4x8;
5391 break;
5392 case glslang::EOpPackUnorm4x8:
5393 libCall = spv::GLSLstd450PackUnorm4x8;
5394 break;
5395 case glslang::EOpUnpackUnorm4x8:
5396 libCall = spv::GLSLstd450UnpackUnorm4x8;
5397 break;
5398 case glslang::EOpPackDouble2x32:
5399 libCall = spv::GLSLstd450PackDouble2x32;
5400 break;
5401 case glslang::EOpUnpackDouble2x32:
5402 libCall = spv::GLSLstd450UnpackDouble2x32;
5403 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005404
Rex Xu8ff43de2016-04-22 16:51:45 +08005405 case glslang::EOpPackInt2x32:
5406 case glslang::EOpUnpackInt2x32:
5407 case glslang::EOpPackUint2x32:
5408 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005409 case glslang::EOpPack16:
5410 case glslang::EOpPack32:
5411 case glslang::EOpPack64:
5412 case glslang::EOpUnpack32:
5413 case glslang::EOpUnpack16:
5414 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005415 case glslang::EOpPackInt2x16:
5416 case glslang::EOpUnpackInt2x16:
5417 case glslang::EOpPackUint2x16:
5418 case glslang::EOpUnpackUint2x16:
5419 case glslang::EOpPackInt4x16:
5420 case glslang::EOpUnpackInt4x16:
5421 case glslang::EOpPackUint4x16:
5422 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005423 case glslang::EOpPackFloat2x16:
5424 case glslang::EOpUnpackFloat2x16:
5425 unaryOp = spv::OpBitcast;
5426 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005427
John Kessenich140f3df2015-06-26 16:58:36 -06005428 case glslang::EOpDPdx:
5429 unaryOp = spv::OpDPdx;
5430 break;
5431 case glslang::EOpDPdy:
5432 unaryOp = spv::OpDPdy;
5433 break;
5434 case glslang::EOpFwidth:
5435 unaryOp = spv::OpFwidth;
5436 break;
5437 case glslang::EOpDPdxFine:
5438 unaryOp = spv::OpDPdxFine;
5439 break;
5440 case glslang::EOpDPdyFine:
5441 unaryOp = spv::OpDPdyFine;
5442 break;
5443 case glslang::EOpFwidthFine:
5444 unaryOp = spv::OpFwidthFine;
5445 break;
5446 case glslang::EOpDPdxCoarse:
5447 unaryOp = spv::OpDPdxCoarse;
5448 break;
5449 case glslang::EOpDPdyCoarse:
5450 unaryOp = spv::OpDPdyCoarse;
5451 break;
5452 case glslang::EOpFwidthCoarse:
5453 unaryOp = spv::OpFwidthCoarse;
5454 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005455 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005456#ifdef AMD_EXTENSIONS
5457 if (typeProxy == glslang::EbtFloat16)
5458 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5459#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005460 libCall = spv::GLSLstd450InterpolateAtCentroid;
5461 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005462 case glslang::EOpAny:
5463 unaryOp = spv::OpAny;
5464 break;
5465 case glslang::EOpAll:
5466 unaryOp = spv::OpAll;
5467 break;
5468
5469 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005470 if (isFloat)
5471 libCall = spv::GLSLstd450FAbs;
5472 else
5473 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005474 break;
5475 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005476 if (isFloat)
5477 libCall = spv::GLSLstd450FSign;
5478 else
5479 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005480 break;
5481
John Kessenichfc51d282015-08-19 13:34:18 -06005482 case glslang::EOpAtomicCounterIncrement:
5483 case glslang::EOpAtomicCounterDecrement:
5484 case glslang::EOpAtomicCounter:
5485 {
5486 // Handle all of the atomics in one place, in createAtomicOperation()
5487 std::vector<spv::Id> operands;
5488 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005489 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005490 }
5491
John Kessenichfc51d282015-08-19 13:34:18 -06005492 case glslang::EOpBitFieldReverse:
5493 unaryOp = spv::OpBitReverse;
5494 break;
5495 case glslang::EOpBitCount:
5496 unaryOp = spv::OpBitCount;
5497 break;
5498 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005499 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005500 break;
5501 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005502 if (isUnsigned)
5503 libCall = spv::GLSLstd450FindUMsb;
5504 else
5505 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005506 break;
5507
Rex Xu574ab042016-04-14 16:53:07 +08005508 case glslang::EOpBallot:
5509 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005510 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005511 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005512 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005513#ifdef AMD_EXTENSIONS
5514 case glslang::EOpMinInvocations:
5515 case glslang::EOpMaxInvocations:
5516 case glslang::EOpAddInvocations:
5517 case glslang::EOpMinInvocationsNonUniform:
5518 case glslang::EOpMaxInvocationsNonUniform:
5519 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005520 case glslang::EOpMinInvocationsInclusiveScan:
5521 case glslang::EOpMaxInvocationsInclusiveScan:
5522 case glslang::EOpAddInvocationsInclusiveScan:
5523 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5524 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5525 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5526 case glslang::EOpMinInvocationsExclusiveScan:
5527 case glslang::EOpMaxInvocationsExclusiveScan:
5528 case glslang::EOpAddInvocationsExclusiveScan:
5529 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5530 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5531 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005532#endif
Rex Xu51596642016-09-21 18:56:12 +08005533 {
5534 std::vector<spv::Id> operands;
5535 operands.push_back(operand);
5536 return createInvocationsOperation(op, typeId, operands, typeProxy);
5537 }
John Kessenich66011cb2018-03-06 16:12:04 -07005538 case glslang::EOpSubgroupAll:
5539 case glslang::EOpSubgroupAny:
5540 case glslang::EOpSubgroupAllEqual:
5541 case glslang::EOpSubgroupBroadcastFirst:
5542 case glslang::EOpSubgroupBallot:
5543 case glslang::EOpSubgroupInverseBallot:
5544 case glslang::EOpSubgroupBallotBitCount:
5545 case glslang::EOpSubgroupBallotInclusiveBitCount:
5546 case glslang::EOpSubgroupBallotExclusiveBitCount:
5547 case glslang::EOpSubgroupBallotFindLSB:
5548 case glslang::EOpSubgroupBallotFindMSB:
5549 case glslang::EOpSubgroupAdd:
5550 case glslang::EOpSubgroupMul:
5551 case glslang::EOpSubgroupMin:
5552 case glslang::EOpSubgroupMax:
5553 case glslang::EOpSubgroupAnd:
5554 case glslang::EOpSubgroupOr:
5555 case glslang::EOpSubgroupXor:
5556 case glslang::EOpSubgroupInclusiveAdd:
5557 case glslang::EOpSubgroupInclusiveMul:
5558 case glslang::EOpSubgroupInclusiveMin:
5559 case glslang::EOpSubgroupInclusiveMax:
5560 case glslang::EOpSubgroupInclusiveAnd:
5561 case glslang::EOpSubgroupInclusiveOr:
5562 case glslang::EOpSubgroupInclusiveXor:
5563 case glslang::EOpSubgroupExclusiveAdd:
5564 case glslang::EOpSubgroupExclusiveMul:
5565 case glslang::EOpSubgroupExclusiveMin:
5566 case glslang::EOpSubgroupExclusiveMax:
5567 case glslang::EOpSubgroupExclusiveAnd:
5568 case glslang::EOpSubgroupExclusiveOr:
5569 case glslang::EOpSubgroupExclusiveXor:
5570 case glslang::EOpSubgroupQuadSwapHorizontal:
5571 case glslang::EOpSubgroupQuadSwapVertical:
5572 case glslang::EOpSubgroupQuadSwapDiagonal: {
5573 std::vector<spv::Id> operands;
5574 operands.push_back(operand);
5575 return createSubgroupOperation(op, typeId, operands, typeProxy);
5576 }
Rex Xu9d93a232016-05-05 12:30:44 +08005577#ifdef AMD_EXTENSIONS
5578 case glslang::EOpMbcnt:
5579 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5580 libCall = spv::MbcntAMD;
5581 break;
5582
5583 case glslang::EOpCubeFaceIndex:
5584 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5585 libCall = spv::CubeFaceIndexAMD;
5586 break;
5587
5588 case glslang::EOpCubeFaceCoord:
5589 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5590 libCall = spv::CubeFaceCoordAMD;
5591 break;
5592#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005593#ifdef NV_EXTENSIONS
5594 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005595 unaryOp = spv::OpGroupNonUniformPartitionNV;
5596 break;
5597#endif
Jeff Bolz9f2aec42019-01-06 17:58:04 -06005598 case glslang::EOpConstructReference:
5599 unaryOp = spv::OpBitcast;
5600 break;
Jeff Bolz88220d52019-05-08 10:24:46 -05005601
5602 case glslang::EOpCopyObject:
5603 unaryOp = spv::OpCopyObject;
5604 break;
5605
John Kessenich140f3df2015-06-26 16:58:36 -06005606 default:
5607 return 0;
5608 }
5609
5610 spv::Id id;
5611 if (libCall >= 0) {
5612 std::vector<spv::Id> args;
5613 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005614 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005615 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005616 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005617 }
John Kessenich140f3df2015-06-26 16:58:36 -06005618
John Kessenichead86222018-03-28 18:01:20 -06005619 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005620 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005621 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005622}
5623
John Kessenich7a53f762016-01-20 11:19:27 -07005624// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005625spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5626 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005627{
5628 // Handle unary operations vector by vector.
5629 // The result type is the same type as the original type.
5630 // The algorithm is to:
5631 // - break the matrix into vectors
5632 // - apply the operation to each vector
5633 // - make a matrix out the vector results
5634
5635 // get the types sorted out
5636 int numCols = builder.getNumColumns(operand);
5637 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005638 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5639 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005640 std::vector<spv::Id> results;
5641
5642 // do each vector op
5643 for (int c = 0; c < numCols; ++c) {
5644 std::vector<unsigned int> indexes;
5645 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005646 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5647 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005648 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005649 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005650 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005651 }
5652
5653 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005654 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005655 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005656 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005657}
5658
John Kessenichad7645f2018-06-04 19:11:25 -06005659// For converting integers where both the bitwidth and the signedness could
5660// change, but only do the width change here. The caller is still responsible
5661// for the signedness conversion.
5662spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005663{
John Kessenichad7645f2018-06-04 19:11:25 -06005664 // Get the result type width, based on the type to convert to.
5665 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005666 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005667 case glslang::EOpConvInt16ToUint8:
5668 case glslang::EOpConvIntToUint8:
5669 case glslang::EOpConvInt64ToUint8:
5670 case glslang::EOpConvUint16ToInt8:
5671 case glslang::EOpConvUintToInt8:
5672 case glslang::EOpConvUint64ToInt8:
5673 width = 8;
5674 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005675 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005676 case glslang::EOpConvIntToUint16:
5677 case glslang::EOpConvInt64ToUint16:
5678 case glslang::EOpConvUint8ToInt16:
5679 case glslang::EOpConvUintToInt16:
5680 case glslang::EOpConvUint64ToInt16:
5681 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005682 break;
5683 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005684 case glslang::EOpConvInt16ToUint:
5685 case glslang::EOpConvInt64ToUint:
5686 case glslang::EOpConvUint8ToInt:
5687 case glslang::EOpConvUint16ToInt:
5688 case glslang::EOpConvUint64ToInt:
5689 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005690 break;
5691 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005692 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005693 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005694 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005695 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005696 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005697 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005698 break;
5699
5700 default:
5701 assert(false && "Default missing");
5702 break;
5703 }
5704
John Kessenichad7645f2018-06-04 19:11:25 -06005705 // Get the conversion operation and result type,
5706 // based on the target width, but the source type.
5707 spv::Id type = spv::NoType;
5708 spv::Op convOp = spv::OpNop;
5709 switch(op) {
5710 case glslang::EOpConvInt8ToUint16:
5711 case glslang::EOpConvInt8ToUint:
5712 case glslang::EOpConvInt8ToUint64:
5713 case glslang::EOpConvInt16ToUint8:
5714 case glslang::EOpConvInt16ToUint:
5715 case glslang::EOpConvInt16ToUint64:
5716 case glslang::EOpConvIntToUint8:
5717 case glslang::EOpConvIntToUint16:
5718 case glslang::EOpConvIntToUint64:
5719 case glslang::EOpConvInt64ToUint8:
5720 case glslang::EOpConvInt64ToUint16:
5721 case glslang::EOpConvInt64ToUint:
5722 convOp = spv::OpSConvert;
5723 type = builder.makeIntType(width);
5724 break;
5725 default:
5726 convOp = spv::OpUConvert;
5727 type = builder.makeUintType(width);
5728 break;
5729 }
5730
John Kessenich66011cb2018-03-06 16:12:04 -07005731 if (vectorSize > 0)
5732 type = builder.makeVectorType(type, vectorSize);
5733
John Kessenichad7645f2018-06-04 19:11:25 -06005734 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005735}
5736
John Kessenichead86222018-03-28 18:01:20 -06005737spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5738 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005739{
5740 spv::Op convOp = spv::OpNop;
5741 spv::Id zero = 0;
5742 spv::Id one = 0;
5743
5744 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5745
5746 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005747 case glslang::EOpConvInt8ToBool:
5748 case glslang::EOpConvUint8ToBool:
5749 zero = builder.makeUint8Constant(0);
5750 zero = makeSmearedConstant(zero, vectorSize);
5751 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005752 case glslang::EOpConvInt16ToBool:
5753 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005754 zero = builder.makeUint16Constant(0);
5755 zero = makeSmearedConstant(zero, vectorSize);
5756 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5757 case glslang::EOpConvIntToBool:
5758 case glslang::EOpConvUintToBool:
5759 zero = builder.makeUintConstant(0);
5760 zero = makeSmearedConstant(zero, vectorSize);
5761 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5762 case glslang::EOpConvInt64ToBool:
5763 case glslang::EOpConvUint64ToBool:
5764 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005765 zero = makeSmearedConstant(zero, vectorSize);
5766 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5767
5768 case glslang::EOpConvFloatToBool:
5769 zero = builder.makeFloatConstant(0.0F);
5770 zero = makeSmearedConstant(zero, vectorSize);
5771 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5772
5773 case glslang::EOpConvDoubleToBool:
5774 zero = builder.makeDoubleConstant(0.0);
5775 zero = makeSmearedConstant(zero, vectorSize);
5776 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5777
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005778 case glslang::EOpConvFloat16ToBool:
5779 zero = builder.makeFloat16Constant(0.0F);
5780 zero = makeSmearedConstant(zero, vectorSize);
5781 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005782
John Kessenich140f3df2015-06-26 16:58:36 -06005783 case glslang::EOpConvBoolToFloat:
5784 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005785 zero = builder.makeFloatConstant(0.0F);
5786 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005787 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005788
John Kessenich140f3df2015-06-26 16:58:36 -06005789 case glslang::EOpConvBoolToDouble:
5790 convOp = spv::OpSelect;
5791 zero = builder.makeDoubleConstant(0.0);
5792 one = builder.makeDoubleConstant(1.0);
5793 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005794
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005795 case glslang::EOpConvBoolToFloat16:
5796 convOp = spv::OpSelect;
5797 zero = builder.makeFloat16Constant(0.0F);
5798 one = builder.makeFloat16Constant(1.0F);
5799 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005800
5801 case glslang::EOpConvBoolToInt8:
5802 zero = builder.makeInt8Constant(0);
5803 one = builder.makeInt8Constant(1);
5804 convOp = spv::OpSelect;
5805 break;
5806
5807 case glslang::EOpConvBoolToUint8:
5808 zero = builder.makeUint8Constant(0);
5809 one = builder.makeUint8Constant(1);
5810 convOp = spv::OpSelect;
5811 break;
5812
5813 case glslang::EOpConvBoolToInt16:
5814 zero = builder.makeInt16Constant(0);
5815 one = builder.makeInt16Constant(1);
5816 convOp = spv::OpSelect;
5817 break;
5818
5819 case glslang::EOpConvBoolToUint16:
5820 zero = builder.makeUint16Constant(0);
5821 one = builder.makeUint16Constant(1);
5822 convOp = spv::OpSelect;
5823 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005824
John Kessenich140f3df2015-06-26 16:58:36 -06005825 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005826 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005827 if (op == glslang::EOpConvBoolToInt64)
5828 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005829 else
5830 zero = builder.makeIntConstant(0);
5831
5832 if (op == glslang::EOpConvBoolToInt64)
5833 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005834 else
5835 one = builder.makeIntConstant(1);
5836
John Kessenich140f3df2015-06-26 16:58:36 -06005837 convOp = spv::OpSelect;
5838 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005839
John Kessenich140f3df2015-06-26 16:58:36 -06005840 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005841 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005842 if (op == glslang::EOpConvBoolToUint64)
5843 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005844 else
5845 zero = builder.makeUintConstant(0);
5846
5847 if (op == glslang::EOpConvBoolToUint64)
5848 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005849 else
5850 one = builder.makeUintConstant(1);
5851
John Kessenich140f3df2015-06-26 16:58:36 -06005852 convOp = spv::OpSelect;
5853 break;
5854
John Kessenich66011cb2018-03-06 16:12:04 -07005855 case glslang::EOpConvInt8ToFloat16:
5856 case glslang::EOpConvInt8ToFloat:
5857 case glslang::EOpConvInt8ToDouble:
5858 case glslang::EOpConvInt16ToFloat16:
5859 case glslang::EOpConvInt16ToFloat:
5860 case glslang::EOpConvInt16ToDouble:
5861 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005862 case glslang::EOpConvIntToFloat:
5863 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005864 case glslang::EOpConvInt64ToFloat:
5865 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005866 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005867 convOp = spv::OpConvertSToF;
5868 break;
5869
John Kessenich66011cb2018-03-06 16:12:04 -07005870 case glslang::EOpConvUint8ToFloat16:
5871 case glslang::EOpConvUint8ToFloat:
5872 case glslang::EOpConvUint8ToDouble:
5873 case glslang::EOpConvUint16ToFloat16:
5874 case glslang::EOpConvUint16ToFloat:
5875 case glslang::EOpConvUint16ToDouble:
5876 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005877 case glslang::EOpConvUintToFloat:
5878 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005879 case glslang::EOpConvUint64ToFloat:
5880 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005881 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005882 convOp = spv::OpConvertUToF;
5883 break;
5884
5885 case glslang::EOpConvDoubleToFloat:
5886 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005887 case glslang::EOpConvDoubleToFloat16:
5888 case glslang::EOpConvFloat16ToDouble:
5889 case glslang::EOpConvFloatToFloat16:
5890 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005891 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005892 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005893 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005894 break;
5895
John Kessenich66011cb2018-03-06 16:12:04 -07005896 case glslang::EOpConvFloat16ToInt8:
5897 case glslang::EOpConvFloatToInt8:
5898 case glslang::EOpConvDoubleToInt8:
5899 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005900 case glslang::EOpConvFloatToInt16:
5901 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005902 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005903 case glslang::EOpConvFloatToInt:
5904 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005905 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005906 case glslang::EOpConvFloatToInt64:
5907 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005908 convOp = spv::OpConvertFToS;
5909 break;
5910
John Kessenich66011cb2018-03-06 16:12:04 -07005911 case glslang::EOpConvUint8ToInt8:
5912 case glslang::EOpConvInt8ToUint8:
5913 case glslang::EOpConvUint16ToInt16:
5914 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005915 case glslang::EOpConvUintToInt:
5916 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005917 case glslang::EOpConvUint64ToInt64:
5918 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005919 if (builder.isInSpecConstCodeGenMode()) {
5920 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005921 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5922 zero = builder.makeUint8Constant(0);
5923 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005924 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005925 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5926 zero = builder.makeUint64Constant(0);
5927 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005928 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005929 }
qining189b2032016-04-12 23:16:20 -04005930 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005931 // Use OpIAdd, instead of OpBitcast to do the conversion when
5932 // generating for OpSpecConstantOp instruction.
5933 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5934 }
5935 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005936 convOp = spv::OpBitcast;
5937 break;
5938
John Kessenich66011cb2018-03-06 16:12:04 -07005939 case glslang::EOpConvFloat16ToUint8:
5940 case glslang::EOpConvFloatToUint8:
5941 case glslang::EOpConvDoubleToUint8:
5942 case glslang::EOpConvFloat16ToUint16:
5943 case glslang::EOpConvFloatToUint16:
5944 case glslang::EOpConvDoubleToUint16:
5945 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005946 case glslang::EOpConvFloatToUint:
5947 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005948 case glslang::EOpConvFloatToUint64:
5949 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005950 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005951 convOp = spv::OpConvertFToU;
5952 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005953
John Kessenich66011cb2018-03-06 16:12:04 -07005954 case glslang::EOpConvInt8ToInt16:
5955 case glslang::EOpConvInt8ToInt:
5956 case glslang::EOpConvInt8ToInt64:
5957 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005958 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005959 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005960 case glslang::EOpConvIntToInt8:
5961 case glslang::EOpConvIntToInt16:
5962 case glslang::EOpConvIntToInt64:
5963 case glslang::EOpConvInt64ToInt8:
5964 case glslang::EOpConvInt64ToInt16:
5965 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005966 convOp = spv::OpSConvert;
5967 break;
5968
John Kessenich66011cb2018-03-06 16:12:04 -07005969 case glslang::EOpConvUint8ToUint16:
5970 case glslang::EOpConvUint8ToUint:
5971 case glslang::EOpConvUint8ToUint64:
5972 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005973 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005974 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005975 case glslang::EOpConvUintToUint8:
5976 case glslang::EOpConvUintToUint16:
5977 case glslang::EOpConvUintToUint64:
5978 case glslang::EOpConvUint64ToUint8:
5979 case glslang::EOpConvUint64ToUint16:
5980 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005981 convOp = spv::OpUConvert;
5982 break;
5983
John Kessenich66011cb2018-03-06 16:12:04 -07005984 case glslang::EOpConvInt8ToUint16:
5985 case glslang::EOpConvInt8ToUint:
5986 case glslang::EOpConvInt8ToUint64:
5987 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005988 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005989 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005990 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005991 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005992 case glslang::EOpConvIntToUint64:
5993 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005994 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005995 case glslang::EOpConvInt64ToUint:
5996 case glslang::EOpConvUint8ToInt16:
5997 case glslang::EOpConvUint8ToInt:
5998 case glslang::EOpConvUint8ToInt64:
5999 case glslang::EOpConvUint16ToInt8:
6000 case glslang::EOpConvUint16ToInt:
6001 case glslang::EOpConvUint16ToInt64:
6002 case glslang::EOpConvUintToInt8:
6003 case glslang::EOpConvUintToInt16:
6004 case glslang::EOpConvUintToInt64:
6005 case glslang::EOpConvUint64ToInt8:
6006 case glslang::EOpConvUint64ToInt16:
6007 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08006008 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06006009 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08006010
6011 if (builder.isInSpecConstCodeGenMode()) {
6012 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07006013 switch(op) {
6014 case glslang::EOpConvInt16ToUint8:
6015 case glslang::EOpConvIntToUint8:
6016 case glslang::EOpConvInt64ToUint8:
6017 case glslang::EOpConvUint16ToInt8:
6018 case glslang::EOpConvUintToInt8:
6019 case glslang::EOpConvUint64ToInt8:
6020 zero = builder.makeUint8Constant(0);
6021 break;
6022 case glslang::EOpConvInt8ToUint16:
6023 case glslang::EOpConvIntToUint16:
6024 case glslang::EOpConvInt64ToUint16:
6025 case glslang::EOpConvUint8ToInt16:
6026 case glslang::EOpConvUintToInt16:
6027 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08006028 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006029 break;
6030 case glslang::EOpConvInt8ToUint:
6031 case glslang::EOpConvInt16ToUint:
6032 case glslang::EOpConvInt64ToUint:
6033 case glslang::EOpConvUint8ToInt:
6034 case glslang::EOpConvUint16ToInt:
6035 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08006036 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006037 break;
6038 case glslang::EOpConvInt8ToUint64:
6039 case glslang::EOpConvInt16ToUint64:
6040 case glslang::EOpConvIntToUint64:
6041 case glslang::EOpConvUint8ToInt64:
6042 case glslang::EOpConvUint16ToInt64:
6043 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08006044 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07006045 break;
6046 default:
6047 assert(false && "Default missing");
6048 break;
6049 }
Rex Xu8ff43de2016-04-22 16:51:45 +08006050 zero = makeSmearedConstant(zero, vectorSize);
6051 // Use OpIAdd, instead of OpBitcast to do the conversion when
6052 // generating for OpSpecConstantOp instruction.
6053 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
6054 }
6055 // For normal run-time conversion instruction, use OpBitcast.
6056 convOp = spv::OpBitcast;
6057 break;
Jeff Bolz9f2aec42019-01-06 17:58:04 -06006058 case glslang::EOpConvUint64ToPtr:
6059 convOp = spv::OpConvertUToPtr;
6060 break;
6061 case glslang::EOpConvPtrToUint64:
6062 convOp = spv::OpConvertPtrToU;
6063 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006064 default:
6065 break;
6066 }
6067
6068 spv::Id result = 0;
6069 if (convOp == spv::OpNop)
6070 return result;
6071
6072 if (convOp == spv::OpSelect) {
6073 zero = makeSmearedConstant(zero, vectorSize);
6074 one = makeSmearedConstant(one, vectorSize);
6075 result = builder.createTriOp(convOp, destType, operand, one, zero);
6076 } else
6077 result = builder.createUnaryOp(convOp, destType, operand);
6078
John Kessenichead86222018-03-28 18:01:20 -06006079 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06006080 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06006081 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06006082}
6083
6084spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
6085{
6086 if (vectorSize == 0)
6087 return constant;
6088
6089 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
6090 std::vector<spv::Id> components;
6091 for (int c = 0; c < vectorSize; ++c)
6092 components.push_back(constant);
6093 return builder.makeCompositeConstant(vectorTypeId, components);
6094}
6095
John Kessenich426394d2015-07-23 10:22:48 -06006096// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07006097spv::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 -06006098{
6099 spv::Op opCode = spv::OpNop;
6100
6101 switch (op) {
6102 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08006103 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006104 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06006105 opCode = spv::OpAtomicIAdd;
6106 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06006107 case glslang::EOpAtomicCounterSubtract:
6108 opCode = spv::OpAtomicISub;
6109 break;
John Kessenich426394d2015-07-23 10:22:48 -06006110 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08006111 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006112 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08006113 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06006114 break;
6115 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08006116 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006117 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08006118 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06006119 break;
6120 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08006121 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006122 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06006123 opCode = spv::OpAtomicAnd;
6124 break;
6125 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08006126 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006127 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06006128 opCode = spv::OpAtomicOr;
6129 break;
6130 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08006131 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006132 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06006133 opCode = spv::OpAtomicXor;
6134 break;
6135 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08006136 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006137 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06006138 opCode = spv::OpAtomicExchange;
6139 break;
6140 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08006141 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06006142 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06006143 opCode = spv::OpAtomicCompareExchange;
6144 break;
6145 case glslang::EOpAtomicCounterIncrement:
6146 opCode = spv::OpAtomicIIncrement;
6147 break;
6148 case glslang::EOpAtomicCounterDecrement:
6149 opCode = spv::OpAtomicIDecrement;
6150 break;
6151 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006152 case glslang::EOpImageAtomicLoad:
6153 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06006154 opCode = spv::OpAtomicLoad;
6155 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05006156 case glslang::EOpAtomicStore:
6157 case glslang::EOpImageAtomicStore:
6158 opCode = spv::OpAtomicStore;
6159 break;
John Kessenich426394d2015-07-23 10:22:48 -06006160 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006161 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06006162 break;
6163 }
6164
Rex Xue8fe8b02017-09-26 15:42:56 +08006165 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
6166 builder.addCapability(spv::CapabilityInt64Atomics);
6167
John Kessenich426394d2015-07-23 10:22:48 -06006168 // Sort out the operands
6169 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05006170 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06006171 // - compare-exchange swaps the value and comparator
6172 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06006173 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05006174 spv::Id pointerId = 0, compareId = 0, valueId = 0;
6175 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
6176 spv::Id scopeId;
6177 if (glslangIntermediate->usingVulkanMemoryModel()) {
6178 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
6179 } else {
6180 scopeId = builder.makeUintConstant(spv::ScopeDevice);
6181 }
6182 // semantics default to relaxed
6183 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
6184 spv::Id semanticsId2 = semanticsId;
6185
6186 pointerId = operands[0];
6187 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
6188 // no additional operands
6189 } else if (opCode == spv::OpAtomicCompareExchange) {
6190 compareId = operands[1];
6191 valueId = operands[2];
6192 if (operands.size() > 3) {
6193 scopeId = operands[3];
6194 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
6195 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
6196 }
6197 } else if (opCode == spv::OpAtomicLoad) {
6198 if (operands.size() > 1) {
6199 scopeId = operands[1];
6200 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
6201 }
6202 } else {
6203 // atomic store or RMW
6204 valueId = operands[1];
6205 if (operands.size() > 2) {
6206 scopeId = operands[2];
6207 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
6208 }
Rex Xu04db3f52015-09-16 11:44:02 +08006209 }
John Kessenich426394d2015-07-23 10:22:48 -06006210
Jeff Bolz36831c92018-09-05 10:11:41 -05006211 // Check for capabilities
6212 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
6213 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6214 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6215 }
John Kessenich426394d2015-07-23 10:22:48 -06006216
Jeff Bolz36831c92018-09-05 10:11:41 -05006217 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
6218 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6219 }
John Kessenich48d6e792017-10-06 21:21:48 -06006220
Jeff Bolz36831c92018-09-05 10:11:41 -05006221 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
6222 spvAtomicOperands.push_back(pointerId);
6223 spvAtomicOperands.push_back(scopeId);
6224 spvAtomicOperands.push_back(semanticsId);
6225 if (opCode == spv::OpAtomicCompareExchange) {
6226 spvAtomicOperands.push_back(semanticsId2);
6227 spvAtomicOperands.push_back(valueId);
6228 spvAtomicOperands.push_back(compareId);
6229 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
6230 spvAtomicOperands.push_back(valueId);
6231 }
John Kessenich48d6e792017-10-06 21:21:48 -06006232
Jeff Bolz36831c92018-09-05 10:11:41 -05006233 if (opCode == spv::OpAtomicStore) {
6234 builder.createNoResultOp(opCode, spvAtomicOperands);
6235 return 0;
6236 } else {
6237 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
6238
6239 // GLSL and HLSL atomic-counter decrement return post-decrement value,
6240 // while SPIR-V returns pre-decrement value. Translate between these semantics.
6241 if (op == glslang::EOpAtomicCounterDecrement)
6242 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
6243
6244 return resultId;
6245 }
John Kessenich426394d2015-07-23 10:22:48 -06006246}
6247
John Kessenich91cef522016-05-05 16:45:40 -06006248// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08006249spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06006250{
Corentin Walleze7061422018-08-08 15:20:15 +02006251#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07006252 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6253 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02006254#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006255
Rex Xu51596642016-09-21 18:56:12 +08006256 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06006257 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08006258 spv::GroupOperation groupOperation = spv::GroupOperationMax;
6259
chaocf200da82016-12-20 12:44:35 -08006260 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
6261 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08006262 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
6263 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006264 } else if (op == glslang::EOpAnyInvocation ||
6265 op == glslang::EOpAllInvocations ||
6266 op == glslang::EOpAllInvocationsEqual) {
6267 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
6268 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08006269 } else {
6270 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04006271#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08006272 if (op == glslang::EOpMinInvocationsNonUniform ||
6273 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08006274 op == glslang::EOpAddInvocationsNonUniform ||
6275 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6276 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6277 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
6278 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
6279 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
6280 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08006281 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04006282#endif
Rex Xu51596642016-09-21 18:56:12 +08006283
Rex Xu9d93a232016-05-05 12:30:44 +08006284#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08006285 switch (op) {
6286 case glslang::EOpMinInvocations:
6287 case glslang::EOpMaxInvocations:
6288 case glslang::EOpAddInvocations:
6289 case glslang::EOpMinInvocationsNonUniform:
6290 case glslang::EOpMaxInvocationsNonUniform:
6291 case glslang::EOpAddInvocationsNonUniform:
6292 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006293 break;
6294 case glslang::EOpMinInvocationsInclusiveScan:
6295 case glslang::EOpMaxInvocationsInclusiveScan:
6296 case glslang::EOpAddInvocationsInclusiveScan:
6297 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6298 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6299 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6300 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006301 break;
6302 case glslang::EOpMinInvocationsExclusiveScan:
6303 case glslang::EOpMaxInvocationsExclusiveScan:
6304 case glslang::EOpAddInvocationsExclusiveScan:
6305 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6306 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6307 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6308 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006309 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006310 default:
6311 break;
Rex Xu430ef402016-10-14 17:22:23 +08006312 }
John Kessenich149afc32018-08-14 13:31:43 -06006313 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6314 spvGroupOperands.push_back(scope);
6315 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006316 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006317 spvGroupOperands.push_back(groupOp);
6318 }
Rex Xu9d93a232016-05-05 12:30:44 +08006319#endif
Rex Xu51596642016-09-21 18:56:12 +08006320 }
6321
John Kessenich149afc32018-08-14 13:31:43 -06006322 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6323 spv::IdImmediate op = { true, *opIt };
6324 spvGroupOperands.push_back(op);
6325 }
John Kessenich91cef522016-05-05 16:45:40 -06006326
6327 switch (op) {
6328 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006329 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006330 break;
John Kessenich91cef522016-05-05 16:45:40 -06006331 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006332 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006333 break;
John Kessenich91cef522016-05-05 16:45:40 -06006334 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006335 opCode = spv::OpSubgroupAllEqualKHR;
6336 break;
Rex Xu51596642016-09-21 18:56:12 +08006337 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006338 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006339 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006340 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006341 break;
6342 case glslang::EOpReadFirstInvocation:
6343 opCode = spv::OpSubgroupFirstInvocationKHR;
6344 break;
6345 case glslang::EOpBallot:
6346 {
6347 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6348 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6349 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6350 //
6351 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6352 //
6353 spv::Id uintType = builder.makeUintType(32);
6354 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6355 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6356
6357 std::vector<spv::Id> components;
6358 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6359 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6360
6361 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6362 return builder.createUnaryOp(spv::OpBitcast, typeId,
6363 builder.createCompositeConstruct(uvec2Type, components));
6364 }
6365
Rex Xu9d93a232016-05-05 12:30:44 +08006366#ifdef AMD_EXTENSIONS
6367 case glslang::EOpMinInvocations:
6368 case glslang::EOpMaxInvocations:
6369 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006370 case glslang::EOpMinInvocationsInclusiveScan:
6371 case glslang::EOpMaxInvocationsInclusiveScan:
6372 case glslang::EOpAddInvocationsInclusiveScan:
6373 case glslang::EOpMinInvocationsExclusiveScan:
6374 case glslang::EOpMaxInvocationsExclusiveScan:
6375 case glslang::EOpAddInvocationsExclusiveScan:
6376 if (op == glslang::EOpMinInvocations ||
6377 op == glslang::EOpMinInvocationsInclusiveScan ||
6378 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006379 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006380 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006381 else {
6382 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006383 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006384 else
Rex Xu51596642016-09-21 18:56:12 +08006385 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006386 }
Rex Xu430ef402016-10-14 17:22:23 +08006387 } else if (op == glslang::EOpMaxInvocations ||
6388 op == glslang::EOpMaxInvocationsInclusiveScan ||
6389 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006390 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006391 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006392 else {
6393 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006394 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006395 else
Rex Xu51596642016-09-21 18:56:12 +08006396 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006397 }
6398 } else {
6399 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006400 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006401 else
Rex Xu51596642016-09-21 18:56:12 +08006402 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006403 }
6404
Rex Xu2bbbe062016-08-23 15:41:05 +08006405 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006406 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006407
6408 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006409 case glslang::EOpMinInvocationsNonUniform:
6410 case glslang::EOpMaxInvocationsNonUniform:
6411 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006412 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6413 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6414 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6415 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6416 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6417 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6418 if (op == glslang::EOpMinInvocationsNonUniform ||
6419 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6420 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006421 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006422 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006423 else {
6424 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006425 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006426 else
Rex Xu51596642016-09-21 18:56:12 +08006427 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006428 }
6429 }
Rex Xu430ef402016-10-14 17:22:23 +08006430 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6431 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6432 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006433 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006434 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006435 else {
6436 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006437 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006438 else
Rex Xu51596642016-09-21 18:56:12 +08006439 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006440 }
6441 }
6442 else {
6443 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006444 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006445 else
Rex Xu51596642016-09-21 18:56:12 +08006446 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006447 }
6448
Rex Xu2bbbe062016-08-23 15:41:05 +08006449 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006450 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006451
6452 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006453#endif
John Kessenich91cef522016-05-05 16:45:40 -06006454 default:
6455 logger->missingFunctionality("invocation operation");
6456 return spv::NoResult;
6457 }
Rex Xu51596642016-09-21 18:56:12 +08006458
6459 assert(opCode != spv::OpNop);
6460 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006461}
6462
Rex Xu2bbbe062016-08-23 15:41:05 +08006463// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006464spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6465 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006466{
Rex Xub7072052016-09-26 15:53:40 +08006467#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006468 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6469 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006470 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006471 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006472 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6473 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6474 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006475#else
6476 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6477 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006478 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6479 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006480#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006481
6482 // Handle group invocation operations scalar by scalar.
6483 // The result type is the same type as the original type.
6484 // The algorithm is to:
6485 // - break the vector into scalars
6486 // - apply the operation to each scalar
6487 // - make a vector out the scalar results
6488
6489 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006490 int numComponents = builder.getNumComponents(operands[0]);
6491 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006492 std::vector<spv::Id> results;
6493
6494 // do each scalar op
6495 for (int comp = 0; comp < numComponents; ++comp) {
6496 std::vector<unsigned int> indexes;
6497 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006498 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6499 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006500 if (op == spv::OpSubgroupReadInvocationKHR) {
6501 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006502 spv::IdImmediate operand = { true, operands[1] };
6503 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006504 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006505 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6506 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006507 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006508 spv::IdImmediate operand = { true, operands[1] };
6509 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006510 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006511 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6512 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006513 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006514 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006515 spvGroupOperands.push_back(scalar);
6516 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006517
Rex Xub7072052016-09-26 15:53:40 +08006518 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006519 }
6520
6521 // put the pieces together
6522 return builder.createCompositeConstruct(typeId, results);
6523}
Rex Xu2bbbe062016-08-23 15:41:05 +08006524
John Kessenich66011cb2018-03-06 16:12:04 -07006525// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006526spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6527 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006528{
6529 // Add the required capabilities.
6530 switch (op) {
6531 case glslang::EOpSubgroupElect:
6532 builder.addCapability(spv::CapabilityGroupNonUniform);
6533 break;
6534 case glslang::EOpSubgroupAll:
6535 case glslang::EOpSubgroupAny:
6536 case glslang::EOpSubgroupAllEqual:
6537 builder.addCapability(spv::CapabilityGroupNonUniform);
6538 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6539 break;
6540 case glslang::EOpSubgroupBroadcast:
6541 case glslang::EOpSubgroupBroadcastFirst:
6542 case glslang::EOpSubgroupBallot:
6543 case glslang::EOpSubgroupInverseBallot:
6544 case glslang::EOpSubgroupBallotBitExtract:
6545 case glslang::EOpSubgroupBallotBitCount:
6546 case glslang::EOpSubgroupBallotInclusiveBitCount:
6547 case glslang::EOpSubgroupBallotExclusiveBitCount:
6548 case glslang::EOpSubgroupBallotFindLSB:
6549 case glslang::EOpSubgroupBallotFindMSB:
6550 builder.addCapability(spv::CapabilityGroupNonUniform);
6551 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6552 break;
6553 case glslang::EOpSubgroupShuffle:
6554 case glslang::EOpSubgroupShuffleXor:
6555 builder.addCapability(spv::CapabilityGroupNonUniform);
6556 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6557 break;
6558 case glslang::EOpSubgroupShuffleUp:
6559 case glslang::EOpSubgroupShuffleDown:
6560 builder.addCapability(spv::CapabilityGroupNonUniform);
6561 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6562 break;
6563 case glslang::EOpSubgroupAdd:
6564 case glslang::EOpSubgroupMul:
6565 case glslang::EOpSubgroupMin:
6566 case glslang::EOpSubgroupMax:
6567 case glslang::EOpSubgroupAnd:
6568 case glslang::EOpSubgroupOr:
6569 case glslang::EOpSubgroupXor:
6570 case glslang::EOpSubgroupInclusiveAdd:
6571 case glslang::EOpSubgroupInclusiveMul:
6572 case glslang::EOpSubgroupInclusiveMin:
6573 case glslang::EOpSubgroupInclusiveMax:
6574 case glslang::EOpSubgroupInclusiveAnd:
6575 case glslang::EOpSubgroupInclusiveOr:
6576 case glslang::EOpSubgroupInclusiveXor:
6577 case glslang::EOpSubgroupExclusiveAdd:
6578 case glslang::EOpSubgroupExclusiveMul:
6579 case glslang::EOpSubgroupExclusiveMin:
6580 case glslang::EOpSubgroupExclusiveMax:
6581 case glslang::EOpSubgroupExclusiveAnd:
6582 case glslang::EOpSubgroupExclusiveOr:
6583 case glslang::EOpSubgroupExclusiveXor:
6584 builder.addCapability(spv::CapabilityGroupNonUniform);
6585 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6586 break;
6587 case glslang::EOpSubgroupClusteredAdd:
6588 case glslang::EOpSubgroupClusteredMul:
6589 case glslang::EOpSubgroupClusteredMin:
6590 case glslang::EOpSubgroupClusteredMax:
6591 case glslang::EOpSubgroupClusteredAnd:
6592 case glslang::EOpSubgroupClusteredOr:
6593 case glslang::EOpSubgroupClusteredXor:
6594 builder.addCapability(spv::CapabilityGroupNonUniform);
6595 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6596 break;
6597 case glslang::EOpSubgroupQuadBroadcast:
6598 case glslang::EOpSubgroupQuadSwapHorizontal:
6599 case glslang::EOpSubgroupQuadSwapVertical:
6600 case glslang::EOpSubgroupQuadSwapDiagonal:
6601 builder.addCapability(spv::CapabilityGroupNonUniform);
6602 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6603 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006604#ifdef NV_EXTENSIONS
6605 case glslang::EOpSubgroupPartitionedAdd:
6606 case glslang::EOpSubgroupPartitionedMul:
6607 case glslang::EOpSubgroupPartitionedMin:
6608 case glslang::EOpSubgroupPartitionedMax:
6609 case glslang::EOpSubgroupPartitionedAnd:
6610 case glslang::EOpSubgroupPartitionedOr:
6611 case glslang::EOpSubgroupPartitionedXor:
6612 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6613 case glslang::EOpSubgroupPartitionedInclusiveMul:
6614 case glslang::EOpSubgroupPartitionedInclusiveMin:
6615 case glslang::EOpSubgroupPartitionedInclusiveMax:
6616 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6617 case glslang::EOpSubgroupPartitionedInclusiveOr:
6618 case glslang::EOpSubgroupPartitionedInclusiveXor:
6619 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6620 case glslang::EOpSubgroupPartitionedExclusiveMul:
6621 case glslang::EOpSubgroupPartitionedExclusiveMin:
6622 case glslang::EOpSubgroupPartitionedExclusiveMax:
6623 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6624 case glslang::EOpSubgroupPartitionedExclusiveOr:
6625 case glslang::EOpSubgroupPartitionedExclusiveXor:
6626 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6627 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6628 break;
6629#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006630 default: assert(0 && "Unhandled subgroup operation!");
6631 }
6632
6633 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6634 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6635 const bool isBool = typeProxy == glslang::EbtBool;
6636
6637 spv::Op opCode = spv::OpNop;
6638
6639 // Figure out which opcode to use.
6640 switch (op) {
6641 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6642 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6643 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6644 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6645 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6646 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6647 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6648 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6649 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6650 case glslang::EOpSubgroupBallotBitCount:
6651 case glslang::EOpSubgroupBallotInclusiveBitCount:
6652 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6653 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6654 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6655 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6656 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6657 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6658 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6659 case glslang::EOpSubgroupAdd:
6660 case glslang::EOpSubgroupInclusiveAdd:
6661 case glslang::EOpSubgroupExclusiveAdd:
6662 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006663#ifdef NV_EXTENSIONS
6664 case glslang::EOpSubgroupPartitionedAdd:
6665 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6666 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6667#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006668 if (isFloat) {
6669 opCode = spv::OpGroupNonUniformFAdd;
6670 } else {
6671 opCode = spv::OpGroupNonUniformIAdd;
6672 }
6673 break;
6674 case glslang::EOpSubgroupMul:
6675 case glslang::EOpSubgroupInclusiveMul:
6676 case glslang::EOpSubgroupExclusiveMul:
6677 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006678#ifdef NV_EXTENSIONS
6679 case glslang::EOpSubgroupPartitionedMul:
6680 case glslang::EOpSubgroupPartitionedInclusiveMul:
6681 case glslang::EOpSubgroupPartitionedExclusiveMul:
6682#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006683 if (isFloat) {
6684 opCode = spv::OpGroupNonUniformFMul;
6685 } else {
6686 opCode = spv::OpGroupNonUniformIMul;
6687 }
6688 break;
6689 case glslang::EOpSubgroupMin:
6690 case glslang::EOpSubgroupInclusiveMin:
6691 case glslang::EOpSubgroupExclusiveMin:
6692 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006693#ifdef NV_EXTENSIONS
6694 case glslang::EOpSubgroupPartitionedMin:
6695 case glslang::EOpSubgroupPartitionedInclusiveMin:
6696 case glslang::EOpSubgroupPartitionedExclusiveMin:
6697#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006698 if (isFloat) {
6699 opCode = spv::OpGroupNonUniformFMin;
6700 } else if (isUnsigned) {
6701 opCode = spv::OpGroupNonUniformUMin;
6702 } else {
6703 opCode = spv::OpGroupNonUniformSMin;
6704 }
6705 break;
6706 case glslang::EOpSubgroupMax:
6707 case glslang::EOpSubgroupInclusiveMax:
6708 case glslang::EOpSubgroupExclusiveMax:
6709 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006710#ifdef NV_EXTENSIONS
6711 case glslang::EOpSubgroupPartitionedMax:
6712 case glslang::EOpSubgroupPartitionedInclusiveMax:
6713 case glslang::EOpSubgroupPartitionedExclusiveMax:
6714#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006715 if (isFloat) {
6716 opCode = spv::OpGroupNonUniformFMax;
6717 } else if (isUnsigned) {
6718 opCode = spv::OpGroupNonUniformUMax;
6719 } else {
6720 opCode = spv::OpGroupNonUniformSMax;
6721 }
6722 break;
6723 case glslang::EOpSubgroupAnd:
6724 case glslang::EOpSubgroupInclusiveAnd:
6725 case glslang::EOpSubgroupExclusiveAnd:
6726 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006727#ifdef NV_EXTENSIONS
6728 case glslang::EOpSubgroupPartitionedAnd:
6729 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6730 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6731#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006732 if (isBool) {
6733 opCode = spv::OpGroupNonUniformLogicalAnd;
6734 } else {
6735 opCode = spv::OpGroupNonUniformBitwiseAnd;
6736 }
6737 break;
6738 case glslang::EOpSubgroupOr:
6739 case glslang::EOpSubgroupInclusiveOr:
6740 case glslang::EOpSubgroupExclusiveOr:
6741 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006742#ifdef NV_EXTENSIONS
6743 case glslang::EOpSubgroupPartitionedOr:
6744 case glslang::EOpSubgroupPartitionedInclusiveOr:
6745 case glslang::EOpSubgroupPartitionedExclusiveOr:
6746#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006747 if (isBool) {
6748 opCode = spv::OpGroupNonUniformLogicalOr;
6749 } else {
6750 opCode = spv::OpGroupNonUniformBitwiseOr;
6751 }
6752 break;
6753 case glslang::EOpSubgroupXor:
6754 case glslang::EOpSubgroupInclusiveXor:
6755 case glslang::EOpSubgroupExclusiveXor:
6756 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006757#ifdef NV_EXTENSIONS
6758 case glslang::EOpSubgroupPartitionedXor:
6759 case glslang::EOpSubgroupPartitionedInclusiveXor:
6760 case glslang::EOpSubgroupPartitionedExclusiveXor:
6761#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006762 if (isBool) {
6763 opCode = spv::OpGroupNonUniformLogicalXor;
6764 } else {
6765 opCode = spv::OpGroupNonUniformBitwiseXor;
6766 }
6767 break;
6768 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6769 case glslang::EOpSubgroupQuadSwapHorizontal:
6770 case glslang::EOpSubgroupQuadSwapVertical:
6771 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6772 default: assert(0 && "Unhandled subgroup operation!");
6773 }
6774
John Kessenich149afc32018-08-14 13:31:43 -06006775 // get the right Group Operation
6776 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006777 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006778 default:
6779 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006780 case glslang::EOpSubgroupBallotBitCount:
6781 case glslang::EOpSubgroupAdd:
6782 case glslang::EOpSubgroupMul:
6783 case glslang::EOpSubgroupMin:
6784 case glslang::EOpSubgroupMax:
6785 case glslang::EOpSubgroupAnd:
6786 case glslang::EOpSubgroupOr:
6787 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006788 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006789 break;
6790 case glslang::EOpSubgroupBallotInclusiveBitCount:
6791 case glslang::EOpSubgroupInclusiveAdd:
6792 case glslang::EOpSubgroupInclusiveMul:
6793 case glslang::EOpSubgroupInclusiveMin:
6794 case glslang::EOpSubgroupInclusiveMax:
6795 case glslang::EOpSubgroupInclusiveAnd:
6796 case glslang::EOpSubgroupInclusiveOr:
6797 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006798 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006799 break;
6800 case glslang::EOpSubgroupBallotExclusiveBitCount:
6801 case glslang::EOpSubgroupExclusiveAdd:
6802 case glslang::EOpSubgroupExclusiveMul:
6803 case glslang::EOpSubgroupExclusiveMin:
6804 case glslang::EOpSubgroupExclusiveMax:
6805 case glslang::EOpSubgroupExclusiveAnd:
6806 case glslang::EOpSubgroupExclusiveOr:
6807 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006808 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006809 break;
6810 case glslang::EOpSubgroupClusteredAdd:
6811 case glslang::EOpSubgroupClusteredMul:
6812 case glslang::EOpSubgroupClusteredMin:
6813 case glslang::EOpSubgroupClusteredMax:
6814 case glslang::EOpSubgroupClusteredAnd:
6815 case glslang::EOpSubgroupClusteredOr:
6816 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006817 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006818 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006819#ifdef NV_EXTENSIONS
6820 case glslang::EOpSubgroupPartitionedAdd:
6821 case glslang::EOpSubgroupPartitionedMul:
6822 case glslang::EOpSubgroupPartitionedMin:
6823 case glslang::EOpSubgroupPartitionedMax:
6824 case glslang::EOpSubgroupPartitionedAnd:
6825 case glslang::EOpSubgroupPartitionedOr:
6826 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006827 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006828 break;
6829 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6830 case glslang::EOpSubgroupPartitionedInclusiveMul:
6831 case glslang::EOpSubgroupPartitionedInclusiveMin:
6832 case glslang::EOpSubgroupPartitionedInclusiveMax:
6833 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6834 case glslang::EOpSubgroupPartitionedInclusiveOr:
6835 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006836 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006837 break;
6838 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6839 case glslang::EOpSubgroupPartitionedExclusiveMul:
6840 case glslang::EOpSubgroupPartitionedExclusiveMin:
6841 case glslang::EOpSubgroupPartitionedExclusiveMax:
6842 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6843 case glslang::EOpSubgroupPartitionedExclusiveOr:
6844 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006845 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006846 break;
6847#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006848 }
6849
John Kessenich149afc32018-08-14 13:31:43 -06006850 // build the instruction
6851 std::vector<spv::IdImmediate> spvGroupOperands;
6852
6853 // Every operation begins with the Execution Scope operand.
6854 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6855 spvGroupOperands.push_back(executionScope);
6856
6857 // Next, for all operations that use a Group Operation, push that as an operand.
6858 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006859 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006860 spvGroupOperands.push_back(groupOperand);
6861 }
6862
John Kessenich66011cb2018-03-06 16:12:04 -07006863 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006864 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6865 spv::IdImmediate operand = { true, *opIt };
6866 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006867 }
6868
6869 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006870 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006871 switch (op) {
6872 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006873 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6874 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6875 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6876 }
6877 if (directionId != spv::NoResult) {
6878 spv::IdImmediate direction = { true, directionId };
6879 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006880 }
6881
6882 return builder.createOp(opCode, typeId, spvGroupOperands);
6883}
6884
John Kessenich5e4b1242015-08-06 22:53:06 -06006885spv::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 -06006886{
John Kessenich66011cb2018-03-06 16:12:04 -07006887 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6888 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006889
John Kessenich140f3df2015-06-26 16:58:36 -06006890 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006891 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006892 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006893 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006894 spv::Id typeId0 = 0;
6895 if (consumedOperands > 0)
6896 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006897 spv::Id typeId1 = 0;
6898 if (consumedOperands > 1)
6899 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006900 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006901
6902 switch (op) {
6903 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006904 if (isFloat)
6905 libCall = spv::GLSLstd450FMin;
6906 else if (isUnsigned)
6907 libCall = spv::GLSLstd450UMin;
6908 else
6909 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006910 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006911 break;
6912 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006913 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006914 break;
6915 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006916 if (isFloat)
6917 libCall = spv::GLSLstd450FMax;
6918 else if (isUnsigned)
6919 libCall = spv::GLSLstd450UMax;
6920 else
6921 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006922 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006923 break;
6924 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006925 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006926 break;
6927 case glslang::EOpDot:
6928 opCode = spv::OpDot;
6929 break;
6930 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006931 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006932 break;
6933
6934 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006935 if (isFloat)
6936 libCall = spv::GLSLstd450FClamp;
6937 else if (isUnsigned)
6938 libCall = spv::GLSLstd450UClamp;
6939 else
6940 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006941 builder.promoteScalar(precision, operands.front(), operands[1]);
6942 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006943 break;
6944 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006945 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6946 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006947 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006948 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006949 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006950 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006951 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006952 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006953 break;
6954 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006955 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006956 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006957 break;
6958 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006959 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006960 builder.promoteScalar(precision, operands[0], operands[2]);
6961 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006962 break;
6963
6964 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006965 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006966 break;
6967 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006968 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006969 break;
6970 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006971 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006972 break;
6973 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006974 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006975 break;
6976 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006977 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006978 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006979 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006980#ifdef AMD_EXTENSIONS
6981 if (typeProxy == glslang::EbtFloat16)
6982 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6983#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006984 libCall = spv::GLSLstd450InterpolateAtSample;
6985 break;
6986 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006987#ifdef AMD_EXTENSIONS
6988 if (typeProxy == glslang::EbtFloat16)
6989 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6990#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006991 libCall = spv::GLSLstd450InterpolateAtOffset;
6992 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006993 case glslang::EOpAddCarry:
6994 opCode = spv::OpIAddCarry;
6995 typeId = builder.makeStructResultType(typeId0, typeId0);
6996 consumedOperands = 2;
6997 break;
6998 case glslang::EOpSubBorrow:
6999 opCode = spv::OpISubBorrow;
7000 typeId = builder.makeStructResultType(typeId0, typeId0);
7001 consumedOperands = 2;
7002 break;
7003 case glslang::EOpUMulExtended:
7004 opCode = spv::OpUMulExtended;
7005 typeId = builder.makeStructResultType(typeId0, typeId0);
7006 consumedOperands = 2;
7007 break;
7008 case glslang::EOpIMulExtended:
7009 opCode = spv::OpSMulExtended;
7010 typeId = builder.makeStructResultType(typeId0, typeId0);
7011 consumedOperands = 2;
7012 break;
7013 case glslang::EOpBitfieldExtract:
7014 if (isUnsigned)
7015 opCode = spv::OpBitFieldUExtract;
7016 else
7017 opCode = spv::OpBitFieldSExtract;
7018 break;
7019 case glslang::EOpBitfieldInsert:
7020 opCode = spv::OpBitFieldInsert;
7021 break;
7022
7023 case glslang::EOpFma:
7024 libCall = spv::GLSLstd450Fma;
7025 break;
7026 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007027 {
7028 libCall = spv::GLSLstd450FrexpStruct;
7029 assert(builder.isPointerType(typeId1));
7030 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08007031 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08007032#ifdef AMD_EXTENSIONS
7033 if (width == 16)
7034 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
7035 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
7036#endif
Rex Xu470026f2017-03-29 17:12:40 +08007037 if (builder.getNumComponents(operands[0]) == 1)
7038 frexpIntType = builder.makeIntegerType(width, true);
7039 else
7040 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
7041 typeId = builder.makeStructResultType(typeId0, frexpIntType);
7042 consumedOperands = 1;
7043 }
John Kessenich55e7d112015-11-15 21:33:39 -07007044 break;
7045 case glslang::EOpLdexp:
7046 libCall = spv::GLSLstd450Ldexp;
7047 break;
7048
Rex Xu574ab042016-04-14 16:53:07 +08007049 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08007050 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08007051
John Kessenich66011cb2018-03-06 16:12:04 -07007052 case glslang::EOpSubgroupBroadcast:
7053 case glslang::EOpSubgroupBallotBitExtract:
7054 case glslang::EOpSubgroupShuffle:
7055 case glslang::EOpSubgroupShuffleXor:
7056 case glslang::EOpSubgroupShuffleUp:
7057 case glslang::EOpSubgroupShuffleDown:
7058 case glslang::EOpSubgroupClusteredAdd:
7059 case glslang::EOpSubgroupClusteredMul:
7060 case glslang::EOpSubgroupClusteredMin:
7061 case glslang::EOpSubgroupClusteredMax:
7062 case glslang::EOpSubgroupClusteredAnd:
7063 case glslang::EOpSubgroupClusteredOr:
7064 case glslang::EOpSubgroupClusteredXor:
7065 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05007066#ifdef NV_EXTENSIONS
7067 case glslang::EOpSubgroupPartitionedAdd:
7068 case glslang::EOpSubgroupPartitionedMul:
7069 case glslang::EOpSubgroupPartitionedMin:
7070 case glslang::EOpSubgroupPartitionedMax:
7071 case glslang::EOpSubgroupPartitionedAnd:
7072 case glslang::EOpSubgroupPartitionedOr:
7073 case glslang::EOpSubgroupPartitionedXor:
7074 case glslang::EOpSubgroupPartitionedInclusiveAdd:
7075 case glslang::EOpSubgroupPartitionedInclusiveMul:
7076 case glslang::EOpSubgroupPartitionedInclusiveMin:
7077 case glslang::EOpSubgroupPartitionedInclusiveMax:
7078 case glslang::EOpSubgroupPartitionedInclusiveAnd:
7079 case glslang::EOpSubgroupPartitionedInclusiveOr:
7080 case glslang::EOpSubgroupPartitionedInclusiveXor:
7081 case glslang::EOpSubgroupPartitionedExclusiveAdd:
7082 case glslang::EOpSubgroupPartitionedExclusiveMul:
7083 case glslang::EOpSubgroupPartitionedExclusiveMin:
7084 case glslang::EOpSubgroupPartitionedExclusiveMax:
7085 case glslang::EOpSubgroupPartitionedExclusiveAnd:
7086 case glslang::EOpSubgroupPartitionedExclusiveOr:
7087 case glslang::EOpSubgroupPartitionedExclusiveXor:
7088#endif
John Kessenich66011cb2018-03-06 16:12:04 -07007089 return createSubgroupOperation(op, typeId, operands, typeProxy);
7090
Rex Xu9d93a232016-05-05 12:30:44 +08007091#ifdef AMD_EXTENSIONS
7092 case glslang::EOpSwizzleInvocations:
7093 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7094 libCall = spv::SwizzleInvocationsAMD;
7095 break;
7096 case glslang::EOpSwizzleInvocationsMasked:
7097 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7098 libCall = spv::SwizzleInvocationsMaskedAMD;
7099 break;
7100 case glslang::EOpWriteInvocation:
7101 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
7102 libCall = spv::WriteInvocationAMD;
7103 break;
7104
7105 case glslang::EOpMin3:
7106 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7107 if (isFloat)
7108 libCall = spv::FMin3AMD;
7109 else {
7110 if (isUnsigned)
7111 libCall = spv::UMin3AMD;
7112 else
7113 libCall = spv::SMin3AMD;
7114 }
7115 break;
7116 case glslang::EOpMax3:
7117 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7118 if (isFloat)
7119 libCall = spv::FMax3AMD;
7120 else {
7121 if (isUnsigned)
7122 libCall = spv::UMax3AMD;
7123 else
7124 libCall = spv::SMax3AMD;
7125 }
7126 break;
7127 case glslang::EOpMid3:
7128 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
7129 if (isFloat)
7130 libCall = spv::FMid3AMD;
7131 else {
7132 if (isUnsigned)
7133 libCall = spv::UMid3AMD;
7134 else
7135 libCall = spv::SMid3AMD;
7136 }
7137 break;
7138
7139 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08007140 if (typeProxy == glslang::EbtFloat16)
7141 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08007142 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
7143 libCall = spv::InterpolateAtVertexAMD;
7144 break;
7145#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05007146 case glslang::EOpBarrier:
7147 {
7148 // This is for the extended controlBarrier function, with four operands.
7149 // The unextended barrier() goes through createNoArgOperation.
7150 assert(operands.size() == 4);
7151 unsigned int executionScope = builder.getConstantScalar(operands[0]);
7152 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
7153 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
7154 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7155 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7156 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7157 }
7158 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
7159 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7160 }
7161 return 0;
7162 }
7163 break;
7164 case glslang::EOpMemoryBarrier:
7165 {
7166 // This is for the extended memoryBarrier function, with three operands.
7167 // The unextended memoryBarrier() goes through createNoArgOperation.
7168 assert(operands.size() == 3);
7169 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
7170 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
7171 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
7172 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
7173 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7174 }
7175 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
7176 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
7177 }
7178 return 0;
7179 }
7180 break;
Chao Chen3c366992018-09-19 11:41:59 -07007181
7182#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07007183 case glslang::EOpReportIntersectionNV:
7184 {
7185 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07007186 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07007187 }
7188 break;
7189 case glslang::EOpTraceNV:
7190 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07007191 builder.createNoResultOp(spv::OpTraceNV, operands);
7192 return 0;
7193 }
7194 break;
7195 case glslang::EOpExecuteCallableNV:
7196 {
7197 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07007198 return 0;
7199 }
7200 break;
Chao Chen3c366992018-09-19 11:41:59 -07007201 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
7202 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
7203 return 0;
7204#endif
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007205 case glslang::EOpCooperativeMatrixMulAdd:
7206 opCode = spv::OpCooperativeMatrixMulAddNV;
7207 break;
7208
John Kessenich140f3df2015-06-26 16:58:36 -06007209 default:
7210 return 0;
7211 }
7212
7213 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07007214 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05007215 // Use an extended instruction from the standard library.
7216 // Construct the call arguments, without modifying the original operands vector.
7217 // We might need the remaining arguments, e.g. in the EOpFrexp case.
7218 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08007219 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01007220 } else if (opCode == spv::OpDot && !isFloat) {
7221 // int dot(int, int)
7222 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
7223 const int componentCount = builder.getNumComponents(operands[0]);
7224 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
7225 builder.setPrecision(mulOp, precision);
7226 id = builder.createCompositeExtract(mulOp, typeId, 0);
7227 for (int i = 1; i < componentCount; ++i) {
7228 builder.setPrecision(id, precision);
7229 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
7230 }
John Kessenich2359bd02015-12-06 19:29:11 -07007231 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07007232 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06007233 case 0:
7234 // should all be handled by visitAggregate and createNoArgOperation
7235 assert(0);
7236 return 0;
7237 case 1:
7238 // should all be handled by createUnaryOperation
7239 assert(0);
7240 return 0;
7241 case 2:
7242 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
7243 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007244 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007245 // anything 3 or over doesn't have l-value operands, so all should be consumed
7246 assert(consumedOperands == operands.size());
7247 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06007248 break;
7249 }
7250 }
7251
John Kessenich55e7d112015-11-15 21:33:39 -07007252 // Decode the return types that were structures
7253 switch (op) {
7254 case glslang::EOpAddCarry:
7255 case glslang::EOpSubBorrow:
7256 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7257 id = builder.createCompositeExtract(id, typeId0, 0);
7258 break;
7259 case glslang::EOpUMulExtended:
7260 case glslang::EOpIMulExtended:
7261 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
7262 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
7263 break;
7264 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08007265 {
7266 assert(operands.size() == 2);
7267 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
7268 // "exp" is floating-point type (from HLSL intrinsic)
7269 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
7270 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
7271 builder.createStore(member1, operands[1]);
7272 } else
7273 // "exp" is integer type (from GLSL built-in function)
7274 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
7275 id = builder.createCompositeExtract(id, typeId0, 0);
7276 }
John Kessenich55e7d112015-11-15 21:33:39 -07007277 break;
7278 default:
7279 break;
7280 }
7281
John Kessenich32cfd492016-02-02 12:37:46 -07007282 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06007283}
7284
Rex Xu9d93a232016-05-05 12:30:44 +08007285// Intrinsics with no arguments (or no return value, and no precision).
7286spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06007287{
Jeff Bolz36831c92018-09-05 10:11:41 -05007288 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
7289 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06007290
7291 switch (op) {
7292 case glslang::EOpEmitVertex:
7293 builder.createNoResultOp(spv::OpEmitVertex);
7294 return 0;
7295 case glslang::EOpEndPrimitive:
7296 builder.createNoResultOp(spv::OpEndPrimitive);
7297 return 0;
7298 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007299 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007300 if (glslangIntermediate->usingVulkanMemoryModel()) {
7301 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7302 spv::MemorySemanticsOutputMemoryKHRMask |
7303 spv::MemorySemanticsAcquireReleaseMask);
7304 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7305 } else {
7306 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7307 }
John Kessenich82979362017-12-11 04:02:24 -07007308 } else {
7309 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7310 spv::MemorySemanticsWorkgroupMemoryMask |
7311 spv::MemorySemanticsAcquireReleaseMask);
7312 }
John Kessenich140f3df2015-06-26 16:58:36 -06007313 return 0;
7314 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007315 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7316 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007317 return 0;
7318 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007319 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7320 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007321 return 0;
7322 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007323 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7324 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007325 return 0;
7326 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007327 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7328 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007329 return 0;
7330 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007331 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7332 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007333 return 0;
7334 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007335 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7336 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007337 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007338 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007339 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007340 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007341 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007342 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007343 case glslang::EOpDeviceMemoryBarrier:
7344 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7345 spv::MemorySemanticsImageMemoryMask |
7346 spv::MemorySemanticsAcquireReleaseMask);
7347 return 0;
7348 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7349 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7350 spv::MemorySemanticsImageMemoryMask |
7351 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007352 return 0;
7353 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007354 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7355 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007356 return 0;
7357 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007358 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7359 spv::MemorySemanticsWorkgroupMemoryMask |
7360 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007361 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007362 case glslang::EOpSubgroupBarrier:
7363 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7364 spv::MemorySemanticsAcquireReleaseMask);
7365 return spv::NoResult;
7366 case glslang::EOpSubgroupMemoryBarrier:
7367 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7368 spv::MemorySemanticsAcquireReleaseMask);
7369 return spv::NoResult;
7370 case glslang::EOpSubgroupMemoryBarrierBuffer:
7371 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7372 spv::MemorySemanticsAcquireReleaseMask);
7373 return spv::NoResult;
7374 case glslang::EOpSubgroupMemoryBarrierImage:
7375 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7376 spv::MemorySemanticsAcquireReleaseMask);
7377 return spv::NoResult;
7378 case glslang::EOpSubgroupMemoryBarrierShared:
7379 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7380 spv::MemorySemanticsAcquireReleaseMask);
7381 return spv::NoResult;
7382 case glslang::EOpSubgroupElect: {
7383 std::vector<spv::Id> operands;
7384 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7385 }
Rex Xu9d93a232016-05-05 12:30:44 +08007386#ifdef AMD_EXTENSIONS
7387 case glslang::EOpTime:
7388 {
7389 std::vector<spv::Id> args; // Dummy arguments
7390 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7391 return builder.setPrecision(id, precision);
7392 }
7393#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007394#ifdef NV_EXTENSIONS
7395 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007396 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007397 return 0;
7398 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007399 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007400 return 0;
7401#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007402 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007403 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007404 return 0;
7405 }
7406}
7407
7408spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7409{
John Kessenich2f273362015-07-18 22:34:27 -06007410 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007411 spv::Id id;
7412 if (symbolValues.end() != iter) {
7413 id = iter->second;
7414 return id;
7415 }
7416
7417 // it was not found, create it
7418 id = createSpvVariable(symbol);
7419 symbolValues[symbol->getId()] = id;
7420
Rex Xuc884b4a2016-06-29 15:03:44 +08007421 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007422 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7423 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7424 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007425#ifdef NV_EXTENSIONS
7426 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7427#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007428 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007429 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007430 if (symbol->getQualifier().hasIndex())
7431 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7432 if (symbol->getQualifier().hasComponent())
7433 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007434 // atomic counters use this:
7435 if (symbol->getQualifier().hasOffset())
7436 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007437 }
7438
scygan2c864272016-05-18 18:09:17 +02007439 if (symbol->getQualifier().hasLocation())
7440 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007441 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007442 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007443 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007444 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007445 }
John Kessenich140f3df2015-06-26 16:58:36 -06007446 if (symbol->getQualifier().hasSet())
7447 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007448 else if (IsDescriptorResource(symbol->getType())) {
7449 // default to 0
7450 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7451 }
John Kessenich140f3df2015-06-26 16:58:36 -06007452 if (symbol->getQualifier().hasBinding())
7453 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
Jeff Bolz0a93cfb2018-12-11 20:53:59 -06007454 else if (IsDescriptorResource(symbol->getType())) {
7455 // default to 0
7456 builder.addDecoration(id, spv::DecorationBinding, 0);
7457 }
John Kessenich6c292d32016-02-15 20:58:50 -07007458 if (symbol->getQualifier().hasAttachment())
7459 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007460 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007461 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenichedaf5562017-12-15 06:21:46 -07007462 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007463 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007464 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7465 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7466 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7467 }
7468 if (symbol->getQualifier().hasXfbOffset())
7469 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007470 }
7471
Rex Xu1da878f2016-02-21 20:59:01 +08007472 if (symbol->getType().isImage()) {
7473 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007474 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007475 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007476 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007477 }
7478
John Kessenich140f3df2015-06-26 16:58:36 -06007479 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007480 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007481 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007482 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007483
John Kessenich5611c6d2018-04-05 11:25:02 -06007484 // nonuniform
7485 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7486
John Kessenichecba76f2017-01-06 00:34:48 -07007487#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007488 if (builtIn == spv::BuiltInSampleMask) {
7489 spv::Decoration decoration;
7490 // GL_NV_sample_mask_override_coverage extension
7491 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007492 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007493 else
7494 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007495 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007496 if (decoration != spv::DecorationMax) {
7497 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7498 }
7499 }
chaoc771d89f2017-01-13 01:10:53 -08007500 else if (builtIn == spv::BuiltInLayer) {
7501 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007502 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007503 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007504 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7505 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7506 }
John Kessenichb41bff62017-08-11 13:07:17 -06007507 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007508 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7509 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007510 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7511 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7512 }
7513 }
7514
chaoc6e5acae2016-12-20 13:28:52 -08007515 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007516 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007517 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007518 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7519 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007520 if (symbol->getQualifier().pervertexNV) {
7521 builder.addDecoration(id, spv::DecorationPerVertexNV);
7522 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7523 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7524 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007525#endif
7526
John Kessenich5d610ee2018-03-07 18:05:55 -07007527 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7528 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7529 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7530 symbol->getType().getQualifier().semanticName);
7531 }
7532
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007533 if (symbol->getBasicType() == glslang::EbtReference) {
7534 builder.addDecoration(id, symbol->getType().getQualifier().restrict ? spv::DecorationRestrictPointerEXT : spv::DecorationAliasedPointerEXT);
7535 }
7536
John Kessenich140f3df2015-06-26 16:58:36 -06007537 return id;
7538}
7539
Chao Chen3c366992018-09-19 11:41:59 -07007540#ifdef NV_EXTENSIONS
7541// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7542void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7543{
7544 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007545 if (qualifier.perPrimitiveNV) {
7546 // Need to add capability/extension for fragment shader.
7547 // Mesh shader already adds this by default.
7548 if (glslangIntermediate->getStage() == EShLangFragment) {
7549 builder.addCapability(spv::CapabilityMeshShadingNV);
7550 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7551 }
Chao Chen3c366992018-09-19 11:41:59 -07007552 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007553 }
Chao Chen3c366992018-09-19 11:41:59 -07007554 if (qualifier.perViewNV)
7555 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7556 if (qualifier.perTaskNV)
7557 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7558 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007559 if (qualifier.perPrimitiveNV) {
7560 // Need to add capability/extension for fragment shader.
7561 // Mesh shader already adds this by default.
7562 if (glslangIntermediate->getStage() == EShLangFragment) {
7563 builder.addCapability(spv::CapabilityMeshShadingNV);
7564 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7565 }
Chao Chen3c366992018-09-19 11:41:59 -07007566 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007567 }
Chao Chen3c366992018-09-19 11:41:59 -07007568 if (qualifier.perViewNV)
7569 builder.addDecoration(id, spv::DecorationPerViewNV);
7570 if (qualifier.perTaskNV)
7571 builder.addDecoration(id, spv::DecorationPerTaskNV);
7572 }
7573}
7574#endif
7575
John Kessenich55e7d112015-11-15 21:33:39 -07007576// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007577// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007578//
7579// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7580//
7581// Recursively walk the nodes. The nodes form a tree whose leaves are
7582// regular constants, which themselves are trees that createSpvConstant()
7583// recursively walks. So, this function walks the "top" of the tree:
7584// - emit specialization constant-building instructions for specConstant
7585// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007586spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007587{
John Kessenich7cc0e282016-03-20 00:46:02 -06007588 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007589
qining4f4bb812016-04-03 23:55:17 -04007590 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007591 if (! node.getQualifier().specConstant) {
7592 // hand off to the non-spec-constant path
7593 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7594 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007595 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007596 nextConst, false);
7597 }
7598
7599 // We now know we have a specialization constant to build
7600
John Kessenichd94c0032016-05-30 19:29:40 -06007601 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007602 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7603 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7604 std::vector<spv::Id> dimConstId;
7605 for (int dim = 0; dim < 3; ++dim) {
7606 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7607 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007608 if (specConst) {
7609 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7610 glslangIntermediate->getLocalSizeSpecId(dim));
7611 }
qining4f4bb812016-04-03 23:55:17 -04007612 }
7613 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7614 }
7615
7616 // An AST node labelled as specialization constant should be a symbol node.
7617 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7618 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007619 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007620 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007621 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7622 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7623 // will set the builder into spec constant op instruction generating mode.
7624 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007625 result = accessChainLoad(sub_tree->getType());
7626 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007627 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007628 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007629 } else {
7630 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007631 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007632 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007633 builder.addName(result, sn->getName().c_str());
7634 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007635 }
qining4f4bb812016-04-03 23:55:17 -04007636
7637 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7638 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007639 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007640 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007641}
7642
John Kessenich140f3df2015-06-26 16:58:36 -06007643// Use 'consts' as the flattened glslang source of scalar constants to recursively
7644// build the aggregate SPIR-V constant.
7645//
7646// If there are not enough elements present in 'consts', 0 will be substituted;
7647// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7648//
qining08408382016-03-21 09:51:37 -04007649spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007650{
7651 // vector of constants for SPIR-V
7652 std::vector<spv::Id> spvConsts;
7653
7654 // Type is used for struct and array constants
7655 spv::Id typeId = convertGlslangToSpvType(glslangType);
7656
7657 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007658 glslang::TType elementType(glslangType, 0);
7659 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007660 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007661 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007662 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007663 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007664 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
Jeff Bolz4605e2e2019-02-19 13:10:32 -06007665 } else if (glslangType.isCoopMat()) {
7666 glslang::TType componentType(glslangType.getBasicType());
7667 spvConsts.push_back(createSpvConstantFromConstUnionArray(componentType, consts, nextConst, false));
Jeff Bolz9f2aec42019-01-06 17:58:04 -06007668 } else if (glslangType.isStruct()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007669 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7670 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007671 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007672 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007673 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7674 bool zero = nextConst >= consts.size();
7675 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007676 case glslang::EbtInt8:
7677 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7678 break;
7679 case glslang::EbtUint8:
7680 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7681 break;
7682 case glslang::EbtInt16:
7683 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7684 break;
7685 case glslang::EbtUint16:
7686 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7687 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007688 case glslang::EbtInt:
7689 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7690 break;
7691 case glslang::EbtUint:
7692 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7693 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007694 case glslang::EbtInt64:
7695 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7696 break;
7697 case glslang::EbtUint64:
7698 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7699 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007700 case glslang::EbtFloat:
7701 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7702 break;
7703 case glslang::EbtDouble:
7704 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7705 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007706 case glslang::EbtFloat16:
7707 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7708 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007709 case glslang::EbtBool:
7710 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7711 break;
7712 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007713 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007714 break;
7715 }
7716 ++nextConst;
7717 }
7718 } else {
7719 // we have a non-aggregate (scalar) constant
7720 bool zero = nextConst >= consts.size();
7721 spv::Id scalar = 0;
7722 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007723 case glslang::EbtInt8:
7724 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7725 break;
7726 case glslang::EbtUint8:
7727 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7728 break;
7729 case glslang::EbtInt16:
7730 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7731 break;
7732 case glslang::EbtUint16:
7733 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7734 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007735 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007736 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007737 break;
7738 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007739 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007740 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007741 case glslang::EbtInt64:
7742 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7743 break;
7744 case glslang::EbtUint64:
7745 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7746 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007747 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007748 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007749 break;
7750 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007751 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007752 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007753 case glslang::EbtFloat16:
7754 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7755 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007756 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007757 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007758 break;
Jeff Bolz3fd12322019-03-05 23:27:09 -06007759 case glslang::EbtReference:
7760 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7761 scalar = builder.createUnaryOp(spv::OpBitcast, typeId, scalar);
7762 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007763 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007764 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007765 break;
7766 }
7767 ++nextConst;
7768 return scalar;
7769 }
7770
7771 return builder.makeCompositeConstant(typeId, spvConsts);
7772}
7773
John Kessenich7c1aa102015-10-15 13:29:11 -06007774// Return true if the node is a constant or symbol whose reading has no
7775// non-trivial observable cost or effect.
7776bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7777{
7778 // don't know what this is
7779 if (node == nullptr)
7780 return false;
7781
7782 // a constant is safe
7783 if (node->getAsConstantUnion() != nullptr)
7784 return true;
7785
7786 // not a symbol means non-trivial
7787 if (node->getAsSymbolNode() == nullptr)
7788 return false;
7789
7790 // a symbol, depends on what's being read
7791 switch (node->getType().getQualifier().storage) {
7792 case glslang::EvqTemporary:
7793 case glslang::EvqGlobal:
7794 case glslang::EvqIn:
7795 case glslang::EvqInOut:
7796 case glslang::EvqConst:
7797 case glslang::EvqConstReadOnly:
7798 case glslang::EvqUniform:
7799 return true;
7800 default:
7801 return false;
7802 }
qining25262b32016-05-06 17:25:16 -04007803}
John Kessenich7c1aa102015-10-15 13:29:11 -06007804
7805// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007806// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007807// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007808// Return true if trivial.
7809bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7810{
7811 if (node == nullptr)
7812 return false;
7813
John Kessenich84cc15f2017-05-24 16:44:47 -06007814 // count non scalars as trivial, as well as anything coming from HLSL
7815 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007816 return true;
7817
John Kessenich7c1aa102015-10-15 13:29:11 -06007818 // symbols and constants are trivial
7819 if (isTrivialLeaf(node))
7820 return true;
7821
7822 // otherwise, it needs to be a simple operation or one or two leaf nodes
7823
7824 // not a simple operation
7825 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7826 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7827 if (binaryNode == nullptr && unaryNode == nullptr)
7828 return false;
7829
7830 // not on leaf nodes
7831 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7832 return false;
7833
7834 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7835 return false;
7836 }
7837
7838 switch (node->getAsOperator()->getOp()) {
7839 case glslang::EOpLogicalNot:
7840 case glslang::EOpConvIntToBool:
7841 case glslang::EOpConvUintToBool:
7842 case glslang::EOpConvFloatToBool:
7843 case glslang::EOpConvDoubleToBool:
7844 case glslang::EOpEqual:
7845 case glslang::EOpNotEqual:
7846 case glslang::EOpLessThan:
7847 case glslang::EOpGreaterThan:
7848 case glslang::EOpLessThanEqual:
7849 case glslang::EOpGreaterThanEqual:
7850 case glslang::EOpIndexDirect:
7851 case glslang::EOpIndexDirectStruct:
7852 case glslang::EOpLogicalXor:
7853 case glslang::EOpAny:
7854 case glslang::EOpAll:
7855 return true;
7856 default:
7857 return false;
7858 }
7859}
7860
7861// Emit short-circuiting code, where 'right' is never evaluated unless
7862// the left side is true (for &&) or false (for ||).
7863spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7864{
7865 spv::Id boolTypeId = builder.makeBoolType();
7866
7867 // emit left operand
7868 builder.clearAccessChain();
7869 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007870 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007871
7872 // Operands to accumulate OpPhi operands
7873 std::vector<spv::Id> phiOperands;
7874 // accumulate left operand's phi information
7875 phiOperands.push_back(leftId);
7876 phiOperands.push_back(builder.getBuildPoint()->getId());
7877
7878 // Make the two kinds of operation symmetric with a "!"
7879 // || => emit "if (! left) result = right"
7880 // && => emit "if ( left) result = right"
7881 //
7882 // TODO: this runtime "not" for || could be avoided by adding functionality
7883 // to 'builder' to have an "else" without an "then"
7884 if (op == glslang::EOpLogicalOr)
7885 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7886
7887 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007888 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007889
7890 // emit right operand as the "then" part of the "if"
7891 builder.clearAccessChain();
7892 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007893 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007894
7895 // accumulate left operand's phi information
7896 phiOperands.push_back(rightId);
7897 phiOperands.push_back(builder.getBuildPoint()->getId());
7898
7899 // finish the "if"
7900 ifBuilder.makeEndIf();
7901
7902 // phi together the two results
7903 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7904}
7905
Frank Henigman541f7bb2018-01-16 00:18:26 -05007906#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007907// Return type Id of the imported set of extended instructions corresponds to the name.
7908// Import this set if it has not been imported yet.
7909spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7910{
7911 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7912 return extBuiltinMap[name];
7913 else {
Rex Xu51596642016-09-21 18:56:12 +08007914 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007915 spv::Id extBuiltins = builder.import(name);
7916 extBuiltinMap[name] = extBuiltins;
7917 return extBuiltins;
7918 }
7919}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007920#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007921
John Kessenich140f3df2015-06-26 16:58:36 -06007922}; // end anonymous namespace
7923
7924namespace glslang {
7925
John Kessenich68d78fd2015-07-12 19:28:10 -06007926void GetSpirvVersion(std::string& version)
7927{
John Kessenich9e55f632015-07-15 10:03:39 -06007928 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007929 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007930 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007931 version = buf;
7932}
7933
John Kessenicha372a3e2017-11-02 22:32:14 -06007934// For low-order part of the generator's magic number. Bump up
7935// when there is a change in the style (e.g., if SSA form changes,
7936// or a different instruction sequence to do something gets used).
7937int GetSpirvGeneratorVersion()
7938{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007939 // return 1; // start
7940 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007941 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007942 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007943 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007944 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7945 // versions 4 and 6 each generate OpArrayLength as it has long been done
7946 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007947}
7948
John Kessenich140f3df2015-06-26 16:58:36 -06007949// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007950void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007951{
7952 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007953 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007954 if (out.fail())
7955 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007956 for (int i = 0; i < (int)spirv.size(); ++i) {
7957 unsigned int word = spirv[i];
7958 out.write((const char*)&word, 4);
7959 }
7960 out.close();
7961}
7962
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007963// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007964void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007965{
7966 std::ofstream out;
7967 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007968 if (out.fail())
7969 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007970 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007971 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007972 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007973 if (varName != nullptr) {
7974 out << "\t #pragma once" << std::endl;
7975 out << "const uint32_t " << varName << "[] = {" << std::endl;
7976 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007977 const int WORDS_PER_LINE = 8;
7978 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7979 out << "\t";
7980 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7981 const unsigned int word = spirv[i + j];
7982 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7983 if (i + j + 1 < (int)spirv.size()) {
7984 out << ",";
7985 }
7986 }
7987 out << std::endl;
7988 }
Flavio15017db2017-02-15 14:29:33 -08007989 if (varName != nullptr) {
7990 out << "};";
7991 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007992 out.close();
7993}
7994
John Kessenich140f3df2015-06-26 16:58:36 -06007995//
7996// Set up the glslang traversal
7997//
John Kessenich4e11b612018-08-30 16:56:59 -06007998void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007999{
Lei Zhang17535f72016-05-04 15:55:59 -04008000 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06008001 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04008002}
8003
John Kessenich4e11b612018-08-30 16:56:59 -06008004void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06008005 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04008006{
John Kessenich140f3df2015-06-26 16:58:36 -06008007 TIntermNode* root = intermediate.getTreeRoot();
8008
8009 if (root == 0)
8010 return;
8011
John Kessenich4e11b612018-08-30 16:56:59 -06008012 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06008013 if (options == nullptr)
8014 options = &defaultOptions;
8015
John Kessenich4e11b612018-08-30 16:56:59 -06008016 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06008017
John Kessenich2b5ea9f2018-01-31 18:35:56 -07008018 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06008019 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07008020 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06008021 it.dumpSpv(spirv);
8022
GregFfb03a552018-03-29 11:49:14 -06008023#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06008024 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
8025 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06008026 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06008027 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06008028
John Kessenich4e11b612018-08-30 16:56:59 -06008029 if (options->validate)
8030 SpirvToolsValidate(intermediate, spirv, logger);
8031
John Kessenich717c80a2018-08-23 15:17:10 -06008032 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06008033 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06008034
GregFcd1f1692017-09-21 18:40:22 -06008035#endif
8036
John Kessenich4e11b612018-08-30 16:56:59 -06008037 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06008038}
8039
8040}; // end namespace glslang