blob: 4a59ffe62e6a6cda947f0b1118e35d29637705a9 [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.
3// Copyright (C) 2015-2016 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#ifdef NV_EXTENSIONS
53 #include "GLSL.ext.NV.h"
54#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060055}
John Kessenich140f3df2015-06-26 16:58:36 -060056
57// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020058#include "../glslang/MachineIndependent/localintermediate.h"
59#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060060#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050061#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060062
John Kessenich140f3df2015-06-26 16:58:36 -060063#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050064#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040065#include <list>
66#include <map>
67#include <stack>
68#include <string>
69#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060070
71namespace {
72
qining4c912612016-04-01 10:35:16 -040073namespace {
74class SpecConstantOpModeGuard {
75public:
76 SpecConstantOpModeGuard(spv::Builder* builder)
77 : builder_(builder) {
78 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040079 }
80 ~SpecConstantOpModeGuard() {
81 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
82 : builder_->setToNormalCodeGenMode();
83 }
qining40887662016-04-03 22:20:42 -040084 void turnOnSpecConstantOpMode() {
85 builder_->setToSpecConstCodeGenMode();
86 }
qining4c912612016-04-01 10:35:16 -040087
88private:
89 spv::Builder* builder_;
90 bool previous_flag_;
91};
John Kessenichead86222018-03-28 18:01:20 -060092
93struct OpDecorations {
94 spv::Decoration precision;
95 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -060096 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -060097};
98
99} // namespace
qining4c912612016-04-01 10:35:16 -0400100
John Kessenich140f3df2015-06-26 16:58:36 -0600101//
102// The main holder of information for translating glslang to SPIR-V.
103//
104// Derives from the AST walking base class.
105//
106class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
107public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700108 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
109 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700110 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600111
112 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
113 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
114 void visitConstantUnion(glslang::TIntermConstantUnion*);
115 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
116 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
117 void visitSymbol(glslang::TIntermSymbol* symbol);
118 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
119 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
120 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
121
John Kessenichfca82622016-11-26 13:23:20 -0700122 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700123 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600124
125protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700126 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
127 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
128
Rex Xu17ff3432016-10-14 17:41:45 +0800129 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800130 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600131 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
Jeff Bolz36831c92018-09-05 10:11:41 -0500132 spv::Builder::AccessChain::CoherentFlags TranslateCoherent(const glslang::TType& type);
133 spv::MemoryAccessMask TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
134 spv::ImageOperandsMask TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
135 spv::Scope TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags);
David Netoa901ffe2016-06-08 14:11:40 +0100136 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700137 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700138 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
139 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenicha2858d92018-01-31 08:11:18 -0700140 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, unsigned int& dependencyLength) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600141 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600142 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich140f3df2015-06-26 16:58:36 -0600143 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
144 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600145 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
146 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
147 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600148 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenichead86222018-03-28 18:01:20 -0600149 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
150 bool lastBufferBlockMember);
John Kessenich0e737842017-03-24 18:38:16 -0600151 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600152 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
153 glslang::TLayoutPacking, const glslang::TQualifier&);
154 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
155 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700156 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700157 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800158 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600159 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700160 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700161 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
162 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700163 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
164 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100165 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600166
John Kessenich6fccb3c2016-09-19 16:01:41 -0600167 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600168 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600169 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600170 void makeFunctions(const glslang::TIntermSequence&);
171 void makeGlobalInitializers(const glslang::TIntermSequence&);
172 void visitFunctions(const glslang::TIntermSequence&);
173 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800174 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600175 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
176 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600177 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
178
John Kessenichead86222018-03-28 18:01:20 -0600179 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
180 glslang::TBasicType typeProxy, bool reduceComparison = true);
181 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
182 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
183 glslang::TBasicType typeProxy);
184 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
185 glslang::TBasicType typeProxy);
186 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
187 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600188 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600189 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800190 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 +0800191 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800192 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700193 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600194 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 +0800195 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600196 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
Chao Chen3c366992018-09-19 11:41:59 -0700197#ifdef NV_EXTENSIONS
198 void addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier & qualifier);
199#endif
qining08408382016-03-21 09:51:37 -0400200 spv::Id createSpvConstant(const glslang::TIntermTyped&);
201 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600202 bool isTrivialLeaf(const glslang::TIntermTyped* node);
203 bool isTrivial(const glslang::TIntermTyped* node);
204 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500205#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800206 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500207#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700208 void addPre13Extension(const char* ext)
209 {
210 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
211 builder.addExtension(ext);
212 }
John Kessenich140f3df2015-06-26 16:58:36 -0600213
John Kessenich121853f2017-05-31 17:11:16 -0600214 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600215 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600216 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700217 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600218 int sequenceDepth;
219
Lei Zhang17535f72016-05-04 15:55:59 -0400220 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400221
John Kessenich140f3df2015-06-26 16:58:36 -0600222 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
223 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700224 bool inEntryPoint;
225 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700226 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 -0700227 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600228 const glslang::TIntermediate* glslangIntermediate;
229 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800230 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600231
John Kessenich2f273362015-07-18 22:34:27 -0600232 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600233 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600234 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700235 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700236 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
237 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600238 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700239 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
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;
559 // *coherent variables are implicitly nonprivate in GLSL
560 flags.nonprivate = type.getQualifier().nonprivate ||
Jeff Bolzab3c9652018-10-15 22:46:48 -0500561 flags.subgroupcoherent ||
562 flags.workgroupcoherent ||
563 flags.queuefamilycoherent ||
564 flags.devicecoherent ||
565 flags.coherent;
Jeff Bolz36831c92018-09-05 10:11:41 -0500566 flags.volatil = type.getQualifier().volatil;
567 flags.isImage = type.getBasicType() == glslang::EbtSampler;
568 return flags;
569}
570
571spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
572{
573 spv::Scope scope;
574 if (coherentFlags.coherent) {
575 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
576 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
577 } else if (coherentFlags.devicecoherent) {
578 scope = spv::ScopeDevice;
579 } else if (coherentFlags.queuefamilycoherent) {
580 scope = spv::ScopeQueueFamilyKHR;
581 } else if (coherentFlags.workgroupcoherent) {
582 scope = spv::ScopeWorkgroup;
583 } else if (coherentFlags.subgroupcoherent) {
584 scope = spv::ScopeSubgroup;
585 } else {
586 scope = spv::ScopeMax;
587 }
588 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
589 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
590 }
591 return scope;
592}
593
David Netoa901ffe2016-06-08 14:11:40 +0100594// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
595// associated capabilities when required. For some built-in variables, a capability
596// is generated only when using the variable in an executable instruction, but not when
597// just declaring a struct member variable with it. This is true for PointSize,
598// ClipDistance, and CullDistance.
599spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600600{
601 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700602 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600603 // Defer adding the capability until the built-in is actually used.
604 if (! memberDeclaration) {
605 switch (glslangIntermediate->getStage()) {
606 case EShLangGeometry:
607 builder.addCapability(spv::CapabilityGeometryPointSize);
608 break;
609 case EShLangTessControl:
610 case EShLangTessEvaluation:
611 builder.addCapability(spv::CapabilityTessellationPointSize);
612 break;
613 default:
614 break;
615 }
John Kessenich92187592016-02-01 13:45:25 -0700616 }
617 return spv::BuiltInPointSize;
618
John Kessenichebb50532016-05-16 19:22:05 -0600619 // These *Distance capabilities logically belong here, but if the member is declared and
620 // then never used, consumers of SPIR-V prefer the capability not be declared.
621 // They are now generated when used, rather than here when declared.
622 // Potentially, the specification should be more clear what the minimum
623 // use needed is to trigger the capability.
624 //
John Kessenich92187592016-02-01 13:45:25 -0700625 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100626 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800627 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700628 return spv::BuiltInClipDistance;
629
630 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100631 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800632 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700633 return spv::BuiltInCullDistance;
634
635 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600636 builder.addCapability(spv::CapabilityMultiViewport);
637 if (glslangIntermediate->getStage() == EShLangVertex ||
638 glslangIntermediate->getStage() == EShLangTessControl ||
639 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800640
John Kessenichba6a3c22017-09-13 13:22:50 -0600641 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
642 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800643 }
John Kessenich92187592016-02-01 13:45:25 -0700644 return spv::BuiltInViewportIndex;
645
John Kessenich5e801132016-02-15 11:09:46 -0700646 case glslang::EbvSampleId:
647 builder.addCapability(spv::CapabilitySampleRateShading);
648 return spv::BuiltInSampleId;
649
650 case glslang::EbvSamplePosition:
651 builder.addCapability(spv::CapabilitySampleRateShading);
652 return spv::BuiltInSamplePosition;
653
654 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700655 return spv::BuiltInSampleMask;
656
John Kessenich78a45572016-07-08 14:05:15 -0600657 case glslang::EbvLayer:
Chao Chen3c366992018-09-19 11:41:59 -0700658#ifdef NV_EXTENSIONS
659 if (glslangIntermediate->getStage() == EShLangMeshNV) {
660 return spv::BuiltInLayer;
661 }
662#endif
John Kessenichba6a3c22017-09-13 13:22:50 -0600663 builder.addCapability(spv::CapabilityGeometry);
664 if (glslangIntermediate->getStage() == EShLangVertex ||
665 glslangIntermediate->getStage() == EShLangTessControl ||
666 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800667
John Kessenichba6a3c22017-09-13 13:22:50 -0600668 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
669 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800670 }
John Kessenich78a45572016-07-08 14:05:15 -0600671 return spv::BuiltInLayer;
672
John Kessenich140f3df2015-06-26 16:58:36 -0600673 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600674 case glslang::EbvVertexId: return spv::BuiltInVertexId;
675 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700676 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
677 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800678
John Kessenichda581a22015-10-14 14:10:30 -0600679 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700680 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800681 builder.addCapability(spv::CapabilityDrawParameters);
682 return spv::BuiltInBaseVertex;
683
John Kessenichda581a22015-10-14 14:10:30 -0600684 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700685 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800686 builder.addCapability(spv::CapabilityDrawParameters);
687 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200688
John Kessenichda581a22015-10-14 14:10:30 -0600689 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700690 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800691 builder.addCapability(spv::CapabilityDrawParameters);
692 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200693
694 case glslang::EbvPrimitiveId:
695 if (glslangIntermediate->getStage() == EShLangFragment)
696 builder.addCapability(spv::CapabilityGeometry);
697 return spv::BuiltInPrimitiveId;
698
Rex Xu37cdcee2017-06-29 17:46:34 +0800699 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800700 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
701 builder.addCapability(spv::CapabilityStencilExportEXT);
702 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800703
John Kessenich140f3df2015-06-26 16:58:36 -0600704 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600705 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
706 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
707 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
708 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
709 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
710 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
711 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600712 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
713 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
714 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
715 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
716 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
717 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
718 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
719 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800720
Rex Xu574ab042016-04-14 16:53:07 +0800721 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800722 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800723 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
724 return spv::BuiltInSubgroupSize;
725
Rex Xu574ab042016-04-14 16:53:07 +0800726 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800727 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800728 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
729 return spv::BuiltInSubgroupLocalInvocationId;
730
Rex Xu574ab042016-04-14 16:53:07 +0800731 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800732 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
733 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
734 return spv::BuiltInSubgroupEqMaskKHR;
735
Rex Xu574ab042016-04-14 16:53:07 +0800736 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800737 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
738 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
739 return spv::BuiltInSubgroupGeMaskKHR;
740
Rex Xu574ab042016-04-14 16:53:07 +0800741 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800742 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
743 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
744 return spv::BuiltInSubgroupGtMaskKHR;
745
Rex Xu574ab042016-04-14 16:53:07 +0800746 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800747 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
748 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
749 return spv::BuiltInSubgroupLeMaskKHR;
750
Rex Xu574ab042016-04-14 16:53:07 +0800751 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800752 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
753 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
754 return spv::BuiltInSubgroupLtMaskKHR;
755
John Kessenich66011cb2018-03-06 16:12:04 -0700756 case glslang::EbvNumSubgroups:
757 builder.addCapability(spv::CapabilityGroupNonUniform);
758 return spv::BuiltInNumSubgroups;
759
760 case glslang::EbvSubgroupID:
761 builder.addCapability(spv::CapabilityGroupNonUniform);
762 return spv::BuiltInSubgroupId;
763
764 case glslang::EbvSubgroupSize2:
765 builder.addCapability(spv::CapabilityGroupNonUniform);
766 return spv::BuiltInSubgroupSize;
767
768 case glslang::EbvSubgroupInvocation2:
769 builder.addCapability(spv::CapabilityGroupNonUniform);
770 return spv::BuiltInSubgroupLocalInvocationId;
771
772 case glslang::EbvSubgroupEqMask2:
773 builder.addCapability(spv::CapabilityGroupNonUniform);
774 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
775 return spv::BuiltInSubgroupEqMask;
776
777 case glslang::EbvSubgroupGeMask2:
778 builder.addCapability(spv::CapabilityGroupNonUniform);
779 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
780 return spv::BuiltInSubgroupGeMask;
781
782 case glslang::EbvSubgroupGtMask2:
783 builder.addCapability(spv::CapabilityGroupNonUniform);
784 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
785 return spv::BuiltInSubgroupGtMask;
786
787 case glslang::EbvSubgroupLeMask2:
788 builder.addCapability(spv::CapabilityGroupNonUniform);
789 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
790 return spv::BuiltInSubgroupLeMask;
791
792 case glslang::EbvSubgroupLtMask2:
793 builder.addCapability(spv::CapabilityGroupNonUniform);
794 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
795 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800796#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800797 case glslang::EbvBaryCoordNoPersp:
798 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
799 return spv::BuiltInBaryCoordNoPerspAMD;
800
801 case glslang::EbvBaryCoordNoPerspCentroid:
802 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
803 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
804
805 case glslang::EbvBaryCoordNoPerspSample:
806 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
807 return spv::BuiltInBaryCoordNoPerspSampleAMD;
808
809 case glslang::EbvBaryCoordSmooth:
810 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
811 return spv::BuiltInBaryCoordSmoothAMD;
812
813 case glslang::EbvBaryCoordSmoothCentroid:
814 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
815 return spv::BuiltInBaryCoordSmoothCentroidAMD;
816
817 case glslang::EbvBaryCoordSmoothSample:
818 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
819 return spv::BuiltInBaryCoordSmoothSampleAMD;
820
821 case glslang::EbvBaryCoordPullModel:
822 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
823 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800824#endif
chaoc771d89f2017-01-13 01:10:53 -0800825
John Kessenich6c8aaac2017-02-27 01:20:51 -0700826 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700827 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700828 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700829 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700830
831 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700832 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700833 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700834 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700835
chaoc771d89f2017-01-13 01:10:53 -0800836#ifdef NV_EXTENSIONS
837 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800838 if (!memberDeclaration) {
839 builder.addExtension(spv::E_SPV_NV_viewport_array2);
840 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
841 }
chaoc771d89f2017-01-13 01:10:53 -0800842 return spv::BuiltInViewportMaskNV;
843 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800844 if (!memberDeclaration) {
845 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
846 builder.addCapability(spv::CapabilityShaderStereoViewNV);
847 }
chaoc771d89f2017-01-13 01:10:53 -0800848 return spv::BuiltInSecondaryPositionNV;
849 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800850 if (!memberDeclaration) {
851 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
852 builder.addCapability(spv::CapabilityShaderStereoViewNV);
853 }
chaoc771d89f2017-01-13 01:10:53 -0800854 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800855 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800856 if (!memberDeclaration) {
857 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
858 builder.addCapability(spv::CapabilityPerViewAttributesNV);
859 }
chaocdf3956c2017-02-14 14:52:34 -0800860 return spv::BuiltInPositionPerViewNV;
861 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800862 if (!memberDeclaration) {
863 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
864 builder.addCapability(spv::CapabilityPerViewAttributesNV);
865 }
chaocdf3956c2017-02-14 14:52:34 -0800866 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700867 case glslang::EbvFragFullyCoveredNV:
868 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
869 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
870 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700871 case glslang::EbvFragmentSizeNV:
872 builder.addExtension(spv::E_SPV_NV_shading_rate);
873 builder.addCapability(spv::CapabilityShadingRateNV);
874 return spv::BuiltInFragmentSizeNV;
875 case glslang::EbvInvocationsPerPixelNV:
876 builder.addExtension(spv::E_SPV_NV_shading_rate);
877 builder.addCapability(spv::CapabilityShadingRateNV);
878 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700879
880 // raytracing
881 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700882 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700883 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700884 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700885 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700886 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700887 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700888 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700889 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700890 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700891 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700892 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700893 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700894 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700895 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700896 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700897 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700898 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700899 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700900 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700901 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700902 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700903 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700904 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700905 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700906 return spv::BuiltInWorldToObjectNV;
907 case glslang::EbvIncomingRayFlagsNV:
908 return spv::BuiltInIncomingRayFlagsNV;
Chao Chen9eada4b2018-09-19 11:39:56 -0700909 case glslang::EbvBaryCoordNV:
910 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
911 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
912 return spv::BuiltInBaryCoordNV;
913 case glslang::EbvBaryCoordNoPerspNV:
914 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
915 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
916 return spv::BuiltInBaryCoordNoPerspNV;
Chao Chen3c366992018-09-19 11:41:59 -0700917 case glslang::EbvTaskCountNV:
918 return spv::BuiltInTaskCountNV;
919 case glslang::EbvPrimitiveCountNV:
920 return spv::BuiltInPrimitiveCountNV;
921 case glslang::EbvPrimitiveIndicesNV:
922 return spv::BuiltInPrimitiveIndicesNV;
923 case glslang::EbvClipDistancePerViewNV:
924 return spv::BuiltInClipDistancePerViewNV;
925 case glslang::EbvCullDistancePerViewNV:
926 return spv::BuiltInCullDistancePerViewNV;
927 case glslang::EbvLayerPerViewNV:
928 return spv::BuiltInLayerPerViewNV;
929 case glslang::EbvMeshViewCountNV:
930 return spv::BuiltInMeshViewCountNV;
931 case glslang::EbvMeshViewIndicesNV:
932 return spv::BuiltInMeshViewIndicesNV;
chaoc771d89f2017-01-13 01:10:53 -0800933#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800934 default:
935 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600936 }
937}
938
Rex Xufc618912015-09-09 16:42:49 +0800939// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700940spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800941{
942 assert(type.getBasicType() == glslang::EbtSampler);
943
John Kessenich5d0fa972016-02-15 11:57:00 -0700944 // Check for capabilities
945 switch (type.getQualifier().layoutFormat) {
946 case glslang::ElfRg32f:
947 case glslang::ElfRg16f:
948 case glslang::ElfR11fG11fB10f:
949 case glslang::ElfR16f:
950 case glslang::ElfRgba16:
951 case glslang::ElfRgb10A2:
952 case glslang::ElfRg16:
953 case glslang::ElfRg8:
954 case glslang::ElfR16:
955 case glslang::ElfR8:
956 case glslang::ElfRgba16Snorm:
957 case glslang::ElfRg16Snorm:
958 case glslang::ElfRg8Snorm:
959 case glslang::ElfR16Snorm:
960 case glslang::ElfR8Snorm:
961
962 case glslang::ElfRg32i:
963 case glslang::ElfRg16i:
964 case glslang::ElfRg8i:
965 case glslang::ElfR16i:
966 case glslang::ElfR8i:
967
968 case glslang::ElfRgb10a2ui:
969 case glslang::ElfRg32ui:
970 case glslang::ElfRg16ui:
971 case glslang::ElfRg8ui:
972 case glslang::ElfR16ui:
973 case glslang::ElfR8ui:
974 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
975 break;
976
977 default:
978 break;
979 }
980
981 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800982 switch (type.getQualifier().layoutFormat) {
983 case glslang::ElfNone: return spv::ImageFormatUnknown;
984 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
985 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
986 case glslang::ElfR32f: return spv::ImageFormatR32f;
987 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
988 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
989 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
990 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
991 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
992 case glslang::ElfR16f: return spv::ImageFormatR16f;
993 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
994 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
995 case glslang::ElfRg16: return spv::ImageFormatRg16;
996 case glslang::ElfRg8: return spv::ImageFormatRg8;
997 case glslang::ElfR16: return spv::ImageFormatR16;
998 case glslang::ElfR8: return spv::ImageFormatR8;
999 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1000 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1001 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1002 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1003 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1004 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1005 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1006 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1007 case glslang::ElfR32i: return spv::ImageFormatR32i;
1008 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1009 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1010 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1011 case glslang::ElfR16i: return spv::ImageFormatR16i;
1012 case glslang::ElfR8i: return spv::ImageFormatR8i;
1013 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1014 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1015 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1016 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1017 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1018 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1019 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1020 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1021 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1022 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001023 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001024 }
1025}
1026
John Kesseniche18fd202018-01-30 11:01:39 -07001027spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001028{
John Kesseniche18fd202018-01-30 11:01:39 -07001029 if (selectionNode.getFlatten())
1030 return spv::SelectionControlFlattenMask;
1031 if (selectionNode.getDontFlatten())
1032 return spv::SelectionControlDontFlattenMask;
1033 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001034}
1035
John Kesseniche18fd202018-01-30 11:01:39 -07001036spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001037{
John Kesseniche18fd202018-01-30 11:01:39 -07001038 if (switchNode.getFlatten())
1039 return spv::SelectionControlFlattenMask;
1040 if (switchNode.getDontFlatten())
1041 return spv::SelectionControlDontFlattenMask;
1042 return spv::SelectionControlMaskNone;
1043}
1044
John Kessenicha2858d92018-01-31 08:11:18 -07001045// return a non-0 dependency if the dependency argument must be set
1046spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
1047 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -07001048{
1049 spv::LoopControlMask control = spv::LoopControlMaskNone;
1050
1051 if (loopNode.getDontUnroll())
1052 control = control | spv::LoopControlDontUnrollMask;
1053 if (loopNode.getUnroll())
1054 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001055 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001056 control = control | spv::LoopControlDependencyInfiniteMask;
1057 else if (loopNode.getLoopDependency() > 0) {
1058 control = control | spv::LoopControlDependencyLengthMask;
1059 dependencyLength = loopNode.getLoopDependency();
1060 }
John Kesseniche18fd202018-01-30 11:01:39 -07001061
1062 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001063}
1064
John Kessenicha5c5fb62017-05-05 05:09:58 -06001065// Translate glslang type to SPIR-V storage class.
1066spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1067{
1068 if (type.getQualifier().isPipeInput())
1069 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001070 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001071 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001072
1073 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1074 type.getQualifier().storage == glslang::EvqUniform) {
1075 if (type.getBasicType() == glslang::EbtAtomicUint)
1076 return spv::StorageClassAtomicCounter;
1077 if (type.containsOpaque())
1078 return spv::StorageClassUniformConstant;
1079 }
1080
1081 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001082 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001083 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001084 }
1085
1086 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001087 if (type.getQualifier().layoutPushConstant)
1088 return spv::StorageClassPushConstant;
Chao Chenb50c02e2018-09-19 11:42:24 -07001089#ifdef NV_EXTENSIONS
1090 if (type.getQualifier().layoutShaderRecordNV)
Ashwin Leleff1783d2018-10-22 16:41:44 -07001091 return spv::StorageClassShaderRecordBufferNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001092#endif
John Kessenicha5c5fb62017-05-05 05:09:58 -06001093 if (type.getBasicType() == glslang::EbtBlock)
1094 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001095 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001096 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001097
1098 switch (type.getQualifier().storage) {
1099 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1100 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1101 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1102 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001103#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001104 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1105 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1106 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1107 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1108 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001109#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001110 default:
1111 assert(0);
1112 break;
1113 }
1114
1115 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001116}
1117
John Kessenich5611c6d2018-04-05 11:25:02 -06001118// Add capabilities pertaining to how an array is indexed.
1119void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1120 const glslang::TType& indexType)
1121{
1122 if (indexType.getQualifier().isNonUniform()) {
1123 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001124 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001125 if (baseType.getBasicType() == glslang::EbtSampler) {
1126 if (baseType.getQualifier().hasAttachment())
1127 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1128 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1129 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1130 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1131 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1132 else if (baseType.isImage())
1133 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1134 else if (baseType.isTexture())
1135 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1136 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1137 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1138 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1139 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1140 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1141 }
1142 } else {
1143 // assume a dynamically uniform index
1144 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001145 if (baseType.getQualifier().hasAttachment()) {
1146 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001147 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001148 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1149 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001150 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001151 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1152 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001153 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001154 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001155 }
1156 }
1157}
1158
qining25262b32016-05-06 17:25:16 -04001159// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001160// descriptor set.
1161bool IsDescriptorResource(const glslang::TType& type)
1162{
John Kessenichf7497e22016-03-08 21:36:22 -07001163 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001164 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001165 return type.getQualifier().isUniformOrBuffer() &&
1166#ifdef NV_EXTENSIONS
1167 ! type.getQualifier().layoutShaderRecordNV &&
1168#endif
1169 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001170
1171 // non block...
1172 // basically samplerXXX/subpass/sampler/texture are all included
1173 // if they are the global-scope-class, not the function parameter
1174 // (or local, if they ever exist) class.
1175 if (type.getBasicType() == glslang::EbtSampler)
1176 return type.getQualifier().isUniformOrBuffer();
1177
1178 // None of the above.
1179 return false;
1180}
1181
John Kesseniche0b6cad2015-12-24 10:30:13 -07001182void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1183{
1184 if (child.layoutMatrix == glslang::ElmNone)
1185 child.layoutMatrix = parent.layoutMatrix;
1186
1187 if (parent.invariant)
1188 child.invariant = true;
1189 if (parent.nopersp)
1190 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001191#ifdef AMD_EXTENSIONS
1192 if (parent.explicitInterp)
1193 child.explicitInterp = true;
1194#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001195 if (parent.flat)
1196 child.flat = true;
1197 if (parent.centroid)
1198 child.centroid = true;
1199 if (parent.patch)
1200 child.patch = true;
1201 if (parent.sample)
1202 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001203 if (parent.coherent)
1204 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001205 if (parent.devicecoherent)
1206 child.devicecoherent = true;
1207 if (parent.queuefamilycoherent)
1208 child.queuefamilycoherent = true;
1209 if (parent.workgroupcoherent)
1210 child.workgroupcoherent = true;
1211 if (parent.subgroupcoherent)
1212 child.subgroupcoherent = true;
1213 if (parent.nonprivate)
1214 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001215 if (parent.volatil)
1216 child.volatil = true;
1217 if (parent.restrict)
1218 child.restrict = true;
1219 if (parent.readonly)
1220 child.readonly = true;
1221 if (parent.writeonly)
1222 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001223#ifdef NV_EXTENSIONS
1224 if (parent.perPrimitiveNV)
1225 child.perPrimitiveNV = true;
1226 if (parent.perViewNV)
1227 child.perViewNV = true;
1228 if (parent.perTaskNV)
1229 child.perTaskNV = true;
1230#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001231}
1232
John Kessenichf2b7f332016-09-01 17:05:23 -06001233bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001234{
John Kessenich7b9fa252016-01-21 18:56:57 -07001235 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001236 // - struct members might inherit from a struct declaration
1237 // (note that non-block structs don't explicitly inherit,
1238 // only implicitly, meaning no decoration involved)
1239 // - affect decorations on the struct members
1240 // (note smooth does not, and expecting something like volatile
1241 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001242 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001243 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001244}
1245
John Kessenich140f3df2015-06-26 16:58:36 -06001246//
1247// Implement the TGlslangToSpvTraverser class.
1248//
1249
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001250TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001251 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1252 : TIntermTraverser(true, false, true),
1253 options(options),
1254 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001255 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001256 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001257 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001258 glslangIntermediate(glslangIntermediate)
1259{
1260 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1261
1262 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001263 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1264 glslangIntermediate->getVersion());
1265
John Kessenich121853f2017-05-31 17:11:16 -06001266 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001267 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001268 builder.setSourceFile(glslangIntermediate->getSourceFile());
1269
1270 // Set the source shader's text. If for SPV version 1.0, include
1271 // a preamble in comments stating the OpModuleProcessed instructions.
1272 // Otherwise, emit those as actual instructions.
1273 std::string text;
1274 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1275 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001276 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001277 text.append("// OpModuleProcessed ");
1278 text.append(processes[p]);
1279 text.append("\n");
1280 } else
1281 builder.addModuleProcessed(processes[p]);
1282 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001283 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001284 text.append("#line 1\n");
1285 text.append(glslangIntermediate->getSourceText());
1286 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -06001287 }
John Kessenich140f3df2015-06-26 16:58:36 -06001288 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz36831c92018-09-05 10:11:41 -05001289 if (glslangIntermediate->usingVulkanMemoryModel()) {
1290 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelVulkanKHR);
1291 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
1292 } else {
1293 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
1294 }
John Kessenicheee9d532016-09-19 18:09:30 -06001295 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1296 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001297
1298 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001299 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1300 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001301 builder.addSourceExtension(it->c_str());
1302
1303 // Add the top-level modes for this shader.
1304
John Kessenich92187592016-02-01 13:45:25 -07001305 if (glslangIntermediate->getXfbMode()) {
1306 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001307 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001308 }
John Kessenich140f3df2015-06-26 16:58:36 -06001309
1310 unsigned int mode;
1311 switch (glslangIntermediate->getStage()) {
1312 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001313 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001314 break;
1315
steve-lunarge7412492017-03-23 11:56:07 -06001316 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001317 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001318 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001319
steve-lunarge7412492017-03-23 11:56:07 -06001320 glslang::TLayoutGeometry primitive;
1321
1322 if (glslangIntermediate->getStage() == EShLangTessControl) {
1323 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1324 primitive = glslangIntermediate->getOutputPrimitive();
1325 } else {
1326 primitive = glslangIntermediate->getInputPrimitive();
1327 }
1328
1329 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001330 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1331 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1332 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001333 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001334 }
John Kessenich4016e382016-07-15 11:53:56 -06001335 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001336 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1337
John Kesseniche6903322015-10-13 16:29:02 -06001338 switch (glslangIntermediate->getVertexSpacing()) {
1339 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1340 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1341 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001342 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001343 }
John Kessenich4016e382016-07-15 11:53:56 -06001344 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001345 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1346
1347 switch (glslangIntermediate->getVertexOrder()) {
1348 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1349 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001350 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001351 }
John Kessenich4016e382016-07-15 11:53:56 -06001352 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001353 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1354
1355 if (glslangIntermediate->getPointMode())
1356 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001357 break;
1358
1359 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001360 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001361 switch (glslangIntermediate->getInputPrimitive()) {
1362 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1363 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1364 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001365 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001366 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001367 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001368 }
John Kessenich4016e382016-07-15 11:53:56 -06001369 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001370 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001371
John Kessenich140f3df2015-06-26 16:58:36 -06001372 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1373
1374 switch (glslangIntermediate->getOutputPrimitive()) {
1375 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1376 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1377 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001378 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001379 }
John Kessenich4016e382016-07-15 11:53:56 -06001380 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001381 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1382 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1383 break;
1384
1385 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001386 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001387 if (glslangIntermediate->getPixelCenterInteger())
1388 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001389
John Kessenich140f3df2015-06-26 16:58:36 -06001390 if (glslangIntermediate->getOriginUpperLeft())
1391 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001392 else
1393 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001394
1395 if (glslangIntermediate->getEarlyFragmentTests())
1396 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1397
chaocc1204522017-06-30 17:14:30 -07001398 if (glslangIntermediate->getPostDepthCoverage()) {
1399 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1400 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1401 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1402 }
1403
John Kesseniche6903322015-10-13 16:29:02 -06001404 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001405 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1406 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001407 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001408 }
John Kessenich4016e382016-07-15 11:53:56 -06001409 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001410 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1411
1412 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1413 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001414 break;
1415
1416 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001417 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001418 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1419 glslangIntermediate->getLocalSize(1),
1420 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001421#ifdef NV_EXTENSIONS
1422 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1423 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1424 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1425 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1426 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1427 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1428 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1429 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1430 }
1431#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001432 break;
1433
Chao Chen3c366992018-09-19 11:41:59 -07001434#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001435 case EShLangRayGenNV:
1436 case EShLangIntersectNV:
1437 case EShLangAnyHitNV:
1438 case EShLangClosestHitNV:
1439 case EShLangMissNV:
1440 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001441 builder.addCapability(spv::CapabilityRayTracingNV);
1442 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001443 break;
Chao Chen3c366992018-09-19 11:41:59 -07001444 case EShLangTaskNV:
1445 case EShLangMeshNV:
1446 builder.addCapability(spv::CapabilityMeshShadingNV);
1447 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1448 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1449 glslangIntermediate->getLocalSize(1),
1450 glslangIntermediate->getLocalSize(2));
1451 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1452 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1453 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1454
1455 switch (glslangIntermediate->getOutputPrimitive()) {
1456 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1457 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1458 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1459 default: mode = spv::ExecutionModeMax; break;
1460 }
1461 if (mode != spv::ExecutionModeMax)
1462 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1463 }
1464 break;
1465#endif
1466
John Kessenich140f3df2015-06-26 16:58:36 -06001467 default:
1468 break;
1469 }
John Kessenich140f3df2015-06-26 16:58:36 -06001470}
1471
John Kessenichfca82622016-11-26 13:23:20 -07001472// Finish creating SPV, after the traversal is complete.
1473void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001474{
John Kessenichf04c51b2018-08-03 15:56:12 -06001475 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001476 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001477 builder.setBuildPoint(shaderEntry->getLastBlock());
1478 builder.leaveFunction();
1479 }
1480
John Kessenich7ba63412015-12-20 17:37:07 -07001481 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001482 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1483 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001484
John Kessenichf04c51b2018-08-03 15:56:12 -06001485 // Add capabilities, extensions, remove unneeded decorations, etc.,
1486 // based on the resulting SPIR-V.
1487 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001488}
1489
John Kessenichfca82622016-11-26 13:23:20 -07001490// Write the SPV into 'out'.
1491void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001492{
John Kessenichfca82622016-11-26 13:23:20 -07001493 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001494}
1495
1496//
1497// Implement the traversal functions.
1498//
1499// Return true from interior nodes to have the external traversal
1500// continue on to children. Return false if children were
1501// already processed.
1502//
1503
1504//
qining25262b32016-05-06 17:25:16 -04001505// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001506// - uniform/input reads
1507// - output writes
1508// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1509// - something simple that degenerates into the last bullet
1510//
1511void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1512{
qining75d1d802016-04-06 14:42:01 -04001513 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1514 if (symbol->getType().getQualifier().isSpecConstant())
1515 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1516
John Kessenich140f3df2015-06-26 16:58:36 -06001517 // getSymbolId() will set up all the IO decorations on the first call.
1518 // Formal function parameters were mapped during makeFunctions().
1519 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001520
1521 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1522 if (builder.isPointer(id)) {
1523 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001524 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1525 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1526 iOSet.insert(id);
1527 }
John Kessenich7ba63412015-12-20 17:37:07 -07001528 }
1529
1530 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001531 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001532 // Prepare to generate code for the access
1533
1534 // L-value chains will be computed left to right. We're on the symbol now,
1535 // which is the left-most part of the access chain, so now is "clear" time,
1536 // followed by setting the base.
1537 builder.clearAccessChain();
1538
1539 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001540 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001541 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001542 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001543 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001544 // These are also pure R-values.
1545 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001546 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001547 builder.setAccessChainRValue(id);
1548 else
1549 builder.setAccessChainLValue(id);
1550 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001551
1552 // Process linkage-only nodes for any special additional interface work.
1553 if (linkageOnly) {
1554 if (glslangIntermediate->getHlslFunctionality1()) {
1555 // Map implicit counter buffers to their originating buffers, which should have been
1556 // seen by now, given earlier pruning of unused counters, and preservation of order
1557 // of declaration.
1558 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1559 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1560 // Save possible originating buffers for counter buffers, keyed by
1561 // making the potential counter-buffer name.
1562 std::string keyName = symbol->getName().c_str();
1563 keyName = glslangIntermediate->addCounterBufferName(keyName);
1564 counterOriginator[keyName] = symbol;
1565 } else {
1566 // Handle a counter buffer, by finding the saved originating buffer.
1567 std::string keyName = symbol->getName().c_str();
1568 auto it = counterOriginator.find(keyName);
1569 if (it != counterOriginator.end()) {
1570 id = getSymbolId(it->second);
1571 if (id != spv::NoResult) {
1572 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001573 if (counterId != spv::NoResult) {
1574 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001575 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001576 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001577 }
1578 }
1579 }
1580 }
1581 }
1582 }
John Kessenich140f3df2015-06-26 16:58:36 -06001583}
1584
1585bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1586{
John Kesseniche485c7a2017-05-31 18:50:53 -06001587 builder.setLine(node->getLoc().line);
1588
qining40887662016-04-03 22:20:42 -04001589 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1590 if (node->getType().getQualifier().isSpecConstant())
1591 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1592
John Kessenich140f3df2015-06-26 16:58:36 -06001593 // First, handle special cases
1594 switch (node->getOp()) {
1595 case glslang::EOpAssign:
1596 case glslang::EOpAddAssign:
1597 case glslang::EOpSubAssign:
1598 case glslang::EOpMulAssign:
1599 case glslang::EOpVectorTimesMatrixAssign:
1600 case glslang::EOpVectorTimesScalarAssign:
1601 case glslang::EOpMatrixTimesScalarAssign:
1602 case glslang::EOpMatrixTimesMatrixAssign:
1603 case glslang::EOpDivAssign:
1604 case glslang::EOpModAssign:
1605 case glslang::EOpAndAssign:
1606 case glslang::EOpInclusiveOrAssign:
1607 case glslang::EOpExclusiveOrAssign:
1608 case glslang::EOpLeftShiftAssign:
1609 case glslang::EOpRightShiftAssign:
1610 // A bin-op assign "a += b" means the same thing as "a = a + b"
1611 // where a is evaluated before b. For a simple assignment, GLSL
1612 // says to evaluate the left before the right. So, always, left
1613 // node then right node.
1614 {
1615 // get the left l-value, save it away
1616 builder.clearAccessChain();
1617 node->getLeft()->traverse(this);
1618 spv::Builder::AccessChain lValue = builder.getAccessChain();
1619
1620 // evaluate the right
1621 builder.clearAccessChain();
1622 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001623 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001624
1625 if (node->getOp() != glslang::EOpAssign) {
1626 // the left is also an r-value
1627 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001628 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001629
1630 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001631 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001632 TranslateNoContractionDecoration(node->getType().getQualifier()),
1633 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001634 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001635 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1636 node->getType().getBasicType());
1637
1638 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001639 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001640 }
1641
1642 // store the result
1643 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001644 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001645
1646 // assignments are expressions having an rValue after they are evaluated...
1647 builder.clearAccessChain();
1648 builder.setAccessChainRValue(rValue);
1649 }
1650 return false;
1651 case glslang::EOpIndexDirect:
1652 case glslang::EOpIndexDirectStruct:
1653 {
1654 // Get the left part of the access chain.
1655 node->getLeft()->traverse(this);
1656
1657 // Add the next element in the chain
1658
David Netoa901ffe2016-06-08 14:11:40 +01001659 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001660 if (! node->getLeft()->getType().isArray() &&
1661 node->getLeft()->getType().isVector() &&
1662 node->getOp() == glslang::EOpIndexDirect) {
1663 // This is essentially a hard-coded vector swizzle of size 1,
1664 // so short circuit the access-chain stuff with a swizzle.
1665 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001666 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001667 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001668 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001669 int spvIndex = glslangIndex;
1670 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1671 node->getOp() == glslang::EOpIndexDirectStruct)
1672 {
1673 // This may be, e.g., an anonymous block-member selection, which generally need
1674 // index remapping due to hidden members in anonymous blocks.
1675 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1676 assert(remapper.size() > 0);
1677 spvIndex = remapper[glslangIndex];
1678 }
John Kessenichebb50532016-05-16 19:22:05 -06001679
David Netoa901ffe2016-06-08 14:11:40 +01001680 // normal case for indexing array or structure or block
Jeff Bolz36831c92018-09-05 10:11:41 -05001681 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()));
David Netoa901ffe2016-06-08 14:11:40 +01001682
1683 // Add capabilities here for accessing PointSize and clip/cull distance.
1684 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001685 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001686 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001687 }
1688 }
1689 return false;
1690 case glslang::EOpIndexIndirect:
1691 {
1692 // Structure or array or vector indirection.
1693 // Will use native SPIR-V access-chain for struct and array indirection;
1694 // matrices are arrays of vectors, so will also work for a matrix.
1695 // Will use the access chain's 'component' for variable index into a vector.
1696
1697 // This adapter is building access chains left to right.
1698 // Set up the access chain to the left.
1699 node->getLeft()->traverse(this);
1700
1701 // save it so that computing the right side doesn't trash it
1702 spv::Builder::AccessChain partial = builder.getAccessChain();
1703
1704 // compute the next index in the chain
1705 builder.clearAccessChain();
1706 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001707 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001708
John Kessenich5611c6d2018-04-05 11:25:02 -06001709 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1710
John Kessenich140f3df2015-06-26 16:58:36 -06001711 // restore the saved access chain
1712 builder.setAccessChain(partial);
1713
1714 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001715 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001716 else
Jeff Bolz36831c92018-09-05 10:11:41 -05001717 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001718 }
1719 return false;
1720 case glslang::EOpVectorSwizzle:
1721 {
1722 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001723 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001724 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001725 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001726 }
1727 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001728 case glslang::EOpMatrixSwizzle:
1729 logger->missingFunctionality("matrix swizzle");
1730 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001731 case glslang::EOpLogicalOr:
1732 case glslang::EOpLogicalAnd:
1733 {
1734
1735 // These may require short circuiting, but can sometimes be done as straight
1736 // binary operations. The right operand must be short circuited if it has
1737 // side effects, and should probably be if it is complex.
1738 if (isTrivial(node->getRight()->getAsTyped()))
1739 break; // handle below as a normal binary operation
1740 // otherwise, we need to do dynamic short circuiting on the right operand
1741 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1742 builder.clearAccessChain();
1743 builder.setAccessChainRValue(result);
1744 }
1745 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001746 default:
1747 break;
1748 }
1749
1750 // Assume generic binary op...
1751
John Kessenich32cfd492016-02-02 12:37:46 -07001752 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001753 builder.clearAccessChain();
1754 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001755 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001756
John Kessenich32cfd492016-02-02 12:37:46 -07001757 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001758 builder.clearAccessChain();
1759 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001760 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001761
John Kessenich32cfd492016-02-02 12:37:46 -07001762 // get result
John Kessenichead86222018-03-28 18:01:20 -06001763 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001764 TranslateNoContractionDecoration(node->getType().getQualifier()),
1765 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001766 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001767 convertGlslangToSpvType(node->getType()), left, right,
1768 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001769
John Kessenich50e57562015-12-21 21:21:11 -07001770 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001771 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001772 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001773 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001774 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001775 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001776 return false;
1777 }
John Kessenich140f3df2015-06-26 16:58:36 -06001778}
1779
1780bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1781{
John Kesseniche485c7a2017-05-31 18:50:53 -06001782 builder.setLine(node->getLoc().line);
1783
qining40887662016-04-03 22:20:42 -04001784 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1785 if (node->getType().getQualifier().isSpecConstant())
1786 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1787
John Kessenichfc51d282015-08-19 13:34:18 -06001788 spv::Id result = spv::NoResult;
1789
1790 // try texturing first
1791 result = createImageTextureFunctionCall(node);
1792 if (result != spv::NoResult) {
1793 builder.clearAccessChain();
1794 builder.setAccessChainRValue(result);
1795
1796 return false; // done with this node
1797 }
1798
1799 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001800
1801 if (node->getOp() == glslang::EOpArrayLength) {
1802 // Quite special; won't want to evaluate the operand.
1803
John Kessenich5611c6d2018-04-05 11:25:02 -06001804 // Currently, the front-end does not allow .length() on an array until it is sized,
1805 // except for the last block membeor of an SSBO.
1806 // TODO: If this changes, link-time sized arrays might show up here, and need their
1807 // size extracted.
1808
John Kessenichc9a80832015-09-12 12:17:44 -06001809 // Normal .length() would have been constant folded by the front-end.
1810 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001811 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001812
John Kessenichc9a80832015-09-12 12:17:44 -06001813 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1814 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001815 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1816 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001817
1818 builder.clearAccessChain();
1819 builder.setAccessChainRValue(length);
1820
1821 return false;
1822 }
1823
John Kessenichfc51d282015-08-19 13:34:18 -06001824 // Start by evaluating the operand
1825
John Kessenich8c8505c2016-07-26 12:50:38 -06001826 // Does it need a swizzle inversion? If so, evaluation is inverted;
1827 // operate first on the swizzle base, then apply the swizzle.
1828 spv::Id invertedType = spv::NoType;
1829 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1830 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1831 invertedType = getInvertedSwizzleType(*node->getOperand());
1832
John Kessenich140f3df2015-06-26 16:58:36 -06001833 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001834 if (invertedType != spv::NoType)
1835 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1836 else
1837 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001838
Rex Xufc618912015-09-09 16:42:49 +08001839 spv::Id operand = spv::NoResult;
1840
1841 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1842 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001843 node->getOp() == glslang::EOpAtomicCounter ||
1844 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001845 operand = builder.accessChainGetLValue(); // Special case l-value operands
1846 else
John Kessenich32cfd492016-02-02 12:37:46 -07001847 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001848
John Kessenichead86222018-03-28 18:01:20 -06001849 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001850 TranslateNoContractionDecoration(node->getType().getQualifier()),
1851 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001852
1853 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001854 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001855 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001856
1857 // if not, then possibly an operation
1858 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001859 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001860
1861 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001862 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001863 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001864 builder.addDecoration(result, decorations.nonUniform);
1865 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001866
John Kessenich140f3df2015-06-26 16:58:36 -06001867 builder.clearAccessChain();
1868 builder.setAccessChainRValue(result);
1869
1870 return false; // done with this node
1871 }
1872
1873 // it must be a special case, check...
1874 switch (node->getOp()) {
1875 case glslang::EOpPostIncrement:
1876 case glslang::EOpPostDecrement:
1877 case glslang::EOpPreIncrement:
1878 case glslang::EOpPreDecrement:
1879 {
1880 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001881 spv::Id one = 0;
1882 if (node->getBasicType() == glslang::EbtFloat)
1883 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001884 else if (node->getBasicType() == glslang::EbtDouble)
1885 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001886 else if (node->getBasicType() == glslang::EbtFloat16)
1887 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001888 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1889 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001890 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1891 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001892 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1893 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001894 else
1895 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001896 glslang::TOperator op;
1897 if (node->getOp() == glslang::EOpPreIncrement ||
1898 node->getOp() == glslang::EOpPostIncrement)
1899 op = glslang::EOpAdd;
1900 else
1901 op = glslang::EOpSub;
1902
John Kessenichead86222018-03-28 18:01:20 -06001903 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001904 convertGlslangToSpvType(node->getType()), operand, one,
1905 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001906 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001907
1908 // The result of operation is always stored, but conditionally the
1909 // consumed result. The consumed result is always an r-value.
1910 builder.accessChainStore(result);
1911 builder.clearAccessChain();
1912 if (node->getOp() == glslang::EOpPreIncrement ||
1913 node->getOp() == glslang::EOpPreDecrement)
1914 builder.setAccessChainRValue(result);
1915 else
1916 builder.setAccessChainRValue(operand);
1917 }
1918
1919 return false;
1920
1921 case glslang::EOpEmitStreamVertex:
1922 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1923 return false;
1924 case glslang::EOpEndStreamPrimitive:
1925 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1926 return false;
1927
1928 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001929 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001930 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001931 }
John Kessenich140f3df2015-06-26 16:58:36 -06001932}
1933
1934bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1935{
qining27e04a02016-04-14 16:40:20 -04001936 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1937 if (node->getType().getQualifier().isSpecConstant())
1938 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1939
John Kessenichfc51d282015-08-19 13:34:18 -06001940 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001941 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1942 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001943
1944 // try texturing
1945 result = createImageTextureFunctionCall(node);
1946 if (result != spv::NoResult) {
1947 builder.clearAccessChain();
1948 builder.setAccessChainRValue(result);
1949
1950 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05001951 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08001952#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05001953 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08001954#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05001955 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08001956 // "imageStore" is a special case, which has no result
1957 return false;
1958 }
John Kessenichfc51d282015-08-19 13:34:18 -06001959
John Kessenich140f3df2015-06-26 16:58:36 -06001960 glslang::TOperator binOp = glslang::EOpNull;
1961 bool reduceComparison = true;
1962 bool isMatrix = false;
1963 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001964 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001965
1966 assert(node->getOp());
1967
John Kessenichf6640762016-08-01 19:44:00 -06001968 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001969
1970 switch (node->getOp()) {
1971 case glslang::EOpSequence:
1972 {
1973 if (preVisit)
1974 ++sequenceDepth;
1975 else
1976 --sequenceDepth;
1977
1978 if (sequenceDepth == 1) {
1979 // If this is the parent node of all the functions, we want to see them
1980 // early, so all call points have actual SPIR-V functions to reference.
1981 // In all cases, still let the traverser visit the children for us.
1982 makeFunctions(node->getAsAggregate()->getSequence());
1983
John Kessenich6fccb3c2016-09-19 16:01:41 -06001984 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001985 // anything else gets there, so visit out of order, doing them all now.
1986 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1987
John Kessenich6a60c2f2016-12-08 21:01:59 -07001988 // 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 -06001989 // so do them manually.
1990 visitFunctions(node->getAsAggregate()->getSequence());
1991
1992 return false;
1993 }
1994
1995 return true;
1996 }
1997 case glslang::EOpLinkerObjects:
1998 {
1999 if (visit == glslang::EvPreVisit)
2000 linkageOnly = true;
2001 else
2002 linkageOnly = false;
2003
2004 return true;
2005 }
2006 case glslang::EOpComma:
2007 {
2008 // processing from left to right naturally leaves the right-most
2009 // lying around in the access chain
2010 glslang::TIntermSequence& glslangOperands = node->getSequence();
2011 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2012 glslangOperands[i]->traverse(this);
2013
2014 return false;
2015 }
2016 case glslang::EOpFunction:
2017 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002018 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002019 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002020 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002021 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002022 } else {
2023 handleFunctionEntry(node);
2024 }
2025 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002026 if (inEntryPoint)
2027 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002028 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002029 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002030 }
2031
2032 return true;
2033 case glslang::EOpParameters:
2034 // Parameters will have been consumed by EOpFunction processing, but not
2035 // the body, so we still visited the function node's children, making this
2036 // child redundant.
2037 return false;
2038 case glslang::EOpFunctionCall:
2039 {
John Kesseniche485c7a2017-05-31 18:50:53 -06002040 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06002041 if (node->isUserDefined())
2042 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002043 // 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 -07002044 if (result) {
2045 builder.clearAccessChain();
2046 builder.setAccessChainRValue(result);
2047 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002048 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002049
2050 return false;
2051 }
2052 case glslang::EOpConstructMat2x2:
2053 case glslang::EOpConstructMat2x3:
2054 case glslang::EOpConstructMat2x4:
2055 case glslang::EOpConstructMat3x2:
2056 case glslang::EOpConstructMat3x3:
2057 case glslang::EOpConstructMat3x4:
2058 case glslang::EOpConstructMat4x2:
2059 case glslang::EOpConstructMat4x3:
2060 case glslang::EOpConstructMat4x4:
2061 case glslang::EOpConstructDMat2x2:
2062 case glslang::EOpConstructDMat2x3:
2063 case glslang::EOpConstructDMat2x4:
2064 case glslang::EOpConstructDMat3x2:
2065 case glslang::EOpConstructDMat3x3:
2066 case glslang::EOpConstructDMat3x4:
2067 case glslang::EOpConstructDMat4x2:
2068 case glslang::EOpConstructDMat4x3:
2069 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002070 case glslang::EOpConstructIMat2x2:
2071 case glslang::EOpConstructIMat2x3:
2072 case glslang::EOpConstructIMat2x4:
2073 case glslang::EOpConstructIMat3x2:
2074 case glslang::EOpConstructIMat3x3:
2075 case glslang::EOpConstructIMat3x4:
2076 case glslang::EOpConstructIMat4x2:
2077 case glslang::EOpConstructIMat4x3:
2078 case glslang::EOpConstructIMat4x4:
2079 case glslang::EOpConstructUMat2x2:
2080 case glslang::EOpConstructUMat2x3:
2081 case glslang::EOpConstructUMat2x4:
2082 case glslang::EOpConstructUMat3x2:
2083 case glslang::EOpConstructUMat3x3:
2084 case glslang::EOpConstructUMat3x4:
2085 case glslang::EOpConstructUMat4x2:
2086 case glslang::EOpConstructUMat4x3:
2087 case glslang::EOpConstructUMat4x4:
2088 case glslang::EOpConstructBMat2x2:
2089 case glslang::EOpConstructBMat2x3:
2090 case glslang::EOpConstructBMat2x4:
2091 case glslang::EOpConstructBMat3x2:
2092 case glslang::EOpConstructBMat3x3:
2093 case glslang::EOpConstructBMat3x4:
2094 case glslang::EOpConstructBMat4x2:
2095 case glslang::EOpConstructBMat4x3:
2096 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002097 case glslang::EOpConstructF16Mat2x2:
2098 case glslang::EOpConstructF16Mat2x3:
2099 case glslang::EOpConstructF16Mat2x4:
2100 case glslang::EOpConstructF16Mat3x2:
2101 case glslang::EOpConstructF16Mat3x3:
2102 case glslang::EOpConstructF16Mat3x4:
2103 case glslang::EOpConstructF16Mat4x2:
2104 case glslang::EOpConstructF16Mat4x3:
2105 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002106 isMatrix = true;
2107 // fall through
2108 case glslang::EOpConstructFloat:
2109 case glslang::EOpConstructVec2:
2110 case glslang::EOpConstructVec3:
2111 case glslang::EOpConstructVec4:
2112 case glslang::EOpConstructDouble:
2113 case glslang::EOpConstructDVec2:
2114 case glslang::EOpConstructDVec3:
2115 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002116 case glslang::EOpConstructFloat16:
2117 case glslang::EOpConstructF16Vec2:
2118 case glslang::EOpConstructF16Vec3:
2119 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002120 case glslang::EOpConstructBool:
2121 case glslang::EOpConstructBVec2:
2122 case glslang::EOpConstructBVec3:
2123 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002124 case glslang::EOpConstructInt8:
2125 case glslang::EOpConstructI8Vec2:
2126 case glslang::EOpConstructI8Vec3:
2127 case glslang::EOpConstructI8Vec4:
2128 case glslang::EOpConstructUint8:
2129 case glslang::EOpConstructU8Vec2:
2130 case glslang::EOpConstructU8Vec3:
2131 case glslang::EOpConstructU8Vec4:
2132 case glslang::EOpConstructInt16:
2133 case glslang::EOpConstructI16Vec2:
2134 case glslang::EOpConstructI16Vec3:
2135 case glslang::EOpConstructI16Vec4:
2136 case glslang::EOpConstructUint16:
2137 case glslang::EOpConstructU16Vec2:
2138 case glslang::EOpConstructU16Vec3:
2139 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002140 case glslang::EOpConstructInt:
2141 case glslang::EOpConstructIVec2:
2142 case glslang::EOpConstructIVec3:
2143 case glslang::EOpConstructIVec4:
2144 case glslang::EOpConstructUint:
2145 case glslang::EOpConstructUVec2:
2146 case glslang::EOpConstructUVec3:
2147 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002148 case glslang::EOpConstructInt64:
2149 case glslang::EOpConstructI64Vec2:
2150 case glslang::EOpConstructI64Vec3:
2151 case glslang::EOpConstructI64Vec4:
2152 case glslang::EOpConstructUint64:
2153 case glslang::EOpConstructU64Vec2:
2154 case glslang::EOpConstructU64Vec3:
2155 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002156 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002157 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06002158 {
John Kesseniche485c7a2017-05-31 18:50:53 -06002159 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06002160 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002161 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002162 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002163 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002164 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07002165 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002166 std::vector<spv::Id> constituents;
2167 for (int c = 0; c < (int)arguments.size(); ++c)
2168 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002169 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002170 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002171 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002172 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002173 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002174
2175 builder.clearAccessChain();
2176 builder.setAccessChainRValue(constructed);
2177
2178 return false;
2179 }
2180
2181 // These six are component-wise compares with component-wise results.
2182 // Forward on to createBinaryOperation(), requesting a vector result.
2183 case glslang::EOpLessThan:
2184 case glslang::EOpGreaterThan:
2185 case glslang::EOpLessThanEqual:
2186 case glslang::EOpGreaterThanEqual:
2187 case glslang::EOpVectorEqual:
2188 case glslang::EOpVectorNotEqual:
2189 {
2190 // Map the operation to a binary
2191 binOp = node->getOp();
2192 reduceComparison = false;
2193 switch (node->getOp()) {
2194 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2195 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2196 default: binOp = node->getOp(); break;
2197 }
2198
2199 break;
2200 }
2201 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002202 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002203 binOp = glslang::EOpMul;
2204 break;
2205 case glslang::EOpOuterProduct:
2206 // two vectors multiplied to make a matrix
2207 binOp = glslang::EOpOuterProduct;
2208 break;
2209 case glslang::EOpDot:
2210 {
qining25262b32016-05-06 17:25:16 -04002211 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002212 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002213 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002214 binOp = glslang::EOpMul;
2215 break;
2216 }
2217 case glslang::EOpMod:
2218 // when an aggregate, this is the floating-point mod built-in function,
2219 // which can be emitted by the one in createBinaryOperation()
2220 binOp = glslang::EOpMod;
2221 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002222 case glslang::EOpEmitVertex:
2223 case glslang::EOpEndPrimitive:
2224 case glslang::EOpBarrier:
2225 case glslang::EOpMemoryBarrier:
2226 case glslang::EOpMemoryBarrierAtomicCounter:
2227 case glslang::EOpMemoryBarrierBuffer:
2228 case glslang::EOpMemoryBarrierImage:
2229 case glslang::EOpMemoryBarrierShared:
2230 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002231 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002232 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002233 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002234 case glslang::EOpWorkgroupMemoryBarrier:
2235 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002236 case glslang::EOpSubgroupBarrier:
2237 case glslang::EOpSubgroupMemoryBarrier:
2238 case glslang::EOpSubgroupMemoryBarrierBuffer:
2239 case glslang::EOpSubgroupMemoryBarrierImage:
2240 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002241 noReturnValue = true;
2242 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2243 break;
2244
Jeff Bolz36831c92018-09-05 10:11:41 -05002245 case glslang::EOpAtomicStore:
2246 noReturnValue = true;
2247 // fallthrough
2248 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002249 case glslang::EOpAtomicAdd:
2250 case glslang::EOpAtomicMin:
2251 case glslang::EOpAtomicMax:
2252 case glslang::EOpAtomicAnd:
2253 case glslang::EOpAtomicOr:
2254 case glslang::EOpAtomicXor:
2255 case glslang::EOpAtomicExchange:
2256 case glslang::EOpAtomicCompSwap:
2257 atomic = true;
2258 break;
2259
John Kessenich0d0c6d32017-07-23 16:08:26 -06002260 case glslang::EOpAtomicCounterAdd:
2261 case glslang::EOpAtomicCounterSubtract:
2262 case glslang::EOpAtomicCounterMin:
2263 case glslang::EOpAtomicCounterMax:
2264 case glslang::EOpAtomicCounterAnd:
2265 case glslang::EOpAtomicCounterOr:
2266 case glslang::EOpAtomicCounterXor:
2267 case glslang::EOpAtomicCounterExchange:
2268 case glslang::EOpAtomicCounterCompSwap:
2269 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2270 builder.addCapability(spv::CapabilityAtomicStorageOps);
2271 atomic = true;
2272 break;
2273
Chao Chen3c366992018-09-19 11:41:59 -07002274#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002275 case glslang::EOpIgnoreIntersectionNV:
2276 case glslang::EOpTerminateRayNV:
2277 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002278 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002279 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2280 noReturnValue = true;
2281 break;
2282#endif
2283
John Kessenich140f3df2015-06-26 16:58:36 -06002284 default:
2285 break;
2286 }
2287
2288 //
2289 // See if it maps to a regular operation.
2290 //
John Kessenich140f3df2015-06-26 16:58:36 -06002291 if (binOp != glslang::EOpNull) {
2292 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2293 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2294 assert(left && right);
2295
2296 builder.clearAccessChain();
2297 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002298 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002299
2300 builder.clearAccessChain();
2301 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002302 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002303
John Kesseniche485c7a2017-05-31 18:50:53 -06002304 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06002305 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002306 TranslateNoContractionDecoration(node->getType().getQualifier()),
2307 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002308 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002309 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002310 left->getType().getBasicType(), reduceComparison);
2311
2312 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002313 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002314 builder.clearAccessChain();
2315 builder.setAccessChainRValue(result);
2316
2317 return false;
2318 }
2319
John Kessenich426394d2015-07-23 10:22:48 -06002320 //
2321 // Create the list of operands.
2322 //
John Kessenich140f3df2015-06-26 16:58:36 -06002323 glslang::TIntermSequence& glslangOperands = node->getSequence();
2324 std::vector<spv::Id> operands;
2325 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002326 // special case l-value operands; there are just a few
2327 bool lvalue = false;
2328 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002329 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002330 case glslang::EOpModf:
2331 if (arg == 1)
2332 lvalue = true;
2333 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002334 case glslang::EOpInterpolateAtSample:
2335 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002336#ifdef AMD_EXTENSIONS
2337 case glslang::EOpInterpolateAtVertex:
2338#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002339 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002340 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002341
2342 // Does it need a swizzle inversion? If so, evaluation is inverted;
2343 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002344 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002345 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2346 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2347 }
Rex Xu7a26c172015-12-08 17:12:09 +08002348 break;
Rex Xud4782c12015-09-06 16:30:11 +08002349 case glslang::EOpAtomicAdd:
2350 case glslang::EOpAtomicMin:
2351 case glslang::EOpAtomicMax:
2352 case glslang::EOpAtomicAnd:
2353 case glslang::EOpAtomicOr:
2354 case glslang::EOpAtomicXor:
2355 case glslang::EOpAtomicExchange:
2356 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002357 case glslang::EOpAtomicLoad:
2358 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002359 case glslang::EOpAtomicCounterAdd:
2360 case glslang::EOpAtomicCounterSubtract:
2361 case glslang::EOpAtomicCounterMin:
2362 case glslang::EOpAtomicCounterMax:
2363 case glslang::EOpAtomicCounterAnd:
2364 case glslang::EOpAtomicCounterOr:
2365 case glslang::EOpAtomicCounterXor:
2366 case glslang::EOpAtomicCounterExchange:
2367 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002368 if (arg == 0)
2369 lvalue = true;
2370 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002371 case glslang::EOpAddCarry:
2372 case glslang::EOpSubBorrow:
2373 if (arg == 2)
2374 lvalue = true;
2375 break;
2376 case glslang::EOpUMulExtended:
2377 case glslang::EOpIMulExtended:
2378 if (arg >= 2)
2379 lvalue = true;
2380 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002381 default:
2382 break;
2383 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002384 builder.clearAccessChain();
2385 if (invertedType != spv::NoType && arg == 0)
2386 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2387 else
2388 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002389 if (lvalue)
2390 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002391 else {
2392 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002393 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002394 }
John Kessenich140f3df2015-06-26 16:58:36 -06002395 }
John Kessenich426394d2015-07-23 10:22:48 -06002396
John Kesseniche485c7a2017-05-31 18:50:53 -06002397 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002398 if (atomic) {
2399 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002400 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002401 } else {
2402 // Pass through to generic operations.
2403 switch (glslangOperands.size()) {
2404 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002405 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002406 break;
2407 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002408 {
2409 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002410 TranslateNoContractionDecoration(node->getType().getQualifier()),
2411 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002412 result = createUnaryOperation(
2413 node->getOp(), decorations,
2414 resultType(), operands.front(),
2415 glslangOperands[0]->getAsTyped()->getBasicType());
2416 }
John Kessenich426394d2015-07-23 10:22:48 -06002417 break;
2418 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002419 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002420 break;
2421 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002422 if (invertedType)
2423 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002424 }
2425
2426 if (noReturnValue)
2427 return false;
2428
2429 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002430 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002431 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002432 } else {
2433 builder.clearAccessChain();
2434 builder.setAccessChainRValue(result);
2435 return false;
2436 }
2437}
2438
John Kessenich433e9ff2017-01-26 20:31:11 -07002439// This path handles both if-then-else and ?:
2440// The if-then-else has a node type of void, while
2441// ?: has either a void or a non-void node type
2442//
2443// Leaving the result, when not void:
2444// GLSL only has r-values as the result of a :?, but
2445// if we have an l-value, that can be more efficient if it will
2446// become the base of a complex r-value expression, because the
2447// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002448bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2449{
John Kessenich4bee5312018-02-20 21:29:05 -07002450 // See if it simple and safe, or required, to execute both sides.
2451 // Crucially, side effects must be either semantically required or avoided,
2452 // and there are performance trade-offs.
2453 // Return true if required or a good idea (and safe) to execute both sides,
2454 // false otherwise.
2455 const auto bothSidesPolicy = [&]() -> bool {
2456 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002457 if (node->getTrueBlock() == nullptr ||
2458 node->getFalseBlock() == nullptr)
2459 return false;
2460
John Kessenich4bee5312018-02-20 21:29:05 -07002461 // required? (unless we write additional code to look for side effects
2462 // and make performance trade-offs if none are present)
2463 if (!node->getShortCircuit())
2464 return true;
2465
2466 // if not required to execute both, decide based on performance/practicality...
2467
2468 // see if OpSelect can handle it
2469 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2470 node->getBasicType() == glslang::EbtVoid)
2471 return false;
2472
John Kessenich433e9ff2017-01-26 20:31:11 -07002473 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2474 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2475
2476 // return true if a single operand to ? : is okay for OpSelect
2477 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002478 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002479 };
2480
2481 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2482 operandOkay(node->getFalseBlock()->getAsTyped());
2483 };
2484
John Kessenich4bee5312018-02-20 21:29:05 -07002485 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2486 // emit the condition before doing anything with selection
2487 node->getCondition()->traverse(this);
2488 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2489
2490 // Find a way of executing both sides and selecting the right result.
2491 const auto executeBothSides = [&]() -> void {
2492 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002493 node->getTrueBlock()->traverse(this);
2494 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2495 node->getFalseBlock()->traverse(this);
2496 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2497
John Kesseniche485c7a2017-05-31 18:50:53 -06002498 builder.setLine(node->getLoc().line);
2499
John Kessenich4bee5312018-02-20 21:29:05 -07002500 // done if void
2501 if (node->getBasicType() == glslang::EbtVoid)
2502 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002503
John Kessenich4bee5312018-02-20 21:29:05 -07002504 // emit code to select between trueValue and falseValue
2505
2506 // see if OpSelect can handle it
2507 if (node->getType().isScalar() || node->getType().isVector()) {
2508 // Emit OpSelect for this selection.
2509
2510 // smear condition to vector, if necessary (AST is always scalar)
2511 if (builder.isVector(trueValue))
2512 condition = builder.smearScalar(spv::NoPrecision, condition,
2513 builder.makeVectorType(builder.makeBoolType(),
2514 builder.getNumComponents(trueValue)));
2515
2516 // OpSelect
2517 result = builder.createTriOp(spv::OpSelect,
2518 convertGlslangToSpvType(node->getType()), condition,
2519 trueValue, falseValue);
2520
2521 builder.clearAccessChain();
2522 builder.setAccessChainRValue(result);
2523 } else {
2524 // We need control flow to select the result.
2525 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2526 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2527
2528 // Selection control:
2529 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2530
2531 // make an "if" based on the value created by the condition
2532 spv::Builder::If ifBuilder(condition, control, builder);
2533
2534 // emit the "then" statement
2535 builder.createStore(trueValue, result);
2536 ifBuilder.makeBeginElse();
2537 // emit the "else" statement
2538 builder.createStore(falseValue, result);
2539
2540 // finish off the control flow
2541 ifBuilder.makeEndIf();
2542
2543 builder.clearAccessChain();
2544 builder.setAccessChainLValue(result);
2545 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002546 };
2547
John Kessenich4bee5312018-02-20 21:29:05 -07002548 // Execute the one side needed, as per the condition
2549 const auto executeOneSide = [&]() {
2550 // Always emit control flow.
2551 if (node->getBasicType() != glslang::EbtVoid)
2552 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002553
John Kessenich4bee5312018-02-20 21:29:05 -07002554 // Selection control:
2555 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2556
2557 // make an "if" based on the value created by the condition
2558 spv::Builder::If ifBuilder(condition, control, builder);
2559
2560 // emit the "then" statement
2561 if (node->getTrueBlock() != nullptr) {
2562 node->getTrueBlock()->traverse(this);
2563 if (result != spv::NoResult)
2564 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2565 }
2566
2567 if (node->getFalseBlock() != nullptr) {
2568 ifBuilder.makeBeginElse();
2569 // emit the "else" statement
2570 node->getFalseBlock()->traverse(this);
2571 if (result != spv::NoResult)
2572 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2573 }
2574
2575 // finish off the control flow
2576 ifBuilder.makeEndIf();
2577
2578 if (result != spv::NoResult) {
2579 builder.clearAccessChain();
2580 builder.setAccessChainLValue(result);
2581 }
2582 };
2583
2584 // Try for OpSelect (or a requirement to execute both sides)
2585 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002586 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2587 if (node->getType().getQualifier().isSpecConstant())
2588 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002589 executeBothSides();
2590 } else
2591 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002592
2593 return false;
2594}
2595
2596bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2597{
2598 // emit and get the condition before doing anything with switch
2599 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002600 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002601
Rex Xu57e65922017-07-04 23:23:40 +08002602 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002603 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002604
John Kessenich140f3df2015-06-26 16:58:36 -06002605 // browse the children to sort out code segments
2606 int defaultSegment = -1;
2607 std::vector<TIntermNode*> codeSegments;
2608 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2609 std::vector<int> caseValues;
2610 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2611 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2612 TIntermNode* child = *c;
2613 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002614 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002615 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002616 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002617 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2618 } else
2619 codeSegments.push_back(child);
2620 }
2621
qining25262b32016-05-06 17:25:16 -04002622 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002623 // statements between the last case and the end of the switch statement
2624 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2625 (int)codeSegments.size() == defaultSegment)
2626 codeSegments.push_back(nullptr);
2627
2628 // make the switch statement
2629 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002630 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002631
2632 // emit all the code in the segments
2633 breakForLoop.push(false);
2634 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2635 builder.nextSwitchSegment(segmentBlocks, s);
2636 if (codeSegments[s])
2637 codeSegments[s]->traverse(this);
2638 else
2639 builder.addSwitchBreak();
2640 }
2641 breakForLoop.pop();
2642
2643 builder.endSwitch(segmentBlocks);
2644
2645 return false;
2646}
2647
2648void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2649{
2650 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002651 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002652
2653 builder.clearAccessChain();
2654 builder.setAccessChainRValue(constant);
2655}
2656
2657bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2658{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002659 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002660 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002661
2662 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002663 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2664 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002665
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002666 // Spec requires back edges to target header blocks, and every header block
2667 // must dominate its merge block. Make a header block first to ensure these
2668 // conditions are met. By definition, it will contain OpLoopMerge, followed
2669 // by a block-ending branch. But we don't want to put any other body/test
2670 // instructions in it, since the body/test may have arbitrary instructions,
2671 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002672 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002673 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002674 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002675 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002676 spv::Block& test = builder.makeNewBlock();
2677 builder.createBranch(&test);
2678
2679 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002680 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002681 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002682 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2683
2684 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002685 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002686 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002687 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002688 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002689 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002690
2691 builder.setBuildPoint(&blocks.continue_target);
2692 if (node->getTerminal())
2693 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002694 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002695 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002696 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002697 builder.createBranch(&blocks.body);
2698
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002699 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002700 builder.setBuildPoint(&blocks.body);
2701 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002702 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002703 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002704 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002705
2706 builder.setBuildPoint(&blocks.continue_target);
2707 if (node->getTerminal())
2708 node->getTerminal()->traverse(this);
2709 if (node->getTest()) {
2710 node->getTest()->traverse(this);
2711 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002712 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002713 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002714 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002715 // TODO: unless there was a break/return/discard instruction
2716 // somewhere in the body, this is an infinite loop, so we should
2717 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002718 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002719 }
John Kessenich140f3df2015-06-26 16:58:36 -06002720 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002721 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002722 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002723 return false;
2724}
2725
2726bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2727{
2728 if (node->getExpression())
2729 node->getExpression()->traverse(this);
2730
John Kesseniche485c7a2017-05-31 18:50:53 -06002731 builder.setLine(node->getLoc().line);
2732
John Kessenich140f3df2015-06-26 16:58:36 -06002733 switch (node->getFlowOp()) {
2734 case glslang::EOpKill:
2735 builder.makeDiscard();
2736 break;
2737 case glslang::EOpBreak:
2738 if (breakForLoop.top())
2739 builder.createLoopExit();
2740 else
2741 builder.addSwitchBreak();
2742 break;
2743 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002744 builder.createLoopContinue();
2745 break;
2746 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002747 if (node->getExpression()) {
2748 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2749 spv::Id returnId = accessChainLoad(glslangReturnType);
2750 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2751 builder.clearAccessChain();
2752 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2753 builder.setAccessChainLValue(copyId);
2754 multiTypeStore(glslangReturnType, returnId);
2755 returnId = builder.createLoad(copyId);
2756 }
2757 builder.makeReturn(false, returnId);
2758 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002759 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002760
2761 builder.clearAccessChain();
2762 break;
2763
2764 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002765 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002766 break;
2767 }
2768
2769 return false;
2770}
2771
2772spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2773{
qining25262b32016-05-06 17:25:16 -04002774 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002775 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002776 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002777 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05002778 spv::Id result = createSpvConstant(*node);
2779 if (result != spv::NoResult)
2780 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06002781 }
2782
2783 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002784 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002785 spv::Id spvType = convertGlslangToSpvType(node->getType());
2786
Rex Xucabbb782017-03-24 13:41:14 +08002787 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2788 node->getType().containsBasicType(glslang::EbtInt16) ||
2789 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002790 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002791 switch (storageClass) {
2792 case spv::StorageClassInput:
2793 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002794 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002795 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002796 break;
2797 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002798 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002799 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002800 break;
2801 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002802 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002803 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2804 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002805 else
2806 builder.addCapability(spv::CapabilityStorageUniform16);
2807 break;
2808 case spv::StorageClassStorageBuffer:
2809 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2810 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2811 break;
2812 default:
2813 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002814 }
2815 }
Rex Xuf89ad982017-04-07 23:22:33 +08002816
John Kessenich312dcfb2018-07-03 13:19:51 -06002817 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2818 node->getType().containsBasicType(glslang::EbtUint8);
2819 if (contains8BitType) {
2820 if (storageClass == spv::StorageClassPushConstant) {
2821 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2822 builder.addCapability(spv::CapabilityStoragePushConstant8);
2823 } else if (storageClass == spv::StorageClassUniform) {
2824 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2825 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01002826 } else if (storageClass == spv::StorageClassStorageBuffer) {
2827 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2828 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
John Kessenich312dcfb2018-07-03 13:19:51 -06002829 }
2830 }
2831
John Kessenich140f3df2015-06-26 16:58:36 -06002832 const char* name = node->getName().c_str();
2833 if (glslang::IsAnonymous(name))
2834 name = "";
2835
2836 return builder.createVariable(storageClass, spvType, name);
2837}
2838
2839// Return type Id of the sampled type.
2840spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2841{
2842 switch (sampler.type) {
2843 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002844#ifdef AMD_EXTENSIONS
2845 case glslang::EbtFloat16:
2846 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2847 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2848 return builder.makeFloatType(16);
2849#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002850 case glslang::EbtInt: return builder.makeIntType(32);
2851 case glslang::EbtUint: return builder.makeUintType(32);
2852 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002853 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002854 return builder.makeFloatType(32);
2855 }
2856}
2857
John Kessenich8c8505c2016-07-26 12:50:38 -06002858// If node is a swizzle operation, return the type that should be used if
2859// the swizzle base is first consumed by another operation, before the swizzle
2860// is applied.
2861spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2862{
John Kessenichecba76f2017-01-06 00:34:48 -07002863 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002864 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2865 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2866 else
2867 return spv::NoType;
2868}
2869
2870// When inverting a swizzle with a parent op, this function
2871// will apply the swizzle operation to a completed parent operation.
2872spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2873{
2874 std::vector<unsigned> swizzle;
2875 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2876 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2877}
2878
John Kessenich8c8505c2016-07-26 12:50:38 -06002879// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2880void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2881{
2882 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2883 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2884 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2885}
2886
John Kessenich3ac051e2015-12-20 11:29:16 -07002887// Convert from a glslang type to an SPV type, by calling into a
2888// recursive version of this function. This establishes the inherited
2889// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002890spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2891{
John Kessenichead86222018-03-28 18:01:20 -06002892 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002893}
2894
2895// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002896// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002897// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002898spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2899 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002900{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002901 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002902
2903 switch (type.getBasicType()) {
2904 case glslang::EbtVoid:
2905 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002906 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002907 break;
2908 case glslang::EbtFloat:
2909 spvType = builder.makeFloatType(32);
2910 break;
2911 case glslang::EbtDouble:
2912 spvType = builder.makeFloatType(64);
2913 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002914 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002915 spvType = builder.makeFloatType(16);
2916 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002917 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002918 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2919 // a 32-bit int where non-0 means true.
2920 if (explicitLayout != glslang::ElpNone)
2921 spvType = builder.makeUintType(32);
2922 else
2923 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002924 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002925 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07002926 spvType = builder.makeIntType(8);
2927 break;
2928 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07002929 spvType = builder.makeUintType(8);
2930 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002931 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07002932 spvType = builder.makeIntType(16);
2933 break;
2934 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07002935 spvType = builder.makeUintType(16);
2936 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002937 case glslang::EbtInt:
2938 spvType = builder.makeIntType(32);
2939 break;
2940 case glslang::EbtUint:
2941 spvType = builder.makeUintType(32);
2942 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002943 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002944 spvType = builder.makeIntType(64);
2945 break;
2946 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002947 spvType = builder.makeUintType(64);
2948 break;
John Kessenich426394d2015-07-23 10:22:48 -06002949 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002950 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002951 spvType = builder.makeUintType(32);
2952 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07002953#ifdef NV_EXTENSIONS
2954 case glslang::EbtAccStructNV:
2955 spvType = builder.makeAccelerationStructureNVType();
2956 break;
2957#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002958 case glslang::EbtSampler:
2959 {
2960 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002961 if (sampler.sampler) {
2962 // pure sampler
2963 spvType = builder.makeSamplerType();
2964 } else {
2965 // an image is present, make its type
2966 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2967 sampler.image ? 2 : 1, TranslateImageFormat(type));
2968 if (sampler.combined) {
2969 // already has both image and sampler, make the combined type
2970 spvType = builder.makeSampledImageType(spvType);
2971 }
John Kessenich55e7d112015-11-15 21:33:39 -07002972 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002973 }
John Kessenich140f3df2015-06-26 16:58:36 -06002974 break;
2975 case glslang::EbtStruct:
2976 case glslang::EbtBlock:
2977 {
2978 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002979 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002980
2981 // Try to share structs for different layouts, but not yet for other
2982 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002983 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002984 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002985 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002986 break;
2987
2988 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002989 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002990 memberRemapper[glslangMembers].resize(glslangMembers->size());
2991 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002992 }
2993 break;
2994 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002995 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002996 break;
2997 }
2998
2999 if (type.isMatrix())
3000 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3001 else {
3002 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3003 if (type.getVectorSize() > 1)
3004 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3005 }
3006
3007 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003008 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3009
John Kessenichc9a80832015-09-12 12:17:44 -06003010 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003011 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003012 // We need to decorate array strides for types needing explicit layout, except blocks.
3013 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003014 // Use a dummy glslang type for querying internal strides of
3015 // arrays of arrays, but using just a one-dimensional array.
3016 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003017 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3018 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003019
3020 // Will compute the higher-order strides here, rather than making a whole
3021 // pile of types and doing repetitive recursion on their contents.
3022 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3023 }
John Kessenichf8842e52016-01-04 19:22:56 -07003024
3025 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003026 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003027 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003028 if (stride > 0)
3029 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003030 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003031 }
3032 } else {
3033 // single-dimensional array, and don't yet have stride
3034
John Kessenichf8842e52016-01-04 19:22:56 -07003035 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003036 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3037 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003038 }
John Kessenich31ed4832015-09-09 17:51:38 -06003039
John Kessenichead86222018-03-28 18:01:20 -06003040 // Do the outer dimension, which might not be known for a runtime-sized array.
3041 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3042 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003043 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003044 else {
3045 if (!lastBufferBlockMember) {
3046 builder.addExtension("SPV_EXT_descriptor_indexing");
3047 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3048 }
John Kessenichead86222018-03-28 18:01:20 -06003049 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003050 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003051 if (stride > 0)
3052 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003053 }
3054
3055 return spvType;
3056}
3057
John Kessenich0e737842017-03-24 18:38:16 -06003058// TODO: this functionality should exist at a higher level, in creating the AST
3059//
3060// Identify interface members that don't have their required extension turned on.
3061//
3062bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3063{
Chao Chen3c366992018-09-19 11:41:59 -07003064#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003065 auto& extensions = glslangIntermediate->getRequestedExtensions();
3066
Rex Xubcf291a2017-03-29 23:01:36 +08003067 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3068 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3069 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003070 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3071 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3072 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003073
3074 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3075 if (member.getFieldName() == "gl_ViewportMask" &&
3076 extensions.find("GL_NV_viewport_array2") == extensions.end())
3077 return true;
3078 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3079 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3080 return true;
3081 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3082 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3083 return true;
3084 }
3085#endif
John Kessenich0e737842017-03-24 18:38:16 -06003086
3087 return false;
3088};
3089
John Kessenich6090df02016-06-30 21:18:02 -06003090// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3091// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3092// Mutually recursive with convertGlslangToSpvType().
3093spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3094 const glslang::TTypeList* glslangMembers,
3095 glslang::TLayoutPacking explicitLayout,
3096 const glslang::TQualifier& qualifier)
3097{
3098 // Create a vector of struct types for SPIR-V to consume
3099 std::vector<spv::Id> spvMembers;
3100 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
John Kessenich6090df02016-06-30 21:18:02 -06003101 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3102 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3103 if (glslangMember.hiddenMember()) {
3104 ++memberDelta;
3105 if (type.getBasicType() == glslang::EbtBlock)
3106 memberRemapper[glslangMembers][i] = -1;
3107 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003108 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003109 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003110 if (filterMember(glslangMember))
3111 continue;
3112 }
John Kessenich6090df02016-06-30 21:18:02 -06003113 // modify just this child's view of the qualifier
3114 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3115 InheritQualifiers(memberQualifier, qualifier);
3116
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003117 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003118 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003119 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003120
3121 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003122 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3123 i == (int)glslangMembers->size() - 1;
3124 spvMembers.push_back(
3125 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06003126 }
3127 }
3128
3129 // Make the SPIR-V type
3130 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003131 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003132 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3133
3134 // Decorate it
3135 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3136
3137 return spvType;
3138}
3139
3140void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3141 const glslang::TTypeList* glslangMembers,
3142 glslang::TLayoutPacking explicitLayout,
3143 const glslang::TQualifier& qualifier,
3144 spv::Id spvType)
3145{
3146 // Name and decorate the non-hidden members
3147 int offset = -1;
3148 int locationOffset = 0; // for use within the members of this struct
3149 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3150 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3151 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003152 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003153 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003154 if (filterMember(glslangMember))
3155 continue;
3156 }
John Kessenich6090df02016-06-30 21:18:02 -06003157
3158 // modify just this child's view of the qualifier
3159 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3160 InheritQualifiers(memberQualifier, qualifier);
3161
3162 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003163 if (member < 0)
3164 continue;
3165
3166 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3167 builder.addMemberDecoration(spvType, member,
3168 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3169 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3170 // Add interpolation and auxiliary storage decorations only to
3171 // top-level members of Input and Output storage classes
3172 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3173 type.getQualifier().storage == glslang::EvqVaryingOut) {
3174 if (type.getBasicType() == glslang::EbtBlock ||
3175 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3176 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3177 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003178#ifdef NV_EXTENSIONS
3179 addMeshNVDecoration(spvType, member, memberQualifier);
3180#endif
John Kessenich6090df02016-06-30 21:18:02 -06003181 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003182 }
3183 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003184
John Kessenich5d610ee2018-03-07 18:05:55 -07003185 if (type.getBasicType() == glslang::EbtBlock &&
3186 qualifier.storage == glslang::EvqBuffer) {
3187 // Add memory decorations only to top-level members of shader storage block
3188 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003189 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003190 for (unsigned int i = 0; i < memory.size(); ++i)
3191 builder.addMemberDecoration(spvType, member, memory[i]);
3192 }
John Kessenich6090df02016-06-30 21:18:02 -06003193
John Kessenich5d610ee2018-03-07 18:05:55 -07003194 // Location assignment was already completed correctly by the front end,
3195 // just track whether a member needs to be decorated.
3196 // Ignore member locations if the container is an array, as that's
3197 // ill-specified and decisions have been made to not allow this.
3198 if (! type.isArray() && memberQualifier.hasLocation())
3199 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003200
John Kessenich5d610ee2018-03-07 18:05:55 -07003201 if (qualifier.hasLocation()) // track for upcoming inheritance
3202 locationOffset += glslangIntermediate->computeTypeLocationSize(
3203 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003204
John Kessenich5d610ee2018-03-07 18:05:55 -07003205 // component, XFB, others
3206 if (glslangMember.getQualifier().hasComponent())
3207 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3208 glslangMember.getQualifier().layoutComponent);
3209 if (glslangMember.getQualifier().hasXfbOffset())
3210 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3211 glslangMember.getQualifier().layoutXfbOffset);
3212 else if (explicitLayout != glslang::ElpNone) {
3213 // figure out what to do with offset, which is accumulating
3214 int nextOffset;
3215 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3216 if (offset >= 0)
3217 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3218 offset = nextOffset;
3219 }
John Kessenich6090df02016-06-30 21:18:02 -06003220
John Kessenich5d610ee2018-03-07 18:05:55 -07003221 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3222 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3223 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003224
John Kessenich5d610ee2018-03-07 18:05:55 -07003225 // built-in variable decorations
3226 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3227 if (builtIn != spv::BuiltInMax)
3228 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003229
John Kessenich5611c6d2018-04-05 11:25:02 -06003230 // nonuniform
3231 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3232
John Kessenichead86222018-03-28 18:01:20 -06003233 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3234 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3235 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3236 memberQualifier.semanticName);
3237 }
3238
chaoc771d89f2017-01-13 01:10:53 -08003239#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003240 if (builtIn == spv::BuiltInLayer) {
3241 // SPV_NV_viewport_array2 extension
3242 if (glslangMember.getQualifier().layoutViewportRelative){
3243 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3244 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3245 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003246 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003247 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3248 builder.addMemberDecoration(spvType, member,
3249 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3250 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3251 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3252 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003253 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003254 }
3255 if (glslangMember.getQualifier().layoutPassthrough) {
3256 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3257 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3258 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3259 }
chaoc771d89f2017-01-13 01:10:53 -08003260#endif
John Kessenich6090df02016-06-30 21:18:02 -06003261 }
3262
3263 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003264 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3265 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003266 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
3267 builder.addCapability(spv::CapabilityGeometryStreams);
3268 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
3269 }
John Kessenich6090df02016-06-30 21:18:02 -06003270}
3271
John Kessenich6c292d32016-02-15 20:58:50 -07003272// Turn the expression forming the array size into an id.
3273// This is not quite trivial, because of specialization constants.
3274// Sometimes, a raw constant is turned into an Id, and sometimes
3275// a specialization constant expression is.
3276spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3277{
3278 // First, see if this is sized with a node, meaning a specialization constant:
3279 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3280 if (specNode != nullptr) {
3281 builder.clearAccessChain();
3282 specNode->traverse(this);
3283 return accessChainLoad(specNode->getAsTyped()->getType());
3284 }
qining25262b32016-05-06 17:25:16 -04003285
John Kessenich6c292d32016-02-15 20:58:50 -07003286 // Otherwise, need a compile-time (front end) size, get it:
3287 int size = arraySizes.getDimSize(dim);
3288 assert(size > 0);
3289 return builder.makeUintConstant(size);
3290}
3291
John Kessenich103bef92016-02-08 21:38:15 -07003292// Wrap the builder's accessChainLoad to:
3293// - localize handling of RelaxedPrecision
3294// - use the SPIR-V inferred type instead of another conversion of the glslang type
3295// (avoids unnecessary work and possible type punning for structures)
3296// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003297spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3298{
John Kessenich103bef92016-02-08 21:38:15 -07003299 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003300
3301 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3302 coherentFlags |= TranslateCoherent(type);
3303
John Kessenich5611c6d2018-04-05 11:25:02 -06003304 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003305 TranslateNonUniformDecoration(type.getQualifier()),
3306 nominalTypeId,
3307 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
3308 TranslateMemoryScope(coherentFlags));
John Kessenich103bef92016-02-08 21:38:15 -07003309
3310 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003311 if (type.getBasicType() == glslang::EbtBool) {
3312 if (builder.isScalarType(nominalTypeId)) {
3313 // Conversion for bool
3314 spv::Id boolType = builder.makeBoolType();
3315 if (nominalTypeId != boolType)
3316 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3317 } else if (builder.isVectorType(nominalTypeId)) {
3318 // Conversion for bvec
3319 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3320 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3321 if (nominalTypeId != bvecType)
3322 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3323 }
3324 }
John Kessenich103bef92016-02-08 21:38:15 -07003325
3326 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003327}
3328
Rex Xu27253232016-02-23 17:51:09 +08003329// Wrap the builder's accessChainStore to:
3330// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003331//
3332// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003333void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3334{
3335 // Need to convert to abstract types when necessary
3336 if (type.getBasicType() == glslang::EbtBool) {
3337 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3338
3339 if (builder.isScalarType(nominalTypeId)) {
3340 // Conversion for bool
3341 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003342 if (nominalTypeId != boolType) {
3343 // keep these outside arguments, for determinant order-of-evaluation
3344 spv::Id one = builder.makeUintConstant(1);
3345 spv::Id zero = builder.makeUintConstant(0);
3346 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3347 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003348 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003349 } else if (builder.isVectorType(nominalTypeId)) {
3350 // Conversion for bvec
3351 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3352 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003353 if (nominalTypeId != bvecType) {
3354 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003355 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3356 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3357 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003358 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003359 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3360 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003361 }
3362 }
3363
Jeff Bolz36831c92018-09-05 10:11:41 -05003364 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3365 coherentFlags |= TranslateCoherent(type);
3366
3367 builder.accessChainStore(rvalue,
3368 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
3369 TranslateMemoryScope(coherentFlags));
Rex Xu27253232016-02-23 17:51:09 +08003370}
3371
John Kessenich4bf71552016-09-02 11:20:21 -06003372// For storing when types match at the glslang level, but not might match at the
3373// SPIR-V level.
3374//
3375// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003376// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003377// as in a member-decorated way.
3378//
3379// NOTE: This function can handle any store request; if it's not special it
3380// simplifies to a simple OpStore.
3381//
3382// Implicitly uses the existing builder.accessChain as the storage target.
3383void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3384{
John Kessenichb3e24e42016-09-11 12:33:43 -06003385 // we only do the complex path here if it's an aggregate
3386 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003387 accessChainStore(type, rValue);
3388 return;
3389 }
3390
John Kessenichb3e24e42016-09-11 12:33:43 -06003391 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003392 spv::Id rType = builder.getTypeId(rValue);
3393 spv::Id lValue = builder.accessChainGetLValue();
3394 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3395 if (lType == rType) {
3396 accessChainStore(type, rValue);
3397 return;
3398 }
3399
John Kessenichb3e24e42016-09-11 12:33:43 -06003400 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003401 // where the two types were the same type in GLSL. This requires member
3402 // by member copy, recursively.
3403
John Kessenichb3e24e42016-09-11 12:33:43 -06003404 // If an array, copy element by element.
3405 if (type.isArray()) {
3406 glslang::TType glslangElementType(type, 0);
3407 spv::Id elementRType = builder.getContainedTypeId(rType);
3408 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3409 // get the source member
3410 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003411
John Kessenichb3e24e42016-09-11 12:33:43 -06003412 // set up the target storage
3413 builder.clearAccessChain();
3414 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003415 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type));
John Kessenich4bf71552016-09-02 11:20:21 -06003416
John Kessenichb3e24e42016-09-11 12:33:43 -06003417 // store the member
3418 multiTypeStore(glslangElementType, elementRValue);
3419 }
3420 } else {
3421 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003422
John Kessenichb3e24e42016-09-11 12:33:43 -06003423 // loop over structure members
3424 const glslang::TTypeList& members = *type.getStruct();
3425 for (int m = 0; m < (int)members.size(); ++m) {
3426 const glslang::TType& glslangMemberType = *members[m].type;
3427
3428 // get the source member
3429 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3430 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3431
3432 // set up the target storage
3433 builder.clearAccessChain();
3434 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003435 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type));
John Kessenichb3e24e42016-09-11 12:33:43 -06003436
3437 // store the member
3438 multiTypeStore(glslangMemberType, memberRValue);
3439 }
John Kessenich4bf71552016-09-02 11:20:21 -06003440 }
3441}
3442
John Kessenichf85e8062015-12-19 13:57:10 -07003443// Decide whether or not this type should be
3444// decorated with offsets and strides, and if so
3445// whether std140 or std430 rules should be applied.
3446glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003447{
John Kessenichf85e8062015-12-19 13:57:10 -07003448 // has to be a block
3449 if (type.getBasicType() != glslang::EbtBlock)
3450 return glslang::ElpNone;
3451
Chao Chen3c366992018-09-19 11:41:59 -07003452 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003453 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003454 type.getQualifier().storage != glslang::EvqBuffer &&
3455 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003456 return glslang::ElpNone;
3457
3458 // return the layout to use
3459 switch (type.getQualifier().layoutPacking) {
3460 case glslang::ElpStd140:
3461 case glslang::ElpStd430:
3462 return type.getQualifier().layoutPacking;
3463 default:
3464 return glslang::ElpNone;
3465 }
John Kessenich31ed4832015-09-09 17:51:38 -06003466}
3467
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003468// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003469int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003470{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003471 int size;
John Kessenich49987892015-12-29 17:11:44 -07003472 int stride;
3473 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003474
3475 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003476}
3477
John Kessenich49987892015-12-29 17:11:44 -07003478// 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 -07003479// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003480int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003481{
John Kessenich49987892015-12-29 17:11:44 -07003482 glslang::TType elementType;
3483 elementType.shallowCopy(matrixType);
3484 elementType.clearArraySizes();
3485
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003486 int size;
John Kessenich49987892015-12-29 17:11:44 -07003487 int stride;
3488 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3489
3490 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003491}
3492
John Kessenich5e4b1242015-08-06 22:53:06 -06003493// Given a member type of a struct, realign the current offset for it, and compute
3494// the next (not yet aligned) offset for the next member, which will get aligned
3495// on the next call.
3496// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3497// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3498// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003499void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003500 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003501{
3502 // this will get a positive value when deemed necessary
3503 nextOffset = -1;
3504
John Kessenich5e4b1242015-08-06 22:53:06 -06003505 // override anything in currentOffset with user-set offset
3506 if (memberType.getQualifier().hasOffset())
3507 currentOffset = memberType.getQualifier().layoutOffset;
3508
3509 // It could be that current linker usage in glslang updated all the layoutOffset,
3510 // in which case the following code does not matter. But, that's not quite right
3511 // once cross-compilation unit GLSL validation is done, as the original user
3512 // settings are needed in layoutOffset, and then the following will come into play.
3513
John Kessenichf85e8062015-12-19 13:57:10 -07003514 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003515 if (! memberType.getQualifier().hasOffset())
3516 currentOffset = -1;
3517
3518 return;
3519 }
3520
John Kessenichf85e8062015-12-19 13:57:10 -07003521 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003522 if (currentOffset < 0)
3523 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003524
John Kessenich5e4b1242015-08-06 22:53:06 -06003525 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3526 // but possibly not yet correctly aligned.
3527
3528 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003529 int dummyStride;
3530 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003531
3532 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003533 // TODO: make this consistent in early phases of code:
3534 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3535 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3536 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003537 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003538 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003539 int dummySize;
3540 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3541 if (componentAlignment <= 4)
3542 memberAlignment = componentAlignment;
3543 }
3544
3545 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003546 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003547
3548 // Bump up to vec4 if there is a bad straddle
3549 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3550 glslang::RoundToPow2(currentOffset, 16);
3551
John Kessenich5e4b1242015-08-06 22:53:06 -06003552 nextOffset = currentOffset + memberSize;
3553}
3554
David Netoa901ffe2016-06-08 14:11:40 +01003555void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003556{
David Netoa901ffe2016-06-08 14:11:40 +01003557 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3558 switch (glslangBuiltIn)
3559 {
3560 case glslang::EbvClipDistance:
3561 case glslang::EbvCullDistance:
3562 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003563#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003564 case glslang::EbvViewportMaskNV:
3565 case glslang::EbvSecondaryPositionNV:
3566 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003567 case glslang::EbvPositionPerViewNV:
3568 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003569 case glslang::EbvTaskCountNV:
3570 case glslang::EbvPrimitiveCountNV:
3571 case glslang::EbvPrimitiveIndicesNV:
3572 case glslang::EbvClipDistancePerViewNV:
3573 case glslang::EbvCullDistancePerViewNV:
3574 case glslang::EbvLayerPerViewNV:
3575 case glslang::EbvMeshViewCountNV:
3576 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003577#endif
David Netoa901ffe2016-06-08 14:11:40 +01003578 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3579 // Alternately, we could just call this for any glslang built-in, since the
3580 // capability already guards against duplicates.
3581 TranslateBuiltInDecoration(glslangBuiltIn, false);
3582 break;
3583 default:
3584 // Capabilities were already generated when the struct was declared.
3585 break;
3586 }
John Kessenichebb50532016-05-16 19:22:05 -06003587}
3588
John Kessenich6fccb3c2016-09-19 16:01:41 -06003589bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003590{
John Kessenicheee9d532016-09-19 18:09:30 -06003591 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003592}
3593
John Kessenichd41993d2017-09-10 15:21:05 -06003594// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003595// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3596// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003597bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003598{
John Kessenich6a14f782017-12-04 02:48:10 -07003599 assert(qualifier == glslang::EvqIn ||
3600 qualifier == glslang::EvqOut ||
3601 qualifier == glslang::EvqInOut ||
3602 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003603 return qualifier != glslang::EvqConstReadOnly;
3604}
3605
3606// Is parameter pass-by-original?
3607bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3608 bool implicitThisParam)
3609{
3610 if (implicitThisParam) // implicit this
3611 return true;
3612 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003613 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003614 return paramType.containsOpaque() || // sampler, etc.
3615 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3616}
3617
John Kessenich140f3df2015-06-26 16:58:36 -06003618// Make all the functions, skeletally, without actually visiting their bodies.
3619void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3620{
Jeff Bolz36831c92018-09-05 10:11:41 -05003621 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003622 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3623 if (paramPrecision != spv::NoPrecision)
3624 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003625 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenichfad62972017-07-18 02:35:46 -06003626 };
3627
John Kessenich140f3df2015-06-26 16:58:36 -06003628 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3629 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003630 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003631 continue;
3632
3633 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003634 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003635 //
qining25262b32016-05-06 17:25:16 -04003636 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003637 // function. What it is an address of varies:
3638 //
John Kessenich4bf71552016-09-02 11:20:21 -06003639 // - "in" parameters not marked as "const" can be written to without modifying the calling
3640 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003641 //
3642 // - "const in" parameters can just be the r-value, as no writes need occur.
3643 //
John Kessenich4bf71552016-09-02 11:20:21 -06003644 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3645 // 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 -06003646
3647 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003648 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003649 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3650
John Kessenichfad62972017-07-18 02:35:46 -06003651 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3652 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003653
John Kessenichfad62972017-07-18 02:35:46 -06003654 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003655 for (int p = 0; p < (int)parameters.size(); ++p) {
3656 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3657 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003658 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003659 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003660 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003661 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3662 else
John Kessenich4bf71552016-09-02 11:20:21 -06003663 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003664 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003665 paramTypes.push_back(typeId);
3666 }
3667
3668 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003669 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3670 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003671 glslFunction->getName().c_str(), paramTypes,
3672 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003673 if (implicitThis)
3674 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003675
3676 // Track function to emit/call later
3677 functionMap[glslFunction->getName().c_str()] = function;
3678
3679 // Set the parameter id's
3680 for (int p = 0; p < (int)parameters.size(); ++p) {
3681 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3682 // give a name too
3683 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3684 }
3685 }
3686}
3687
3688// Process all the initializers, while skipping the functions and link objects
3689void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3690{
3691 builder.setBuildPoint(shaderEntry->getLastBlock());
3692 for (int i = 0; i < (int)initializers.size(); ++i) {
3693 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3694 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3695
3696 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003697 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003698 initializer->traverse(this);
3699 }
3700 }
3701}
3702
3703// Process all the functions, while skipping initializers.
3704void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3705{
3706 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3707 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003708 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003709 node->traverse(this);
3710 }
3711}
3712
3713void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3714{
qining25262b32016-05-06 17:25:16 -04003715 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003716 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003717 currentFunction = functionMap[node->getName().c_str()];
3718 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003719 builder.setBuildPoint(functionBlock);
3720}
3721
Rex Xu04db3f52015-09-16 11:44:02 +08003722void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003723{
Rex Xufc618912015-09-09 16:42:49 +08003724 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003725
3726 glslang::TSampler sampler = {};
3727 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003728#ifdef AMD_EXTENSIONS
3729 bool f16ShadowCompare = false;
3730#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003731 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003732 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3733 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003734#ifdef AMD_EXTENSIONS
3735 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3736#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003737 }
3738
John Kessenich140f3df2015-06-26 16:58:36 -06003739 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3740 builder.clearAccessChain();
3741 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003742
3743 // Special case l-value operands
3744 bool lvalue = false;
3745 switch (node.getOp()) {
3746 case glslang::EOpImageAtomicAdd:
3747 case glslang::EOpImageAtomicMin:
3748 case glslang::EOpImageAtomicMax:
3749 case glslang::EOpImageAtomicAnd:
3750 case glslang::EOpImageAtomicOr:
3751 case glslang::EOpImageAtomicXor:
3752 case glslang::EOpImageAtomicExchange:
3753 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05003754 case glslang::EOpImageAtomicLoad:
3755 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08003756 if (i == 0)
3757 lvalue = true;
3758 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003759 case glslang::EOpSparseImageLoad:
3760 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3761 lvalue = true;
3762 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003763#ifdef AMD_EXTENSIONS
3764 case glslang::EOpSparseTexture:
3765 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3766 lvalue = true;
3767 break;
3768 case glslang::EOpSparseTextureClamp:
3769 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3770 lvalue = true;
3771 break;
3772 case glslang::EOpSparseTextureLod:
3773 case glslang::EOpSparseTextureOffset:
3774 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3775 lvalue = true;
3776 break;
3777#else
Rex Xu48edadf2015-12-31 16:11:41 +08003778 case glslang::EOpSparseTexture:
3779 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3780 lvalue = true;
3781 break;
3782 case glslang::EOpSparseTextureClamp:
3783 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3784 lvalue = true;
3785 break;
3786 case glslang::EOpSparseTextureLod:
3787 case glslang::EOpSparseTextureOffset:
3788 if (i == 3)
3789 lvalue = true;
3790 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003791#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003792 case glslang::EOpSparseTextureFetch:
3793 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3794 lvalue = true;
3795 break;
3796 case glslang::EOpSparseTextureFetchOffset:
3797 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3798 lvalue = true;
3799 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003800#ifdef AMD_EXTENSIONS
3801 case glslang::EOpSparseTextureLodOffset:
3802 case glslang::EOpSparseTextureGrad:
3803 case glslang::EOpSparseTextureOffsetClamp:
3804 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3805 lvalue = true;
3806 break;
3807 case glslang::EOpSparseTextureGradOffset:
3808 case glslang::EOpSparseTextureGradClamp:
3809 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3810 lvalue = true;
3811 break;
3812 case glslang::EOpSparseTextureGradOffsetClamp:
3813 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3814 lvalue = true;
3815 break;
3816#else
Rex Xu48edadf2015-12-31 16:11:41 +08003817 case glslang::EOpSparseTextureLodOffset:
3818 case glslang::EOpSparseTextureGrad:
3819 case glslang::EOpSparseTextureOffsetClamp:
3820 if (i == 4)
3821 lvalue = true;
3822 break;
3823 case glslang::EOpSparseTextureGradOffset:
3824 case glslang::EOpSparseTextureGradClamp:
3825 if (i == 5)
3826 lvalue = true;
3827 break;
3828 case glslang::EOpSparseTextureGradOffsetClamp:
3829 if (i == 6)
3830 lvalue = true;
3831 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003832#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003833 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003834 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3835 lvalue = true;
3836 break;
3837 case glslang::EOpSparseTextureGatherOffset:
3838 case glslang::EOpSparseTextureGatherOffsets:
3839 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3840 lvalue = true;
3841 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003842#ifdef AMD_EXTENSIONS
3843 case glslang::EOpSparseTextureGatherLod:
3844 if (i == 3)
3845 lvalue = true;
3846 break;
3847 case glslang::EOpSparseTextureGatherLodOffset:
3848 case glslang::EOpSparseTextureGatherLodOffsets:
3849 if (i == 4)
3850 lvalue = true;
3851 break;
Rex Xu129799a2017-07-05 17:23:28 +08003852 case glslang::EOpSparseImageLoadLod:
3853 if (i == 3)
3854 lvalue = true;
3855 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003856#endif
Chao Chen3a137962018-09-19 11:41:27 -07003857#ifdef NV_EXTENSIONS
3858 case glslang::EOpImageSampleFootprintNV:
3859 if (i == 4)
3860 lvalue = true;
3861 break;
3862 case glslang::EOpImageSampleFootprintClampNV:
3863 case glslang::EOpImageSampleFootprintLodNV:
3864 if (i == 5)
3865 lvalue = true;
3866 break;
3867 case glslang::EOpImageSampleFootprintGradNV:
3868 if (i == 6)
3869 lvalue = true;
3870 break;
3871 case glslang::EOpImageSampleFootprintGradClampNV:
3872 if (i == 7)
3873 lvalue = true;
3874 break;
3875#endif
Rex Xufc618912015-09-09 16:42:49 +08003876 default:
3877 break;
3878 }
3879
Rex Xu6b86d492015-09-16 17:48:22 +08003880 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003881 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003882 else
John Kessenich32cfd492016-02-02 12:37:46 -07003883 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003884 }
3885}
3886
John Kessenichfc51d282015-08-19 13:34:18 -06003887void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003888{
John Kessenichfc51d282015-08-19 13:34:18 -06003889 builder.clearAccessChain();
3890 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003891 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003892}
John Kessenich140f3df2015-06-26 16:58:36 -06003893
John Kessenichfc51d282015-08-19 13:34:18 -06003894spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3895{
John Kesseniche485c7a2017-05-31 18:50:53 -06003896 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003897 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003898
3899 builder.setLine(node->getLoc().line);
3900
John Kessenichfc51d282015-08-19 13:34:18 -06003901 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05003902
3903 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
3904 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
3905 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003906#ifdef AMD_EXTENSIONS
3907 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3908 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3909 : false;
3910#endif
3911
John Kessenichfc51d282015-08-19 13:34:18 -06003912 std::vector<spv::Id> arguments;
3913 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003914 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003915 else
3916 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003917 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003918
3919 spv::Builder::TextureParameters params = { };
3920 params.sampler = arguments[0];
3921
Rex Xu04db3f52015-09-16 11:44:02 +08003922 glslang::TCrackedTextureOp cracked;
3923 node->crackTexture(sampler, cracked);
3924
amhagan05506bb2017-06-13 16:53:02 -04003925 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003926
John Kessenichfc51d282015-08-19 13:34:18 -06003927 // Check for queries
3928 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003929 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3930 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003931 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003932
John Kessenichfc51d282015-08-19 13:34:18 -06003933 switch (node->getOp()) {
3934 case glslang::EOpImageQuerySize:
3935 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003936 if (arguments.size() > 1) {
3937 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003938 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003939 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003940 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003941 case glslang::EOpImageQuerySamples:
3942 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003943 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003944 case glslang::EOpTextureQueryLod:
3945 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003946 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003947 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003948 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003949 case glslang::EOpSparseTexelsResident:
3950 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003951 default:
3952 assert(0);
3953 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003954 }
John Kessenich140f3df2015-06-26 16:58:36 -06003955 }
3956
LoopDawg4425f242018-02-18 11:40:01 -07003957 int components = node->getType().getVectorSize();
3958
3959 if (node->getOp() == glslang::EOpTextureFetch) {
3960 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3961 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3962 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3963 // here around e.g. which ones return scalars or other types.
3964 components = 4;
3965 }
3966
3967 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3968
3969 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3970
Rex Xufc618912015-09-09 16:42:49 +08003971 // Check for image functions other than queries
3972 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06003973 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06003974 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06003975 spv::IdImmediate image = { true, *(opIt++) };
3976 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07003977
3978 // Handle subpass operations
3979 // TODO: GLSL should change to have the "MS" only on the type rather than the
3980 // built-in function.
3981 if (cracked.subpass) {
3982 // add on the (0,0) coordinate
3983 spv::Id zero = builder.makeIntConstant(0);
3984 std::vector<spv::Id> comps;
3985 comps.push_back(zero);
3986 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06003987 spv::IdImmediate coord = { true,
3988 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
3989 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07003990 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003991 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3992 operands.push_back(imageOperands);
3993 spv::IdImmediate imageOperand = { true, *(opIt++) };
3994 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07003995 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003996 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3997 builder.setPrecision(result, precision);
3998 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003999 }
4000
John Kessenich149afc32018-08-14 13:31:43 -06004001 spv::IdImmediate coord = { true, *(opIt++) };
4002 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004003#ifdef AMD_EXTENSIONS
4004 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4005#else
John Kessenich56bab042015-09-16 10:54:31 -06004006 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004007#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004008 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004009 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004010 mask = mask | spv::ImageOperandsSampleMask;
4011 }
Rex Xu129799a2017-07-05 17:23:28 +08004012#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004013 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004014 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4015 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004016 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004017 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004018#endif
4019 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4020 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4021 if (mask) {
4022 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4023 operands.push_back(imageOperands);
4024 }
4025 if (mask & spv::ImageOperandsSampleMask) {
4026 spv::IdImmediate imageOperand = { true, *opIt++ };
4027 operands.push_back(imageOperand);
4028 }
4029#ifdef AMD_EXTENSIONS
4030 if (mask & spv::ImageOperandsLodMask) {
4031 spv::IdImmediate imageOperand = { true, *opIt++ };
4032 operands.push_back(imageOperand);
4033 }
4034#endif
4035 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4036 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4037 operands.push_back(imageOperand);
4038 }
4039
John Kessenich149afc32018-08-14 13:31:43 -06004040 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004041 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004042
John Kessenich149afc32018-08-14 13:31:43 -06004043 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004044 builder.setPrecision(result[0], precision);
4045
4046 // If needed, add a conversion constructor to the proper size.
4047 if (components != node->getType().getVectorSize())
4048 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4049
4050 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004051#ifdef AMD_EXTENSIONS
4052 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4053#else
John Kessenich56bab042015-09-16 10:54:31 -06004054 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004055#endif
Rex Xu129799a2017-07-05 17:23:28 +08004056
Jeff Bolz36831c92018-09-05 10:11:41 -05004057 // Push the texel value before the operands
4058#ifdef AMD_EXTENSIONS
4059 if (sampler.ms || cracked.lod) {
4060#else
4061 if (sampler.ms) {
4062#endif
John Kessenich149afc32018-08-14 13:31:43 -06004063 spv::IdImmediate texel = { true, *(opIt + 1) };
4064 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004065 } else {
4066 spv::IdImmediate texel = { true, *opIt };
4067 operands.push_back(texel);
4068 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004069
4070 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4071 if (sampler.ms) {
4072 mask = mask | spv::ImageOperandsSampleMask;
4073 }
4074#ifdef AMD_EXTENSIONS
4075 if (cracked.lod) {
4076 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4077 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4078 mask = mask | spv::ImageOperandsLodMask;
4079 }
4080#endif
4081 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4082 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
4083 if (mask) {
4084 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4085 operands.push_back(imageOperands);
4086 }
4087 if (mask & spv::ImageOperandsSampleMask) {
4088 spv::IdImmediate imageOperand = { true, *opIt++ };
4089 operands.push_back(imageOperand);
4090 }
4091#ifdef AMD_EXTENSIONS
4092 if (mask & spv::ImageOperandsLodMask) {
4093 spv::IdImmediate imageOperand = { true, *opIt++ };
4094 operands.push_back(imageOperand);
4095 }
4096#endif
4097 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
4098 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4099 operands.push_back(imageOperand);
4100 }
4101
John Kessenich56bab042015-09-16 10:54:31 -06004102 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004103 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004104 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004105 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004106#ifdef AMD_EXTENSIONS
4107 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
4108#else
Rex Xu5eafa472016-02-19 22:24:03 +08004109 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004110#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004111 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004112 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004113 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4114
Jeff Bolz36831c92018-09-05 10:11:41 -05004115 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004116 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004117 mask = mask | spv::ImageOperandsSampleMask;
4118 }
Rex Xu129799a2017-07-05 17:23:28 +08004119#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004120 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004121 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4122 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4123
Jeff Bolz36831c92018-09-05 10:11:41 -05004124 mask = mask | spv::ImageOperandsLodMask;
4125 }
4126#endif
4127 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4128 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4129 if (mask) {
4130 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004131 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004132 }
4133 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004134 spv::IdImmediate imageOperand = { true, *opIt++ };
4135 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004136 }
4137#ifdef AMD_EXTENSIONS
4138 if (mask & spv::ImageOperandsLodMask) {
4139 spv::IdImmediate imageOperand = { true, *opIt++ };
4140 operands.push_back(imageOperand);
4141 }
Rex Xu129799a2017-07-05 17:23:28 +08004142#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004143 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4144 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4145 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004146 }
4147
4148 // Create the return type that was a special structure
4149 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004150 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004151 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4152 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4153
4154 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4155
4156 // Decode the return type
4157 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4158 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004159 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004160 // Process image atomic operations
4161
4162 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4163 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004164 // For non-MS, the sample value should be 0
4165 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4166 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004167
Jeff Bolz36831c92018-09-05 10:11:41 -05004168 spv::Id resultTypeId;
4169 // imageAtomicStore has a void return type so base the pointer type on
4170 // the type of the value operand.
4171 if (node->getOp() == glslang::EOpImageAtomicStore) {
4172 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4173 } else {
4174 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4175 }
John Kessenich56bab042015-09-16 10:54:31 -06004176 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004177
4178 std::vector<spv::Id> operands;
4179 operands.push_back(pointer);
4180 for (; opIt != arguments.end(); ++opIt)
4181 operands.push_back(*opIt);
4182
John Kessenich8c8505c2016-07-26 12:50:38 -06004183 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004184 }
4185 }
4186
amhagan05506bb2017-06-13 16:53:02 -04004187#ifdef AMD_EXTENSIONS
4188 // Check for fragment mask functions other than queries
4189 if (cracked.fragMask) {
4190 assert(sampler.ms);
4191
4192 auto opIt = arguments.begin();
4193 std::vector<spv::Id> operands;
4194
4195 // Extract the image if necessary
4196 if (builder.isSampledImage(params.sampler))
4197 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4198
4199 operands.push_back(params.sampler);
4200 ++opIt;
4201
4202 if (sampler.isSubpass()) {
4203 // add on the (0,0) coordinate
4204 spv::Id zero = builder.makeIntConstant(0);
4205 std::vector<spv::Id> comps;
4206 comps.push_back(zero);
4207 comps.push_back(zero);
4208 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4209 }
4210
4211 for (; opIt != arguments.end(); ++opIt)
4212 operands.push_back(*opIt);
4213
4214 spv::Op fragMaskOp = spv::OpNop;
4215 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4216 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4217 else if (node->getOp() == glslang::EOpFragmentFetch)
4218 fragMaskOp = spv::OpFragmentFetchAMD;
4219
4220 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4221 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4222 return builder.createOp(fragMaskOp, resultType(), operands);
4223 }
4224#endif
4225
Rex Xufc618912015-09-09 16:42:49 +08004226 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004227 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004228#ifdef NV_EXTENSIONS
4229 bool imageFootprint = node->isImageFootprint();
4230#endif
4231
Rex Xu71519fe2015-11-11 15:35:47 +08004232 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4233
John Kessenichfc51d282015-08-19 13:34:18 -06004234 // check for bias argument
4235 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004236#ifdef AMD_EXTENSIONS
4237 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4238#else
Rex Xu71519fe2015-11-11 15:35:47 +08004239 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004240#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004241 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004242#ifdef AMD_EXTENSIONS
4243 if (cracked.gather)
4244 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004245
4246 if (f16ShadowCompare)
4247 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004248#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004249 if (cracked.offset)
4250 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004251#ifdef AMD_EXTENSIONS
4252 else if (cracked.offsets)
4253 ++nonBiasArgCount;
4254#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004255 if (cracked.grad)
4256 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004257 if (cracked.lodClamp)
4258 ++nonBiasArgCount;
4259 if (sparse)
4260 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004261#ifdef NV_EXTENSIONS
4262 if (imageFootprint)
4263 //Following three extra arguments
4264 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4265 nonBiasArgCount += 3;
4266#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004267 if ((int)arguments.size() > nonBiasArgCount)
4268 bias = true;
4269 }
4270
John Kessenicha5c33d62016-06-02 23:45:21 -06004271 // See if the sampler param should really be just the SPV image part
4272 if (cracked.fetch) {
4273 // a fetch needs to have the image extracted first
4274 if (builder.isSampledImage(params.sampler))
4275 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4276 }
4277
Rex Xu225e0fc2016-11-17 17:47:59 +08004278#ifdef AMD_EXTENSIONS
4279 if (cracked.gather) {
4280 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4281 if (bias || cracked.lod ||
4282 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4283 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004284 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004285 }
4286 }
4287#endif
4288
John Kessenichfc51d282015-08-19 13:34:18 -06004289 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004290
John Kessenichfc51d282015-08-19 13:34:18 -06004291 params.coords = arguments[1];
4292 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004293 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004294
4295 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004296#ifdef AMD_EXTENSIONS
4297 if (cubeCompare || f16ShadowCompare) {
4298#else
Rex Xu48edadf2015-12-31 16:11:41 +08004299 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004300#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004301 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004302 ++extraArgs;
4303 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004304 params.Dref = arguments[2];
4305 ++extraArgs;
4306 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004307 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004308 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004309 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004310 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004311 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004312 dRefComp = builder.getNumComponents(params.coords) - 1;
4313 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004314 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4315 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004316
4317 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004318 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004319 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004320 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004321 } else if (glslangIntermediate->getStage() != EShLangFragment
4322#ifdef NV_EXTENSIONS
4323 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4324 && !(glslangIntermediate->getStage() == EShLangCompute &&
4325 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4326#endif
4327 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004328 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4329 noImplicitLod = true;
4330 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004331
4332 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004333 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004334 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004335 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004336 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004337
4338 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004339 if (cracked.grad) {
4340 params.gradX = arguments[2 + extraArgs];
4341 params.gradY = arguments[3 + extraArgs];
4342 extraArgs += 2;
4343 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004344
4345 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004346 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004347 params.offset = arguments[2 + extraArgs];
4348 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004349 } else if (cracked.offsets) {
4350 params.offsets = arguments[2 + extraArgs];
4351 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004352 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004353
4354 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004355 if (cracked.lodClamp) {
4356 params.lodClamp = arguments[2 + extraArgs];
4357 ++extraArgs;
4358 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004359 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004360 if (sparse) {
4361 params.texelOut = arguments[2 + extraArgs];
4362 ++extraArgs;
4363 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004364
John Kessenich76d4dfc2016-06-16 12:43:23 -06004365 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004366 if (cracked.gather && ! sampler.shadow) {
4367 // default component is 0, if missing, otherwise an argument
4368 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004369 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004370 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004371 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004372 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004373 }
Chao Chen3a137962018-09-19 11:41:27 -07004374#ifdef NV_EXTENSIONS
4375 spv::Id resultStruct = spv::NoResult;
4376 if (imageFootprint) {
4377 //Following three extra arguments
4378 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4379 params.granularity = arguments[2 + extraArgs];
4380 params.coarse = arguments[3 + extraArgs];
4381 resultStruct = arguments[4 + extraArgs];
4382 extraArgs += 3;
4383 }
4384#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004385 // bias
4386 if (bias) {
4387 params.bias = arguments[2 + extraArgs];
4388 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004389 }
John Kessenichfc51d282015-08-19 13:34:18 -06004390
Chao Chen3a137962018-09-19 11:41:27 -07004391#ifdef NV_EXTENSIONS
4392 if (imageFootprint) {
4393 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4394 builder.addCapability(spv::CapabilityImageFootprintNV);
4395
4396
4397 //resultStructType(OpenGL type) contains 5 elements:
4398 //struct gl_TextureFootprint2DNV {
4399 // uvec2 anchor;
4400 // uvec2 offset;
4401 // uvec2 mask;
4402 // uint lod;
4403 // uint granularity;
4404 //};
4405 //or
4406 //struct gl_TextureFootprint3DNV {
4407 // uvec3 anchor;
4408 // uvec3 offset;
4409 // uvec2 mask;
4410 // uint lod;
4411 // uint granularity;
4412 //};
4413 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4414 assert(builder.isStructType(resultStructType));
4415
4416 //resType (SPIR-V type) contains 6 elements:
4417 //Member 0 must be a Boolean type scalar(LOD),
4418 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4419 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4420 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4421 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4422 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4423 std::vector<spv::Id> members;
4424 members.push_back(resultType());
4425 for (int i = 0; i < 5; i++) {
4426 members.push_back(builder.getContainedTypeId(resultStructType, i));
4427 }
4428 spv::Id resType = builder.makeStructType(members, "ResType");
4429
4430 //call ImageFootprintNV
4431 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
4432
4433 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4434 for (int i = 0; i < 5; i++) {
4435 builder.clearAccessChain();
4436 builder.setAccessChainLValue(resultStruct);
4437
4438 //Accessing to a struct we created, no coherent flag is set
4439 spv::Builder::AccessChain::CoherentFlags flags;
4440 flags.clear();
4441
4442 builder.accessChainPush(builder.makeIntConstant(i), flags);
4443 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4444 }
4445 return builder.createCompositeExtract(res, resultType(), 0);
4446 }
4447#endif
4448
John Kessenich65336482016-06-16 14:06:26 -06004449 // projective component (might not to move)
4450 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4451 // are divided by the last component of P."
4452 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4453 // unused components will appear after all used components."
4454 if (cracked.proj) {
4455 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4456 int projTargetComp;
4457 switch (sampler.dim) {
4458 case glslang::Esd1D: projTargetComp = 1; break;
4459 case glslang::Esd2D: projTargetComp = 2; break;
4460 case glslang::EsdRect: projTargetComp = 2; break;
4461 default: projTargetComp = projSourceComp; break;
4462 }
4463 // copy the projective coordinate if we have to
4464 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004465 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004466 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4467 projSourceComp);
4468 params.coords = builder.createCompositeInsert(projComp, params.coords,
4469 builder.getTypeId(params.coords), projTargetComp);
4470 }
4471 }
4472
Jeff Bolz36831c92018-09-05 10:11:41 -05004473 // nonprivate
4474 if (imageType.getQualifier().nonprivate) {
4475 params.nonprivate = true;
4476 }
4477
4478 // volatile
4479 if (imageType.getQualifier().volatil) {
4480 params.volatil = true;
4481 }
4482
St0fFa1184dd2018-04-09 21:08:14 +02004483 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004484 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004485 );
LoopDawg4425f242018-02-18 11:40:01 -07004486
4487 if (components != node->getType().getVectorSize())
4488 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4489
4490 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004491}
4492
4493spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4494{
4495 // Grab the function's pointer from the previously created function
4496 spv::Function* function = functionMap[node->getName().c_str()];
4497 if (! function)
4498 return 0;
4499
4500 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4501 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4502
4503 // See comments in makeFunctions() for details about the semantics for parameter passing.
4504 //
4505 // These imply we need a four step process:
4506 // 1. Evaluate the arguments
4507 // 2. Allocate and make copies of in, out, and inout arguments
4508 // 3. Make the call
4509 // 4. Copy back the results
4510
John Kessenichd3ed90b2018-05-04 11:43:03 -06004511 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004512 std::vector<spv::Builder::AccessChain> lValues;
4513 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004514 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004515 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004516 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004517 // build l-value
4518 builder.clearAccessChain();
4519 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004520 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004521 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004522 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004523 // save l-value
4524 lValues.push_back(builder.getAccessChain());
4525 } else {
4526 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004527 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004528 }
4529 }
4530
4531 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4532 // copy the original into that space.
4533 //
4534 // Also, build up the list of actual arguments to pass in for the call
4535 int lValueCount = 0;
4536 int rValueCount = 0;
4537 std::vector<spv::Id> spvArgs;
4538 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4539 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004540 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004541 builder.setAccessChain(lValues[lValueCount]);
4542 arg = builder.accessChainGetLValue();
4543 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004544 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004545 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004546 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004547 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4548 // need to copy the input into output space
4549 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004550 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004551 builder.clearAccessChain();
4552 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004553 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004554 }
4555 ++lValueCount;
4556 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004557 // process r-value, which involves a copy for a type mismatch
4558 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4559 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4560 builder.clearAccessChain();
4561 builder.setAccessChainLValue(argCopy);
4562 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4563 arg = builder.createLoad(argCopy);
4564 } else
4565 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004566 ++rValueCount;
4567 }
4568 spvArgs.push_back(arg);
4569 }
4570
4571 // 3. Make the call.
4572 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004573 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004574
4575 // 4. Copy back out an "out" arguments.
4576 lValueCount = 0;
4577 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004578 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004579 ++lValueCount;
4580 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004581 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4582 spv::Id copy = builder.createLoad(spvArgs[a]);
4583 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004584 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004585 }
4586 ++lValueCount;
4587 }
4588 }
4589
4590 return result;
4591}
4592
4593// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004594spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004595 spv::Id typeId, spv::Id left, spv::Id right,
4596 glslang::TBasicType typeProxy, bool reduceComparison)
4597{
John Kessenich66011cb2018-03-06 16:12:04 -07004598 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4599 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004600 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004601
4602 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004603 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004604 bool comparison = false;
4605
4606 switch (op) {
4607 case glslang::EOpAdd:
4608 case glslang::EOpAddAssign:
4609 if (isFloat)
4610 binOp = spv::OpFAdd;
4611 else
4612 binOp = spv::OpIAdd;
4613 break;
4614 case glslang::EOpSub:
4615 case glslang::EOpSubAssign:
4616 if (isFloat)
4617 binOp = spv::OpFSub;
4618 else
4619 binOp = spv::OpISub;
4620 break;
4621 case glslang::EOpMul:
4622 case glslang::EOpMulAssign:
4623 if (isFloat)
4624 binOp = spv::OpFMul;
4625 else
4626 binOp = spv::OpIMul;
4627 break;
4628 case glslang::EOpVectorTimesScalar:
4629 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004630 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004631 if (builder.isVector(right))
4632 std::swap(left, right);
4633 assert(builder.isScalar(right));
4634 needMatchingVectors = false;
4635 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01004636 } else if (isFloat)
4637 binOp = spv::OpFMul;
4638 else
John Kessenichec43d0a2015-07-04 17:17:31 -06004639 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004640 break;
4641 case glslang::EOpVectorTimesMatrix:
4642 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004643 binOp = spv::OpVectorTimesMatrix;
4644 break;
4645 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004646 binOp = spv::OpMatrixTimesVector;
4647 break;
4648 case glslang::EOpMatrixTimesScalar:
4649 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004650 binOp = spv::OpMatrixTimesScalar;
4651 break;
4652 case glslang::EOpMatrixTimesMatrix:
4653 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004654 binOp = spv::OpMatrixTimesMatrix;
4655 break;
4656 case glslang::EOpOuterProduct:
4657 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004658 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004659 break;
4660
4661 case glslang::EOpDiv:
4662 case glslang::EOpDivAssign:
4663 if (isFloat)
4664 binOp = spv::OpFDiv;
4665 else if (isUnsigned)
4666 binOp = spv::OpUDiv;
4667 else
4668 binOp = spv::OpSDiv;
4669 break;
4670 case glslang::EOpMod:
4671 case glslang::EOpModAssign:
4672 if (isFloat)
4673 binOp = spv::OpFMod;
4674 else if (isUnsigned)
4675 binOp = spv::OpUMod;
4676 else
4677 binOp = spv::OpSMod;
4678 break;
4679 case glslang::EOpRightShift:
4680 case glslang::EOpRightShiftAssign:
4681 if (isUnsigned)
4682 binOp = spv::OpShiftRightLogical;
4683 else
4684 binOp = spv::OpShiftRightArithmetic;
4685 break;
4686 case glslang::EOpLeftShift:
4687 case glslang::EOpLeftShiftAssign:
4688 binOp = spv::OpShiftLeftLogical;
4689 break;
4690 case glslang::EOpAnd:
4691 case glslang::EOpAndAssign:
4692 binOp = spv::OpBitwiseAnd;
4693 break;
4694 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004695 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004696 binOp = spv::OpLogicalAnd;
4697 break;
4698 case glslang::EOpInclusiveOr:
4699 case glslang::EOpInclusiveOrAssign:
4700 binOp = spv::OpBitwiseOr;
4701 break;
4702 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004703 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004704 binOp = spv::OpLogicalOr;
4705 break;
4706 case glslang::EOpExclusiveOr:
4707 case glslang::EOpExclusiveOrAssign:
4708 binOp = spv::OpBitwiseXor;
4709 break;
4710 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004711 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004712 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004713 break;
4714
4715 case glslang::EOpLessThan:
4716 case glslang::EOpGreaterThan:
4717 case glslang::EOpLessThanEqual:
4718 case glslang::EOpGreaterThanEqual:
4719 case glslang::EOpEqual:
4720 case glslang::EOpNotEqual:
4721 case glslang::EOpVectorEqual:
4722 case glslang::EOpVectorNotEqual:
4723 comparison = true;
4724 break;
4725 default:
4726 break;
4727 }
4728
John Kessenich7c1aa102015-10-15 13:29:11 -06004729 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004730 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004731 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004732 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004733 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004734
4735 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004736 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004737 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004738
qining25262b32016-05-06 17:25:16 -04004739 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004740 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004741 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004742 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004743 }
4744
4745 if (! comparison)
4746 return 0;
4747
John Kessenich7c1aa102015-10-15 13:29:11 -06004748 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004749
John Kessenich4583b612016-08-07 19:14:22 -06004750 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004751 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4752 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004753 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004754 return result;
4755 }
John Kessenich140f3df2015-06-26 16:58:36 -06004756
4757 switch (op) {
4758 case glslang::EOpLessThan:
4759 if (isFloat)
4760 binOp = spv::OpFOrdLessThan;
4761 else if (isUnsigned)
4762 binOp = spv::OpULessThan;
4763 else
4764 binOp = spv::OpSLessThan;
4765 break;
4766 case glslang::EOpGreaterThan:
4767 if (isFloat)
4768 binOp = spv::OpFOrdGreaterThan;
4769 else if (isUnsigned)
4770 binOp = spv::OpUGreaterThan;
4771 else
4772 binOp = spv::OpSGreaterThan;
4773 break;
4774 case glslang::EOpLessThanEqual:
4775 if (isFloat)
4776 binOp = spv::OpFOrdLessThanEqual;
4777 else if (isUnsigned)
4778 binOp = spv::OpULessThanEqual;
4779 else
4780 binOp = spv::OpSLessThanEqual;
4781 break;
4782 case glslang::EOpGreaterThanEqual:
4783 if (isFloat)
4784 binOp = spv::OpFOrdGreaterThanEqual;
4785 else if (isUnsigned)
4786 binOp = spv::OpUGreaterThanEqual;
4787 else
4788 binOp = spv::OpSGreaterThanEqual;
4789 break;
4790 case glslang::EOpEqual:
4791 case glslang::EOpVectorEqual:
4792 if (isFloat)
4793 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004794 else if (isBool)
4795 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004796 else
4797 binOp = spv::OpIEqual;
4798 break;
4799 case glslang::EOpNotEqual:
4800 case glslang::EOpVectorNotEqual:
4801 if (isFloat)
4802 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004803 else if (isBool)
4804 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004805 else
4806 binOp = spv::OpINotEqual;
4807 break;
4808 default:
4809 break;
4810 }
4811
qining25262b32016-05-06 17:25:16 -04004812 if (binOp != spv::OpNop) {
4813 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004814 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004815 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004816 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004817 }
John Kessenich140f3df2015-06-26 16:58:36 -06004818
4819 return 0;
4820}
4821
John Kessenich04bb8a02015-12-12 12:28:14 -07004822//
4823// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4824// These can be any of:
4825//
4826// matrix * scalar
4827// scalar * matrix
4828// matrix * matrix linear algebraic
4829// matrix * vector
4830// vector * matrix
4831// matrix * matrix componentwise
4832// matrix op matrix op in {+, -, /}
4833// matrix op scalar op in {+, -, /}
4834// scalar op matrix op in {+, -, /}
4835//
John Kessenichead86222018-03-28 18:01:20 -06004836spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4837 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004838{
4839 bool firstClass = true;
4840
4841 // First, handle first-class matrix operations (* and matrix/scalar)
4842 switch (op) {
4843 case spv::OpFDiv:
4844 if (builder.isMatrix(left) && builder.isScalar(right)) {
4845 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004846 spv::Id resultType = builder.getTypeId(right);
4847 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004848 op = spv::OpMatrixTimesScalar;
4849 } else
4850 firstClass = false;
4851 break;
4852 case spv::OpMatrixTimesScalar:
4853 if (builder.isMatrix(right))
4854 std::swap(left, right);
4855 assert(builder.isScalar(right));
4856 break;
4857 case spv::OpVectorTimesMatrix:
4858 assert(builder.isVector(left));
4859 assert(builder.isMatrix(right));
4860 break;
4861 case spv::OpMatrixTimesVector:
4862 assert(builder.isMatrix(left));
4863 assert(builder.isVector(right));
4864 break;
4865 case spv::OpMatrixTimesMatrix:
4866 assert(builder.isMatrix(left));
4867 assert(builder.isMatrix(right));
4868 break;
4869 default:
4870 firstClass = false;
4871 break;
4872 }
4873
qining25262b32016-05-06 17:25:16 -04004874 if (firstClass) {
4875 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004876 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004877 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004878 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004879 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004880
LoopDawg592860c2016-06-09 08:57:35 -06004881 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004882 // The result type of all of them is the same type as the (a) matrix operand.
4883 // The algorithm is to:
4884 // - break the matrix(es) into vectors
4885 // - smear any scalar to a vector
4886 // - do vector operations
4887 // - make a matrix out the vector results
4888 switch (op) {
4889 case spv::OpFAdd:
4890 case spv::OpFSub:
4891 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004892 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004893 case spv::OpFMul:
4894 {
4895 // one time set up...
4896 bool leftMat = builder.isMatrix(left);
4897 bool rightMat = builder.isMatrix(right);
4898 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4899 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4900 spv::Id scalarType = builder.getScalarTypeId(typeId);
4901 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4902 std::vector<spv::Id> results;
4903 spv::Id smearVec = spv::NoResult;
4904 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004905 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004906 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004907 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004908
4909 // do each vector op
4910 for (unsigned int c = 0; c < numCols; ++c) {
4911 std::vector<unsigned int> indexes;
4912 indexes.push_back(c);
4913 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4914 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004915 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004916 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004917 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004918 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004919 }
4920
4921 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004922 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004923 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004924 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004925 }
4926 default:
4927 assert(0);
4928 return spv::NoResult;
4929 }
4930}
4931
John Kessenichead86222018-03-28 18:01:20 -06004932spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4933 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004934{
4935 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004936 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004937 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004938 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4939 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004940
4941 switch (op) {
4942 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004943 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004944 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004945 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004946 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004947 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004948 unaryOp = spv::OpSNegate;
4949 break;
4950
4951 case glslang::EOpLogicalNot:
4952 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004953 unaryOp = spv::OpLogicalNot;
4954 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004955 case glslang::EOpBitwiseNot:
4956 unaryOp = spv::OpNot;
4957 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004958
John Kessenich140f3df2015-06-26 16:58:36 -06004959 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004960 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004961 break;
4962 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004963 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004964 break;
4965 case glslang::EOpTranspose:
4966 unaryOp = spv::OpTranspose;
4967 break;
4968
4969 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004970 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004971 break;
4972 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004973 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004974 break;
4975 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004976 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004977 break;
4978 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004979 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004980 break;
4981 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004982 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004983 break;
4984 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004985 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004986 break;
4987 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004988 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004989 break;
4990 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004991 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004992 break;
4993
4994 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004995 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004996 break;
4997 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004998 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004999 break;
5000 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005001 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005002 break;
5003 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005004 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005005 break;
5006 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005007 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005008 break;
5009 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005010 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005011 break;
5012
5013 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005014 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005015 break;
5016 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005017 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005018 break;
5019
5020 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005021 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005022 break;
5023 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005024 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005025 break;
5026 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005027 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005028 break;
5029 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005030 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005031 break;
5032 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005033 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005034 break;
5035 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005036 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005037 break;
5038
5039 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005040 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005041 break;
5042 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005043 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005044 break;
5045 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005046 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005047 break;
5048 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005049 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005050 break;
5051 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005052 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005053 break;
5054 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005055 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005056 break;
5057
5058 case glslang::EOpIsNan:
5059 unaryOp = spv::OpIsNan;
5060 break;
5061 case glslang::EOpIsInf:
5062 unaryOp = spv::OpIsInf;
5063 break;
LoopDawg592860c2016-06-09 08:57:35 -06005064 case glslang::EOpIsFinite:
5065 unaryOp = spv::OpIsFinite;
5066 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005067
Rex Xucbc426e2015-12-15 16:03:10 +08005068 case glslang::EOpFloatBitsToInt:
5069 case glslang::EOpFloatBitsToUint:
5070 case glslang::EOpIntBitsToFloat:
5071 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005072 case glslang::EOpDoubleBitsToInt64:
5073 case glslang::EOpDoubleBitsToUint64:
5074 case glslang::EOpInt64BitsToDouble:
5075 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005076 case glslang::EOpFloat16BitsToInt16:
5077 case glslang::EOpFloat16BitsToUint16:
5078 case glslang::EOpInt16BitsToFloat16:
5079 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005080 unaryOp = spv::OpBitcast;
5081 break;
5082
John Kessenich140f3df2015-06-26 16:58:36 -06005083 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005084 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005085 break;
5086 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005087 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005088 break;
5089 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005090 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005091 break;
5092 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005093 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005094 break;
5095 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005096 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005097 break;
5098 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005099 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005100 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005101 case glslang::EOpPackSnorm4x8:
5102 libCall = spv::GLSLstd450PackSnorm4x8;
5103 break;
5104 case glslang::EOpUnpackSnorm4x8:
5105 libCall = spv::GLSLstd450UnpackSnorm4x8;
5106 break;
5107 case glslang::EOpPackUnorm4x8:
5108 libCall = spv::GLSLstd450PackUnorm4x8;
5109 break;
5110 case glslang::EOpUnpackUnorm4x8:
5111 libCall = spv::GLSLstd450UnpackUnorm4x8;
5112 break;
5113 case glslang::EOpPackDouble2x32:
5114 libCall = spv::GLSLstd450PackDouble2x32;
5115 break;
5116 case glslang::EOpUnpackDouble2x32:
5117 libCall = spv::GLSLstd450UnpackDouble2x32;
5118 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005119
Rex Xu8ff43de2016-04-22 16:51:45 +08005120 case glslang::EOpPackInt2x32:
5121 case glslang::EOpUnpackInt2x32:
5122 case glslang::EOpPackUint2x32:
5123 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005124 case glslang::EOpPack16:
5125 case glslang::EOpPack32:
5126 case glslang::EOpPack64:
5127 case glslang::EOpUnpack32:
5128 case glslang::EOpUnpack16:
5129 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005130 case glslang::EOpPackInt2x16:
5131 case glslang::EOpUnpackInt2x16:
5132 case glslang::EOpPackUint2x16:
5133 case glslang::EOpUnpackUint2x16:
5134 case glslang::EOpPackInt4x16:
5135 case glslang::EOpUnpackInt4x16:
5136 case glslang::EOpPackUint4x16:
5137 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005138 case glslang::EOpPackFloat2x16:
5139 case glslang::EOpUnpackFloat2x16:
5140 unaryOp = spv::OpBitcast;
5141 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005142
John Kessenich140f3df2015-06-26 16:58:36 -06005143 case glslang::EOpDPdx:
5144 unaryOp = spv::OpDPdx;
5145 break;
5146 case glslang::EOpDPdy:
5147 unaryOp = spv::OpDPdy;
5148 break;
5149 case glslang::EOpFwidth:
5150 unaryOp = spv::OpFwidth;
5151 break;
5152 case glslang::EOpDPdxFine:
5153 unaryOp = spv::OpDPdxFine;
5154 break;
5155 case glslang::EOpDPdyFine:
5156 unaryOp = spv::OpDPdyFine;
5157 break;
5158 case glslang::EOpFwidthFine:
5159 unaryOp = spv::OpFwidthFine;
5160 break;
5161 case glslang::EOpDPdxCoarse:
5162 unaryOp = spv::OpDPdxCoarse;
5163 break;
5164 case glslang::EOpDPdyCoarse:
5165 unaryOp = spv::OpDPdyCoarse;
5166 break;
5167 case glslang::EOpFwidthCoarse:
5168 unaryOp = spv::OpFwidthCoarse;
5169 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005170 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005171#ifdef AMD_EXTENSIONS
5172 if (typeProxy == glslang::EbtFloat16)
5173 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5174#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005175 libCall = spv::GLSLstd450InterpolateAtCentroid;
5176 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005177 case glslang::EOpAny:
5178 unaryOp = spv::OpAny;
5179 break;
5180 case glslang::EOpAll:
5181 unaryOp = spv::OpAll;
5182 break;
5183
5184 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005185 if (isFloat)
5186 libCall = spv::GLSLstd450FAbs;
5187 else
5188 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005189 break;
5190 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005191 if (isFloat)
5192 libCall = spv::GLSLstd450FSign;
5193 else
5194 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005195 break;
5196
John Kessenichfc51d282015-08-19 13:34:18 -06005197 case glslang::EOpAtomicCounterIncrement:
5198 case glslang::EOpAtomicCounterDecrement:
5199 case glslang::EOpAtomicCounter:
5200 {
5201 // Handle all of the atomics in one place, in createAtomicOperation()
5202 std::vector<spv::Id> operands;
5203 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005204 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005205 }
5206
John Kessenichfc51d282015-08-19 13:34:18 -06005207 case glslang::EOpBitFieldReverse:
5208 unaryOp = spv::OpBitReverse;
5209 break;
5210 case glslang::EOpBitCount:
5211 unaryOp = spv::OpBitCount;
5212 break;
5213 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005214 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005215 break;
5216 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005217 if (isUnsigned)
5218 libCall = spv::GLSLstd450FindUMsb;
5219 else
5220 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005221 break;
5222
Rex Xu574ab042016-04-14 16:53:07 +08005223 case glslang::EOpBallot:
5224 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005225 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005226 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005227 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005228#ifdef AMD_EXTENSIONS
5229 case glslang::EOpMinInvocations:
5230 case glslang::EOpMaxInvocations:
5231 case glslang::EOpAddInvocations:
5232 case glslang::EOpMinInvocationsNonUniform:
5233 case glslang::EOpMaxInvocationsNonUniform:
5234 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005235 case glslang::EOpMinInvocationsInclusiveScan:
5236 case glslang::EOpMaxInvocationsInclusiveScan:
5237 case glslang::EOpAddInvocationsInclusiveScan:
5238 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5239 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5240 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5241 case glslang::EOpMinInvocationsExclusiveScan:
5242 case glslang::EOpMaxInvocationsExclusiveScan:
5243 case glslang::EOpAddInvocationsExclusiveScan:
5244 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5245 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5246 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005247#endif
Rex Xu51596642016-09-21 18:56:12 +08005248 {
5249 std::vector<spv::Id> operands;
5250 operands.push_back(operand);
5251 return createInvocationsOperation(op, typeId, operands, typeProxy);
5252 }
John Kessenich66011cb2018-03-06 16:12:04 -07005253 case glslang::EOpSubgroupAll:
5254 case glslang::EOpSubgroupAny:
5255 case glslang::EOpSubgroupAllEqual:
5256 case glslang::EOpSubgroupBroadcastFirst:
5257 case glslang::EOpSubgroupBallot:
5258 case glslang::EOpSubgroupInverseBallot:
5259 case glslang::EOpSubgroupBallotBitCount:
5260 case glslang::EOpSubgroupBallotInclusiveBitCount:
5261 case glslang::EOpSubgroupBallotExclusiveBitCount:
5262 case glslang::EOpSubgroupBallotFindLSB:
5263 case glslang::EOpSubgroupBallotFindMSB:
5264 case glslang::EOpSubgroupAdd:
5265 case glslang::EOpSubgroupMul:
5266 case glslang::EOpSubgroupMin:
5267 case glslang::EOpSubgroupMax:
5268 case glslang::EOpSubgroupAnd:
5269 case glslang::EOpSubgroupOr:
5270 case glslang::EOpSubgroupXor:
5271 case glslang::EOpSubgroupInclusiveAdd:
5272 case glslang::EOpSubgroupInclusiveMul:
5273 case glslang::EOpSubgroupInclusiveMin:
5274 case glslang::EOpSubgroupInclusiveMax:
5275 case glslang::EOpSubgroupInclusiveAnd:
5276 case glslang::EOpSubgroupInclusiveOr:
5277 case glslang::EOpSubgroupInclusiveXor:
5278 case glslang::EOpSubgroupExclusiveAdd:
5279 case glslang::EOpSubgroupExclusiveMul:
5280 case glslang::EOpSubgroupExclusiveMin:
5281 case glslang::EOpSubgroupExclusiveMax:
5282 case glslang::EOpSubgroupExclusiveAnd:
5283 case glslang::EOpSubgroupExclusiveOr:
5284 case glslang::EOpSubgroupExclusiveXor:
5285 case glslang::EOpSubgroupQuadSwapHorizontal:
5286 case glslang::EOpSubgroupQuadSwapVertical:
5287 case glslang::EOpSubgroupQuadSwapDiagonal: {
5288 std::vector<spv::Id> operands;
5289 operands.push_back(operand);
5290 return createSubgroupOperation(op, typeId, operands, typeProxy);
5291 }
Rex Xu9d93a232016-05-05 12:30:44 +08005292#ifdef AMD_EXTENSIONS
5293 case glslang::EOpMbcnt:
5294 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5295 libCall = spv::MbcntAMD;
5296 break;
5297
5298 case glslang::EOpCubeFaceIndex:
5299 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5300 libCall = spv::CubeFaceIndexAMD;
5301 break;
5302
5303 case glslang::EOpCubeFaceCoord:
5304 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5305 libCall = spv::CubeFaceCoordAMD;
5306 break;
5307#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005308#ifdef NV_EXTENSIONS
5309 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005310 unaryOp = spv::OpGroupNonUniformPartitionNV;
5311 break;
5312#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005313 default:
5314 return 0;
5315 }
5316
5317 spv::Id id;
5318 if (libCall >= 0) {
5319 std::vector<spv::Id> args;
5320 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005321 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005322 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005323 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005324 }
John Kessenich140f3df2015-06-26 16:58:36 -06005325
John Kessenichead86222018-03-28 18:01:20 -06005326 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005327 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005328 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005329}
5330
John Kessenich7a53f762016-01-20 11:19:27 -07005331// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005332spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5333 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005334{
5335 // Handle unary operations vector by vector.
5336 // The result type is the same type as the original type.
5337 // The algorithm is to:
5338 // - break the matrix into vectors
5339 // - apply the operation to each vector
5340 // - make a matrix out the vector results
5341
5342 // get the types sorted out
5343 int numCols = builder.getNumColumns(operand);
5344 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005345 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5346 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005347 std::vector<spv::Id> results;
5348
5349 // do each vector op
5350 for (int c = 0; c < numCols; ++c) {
5351 std::vector<unsigned int> indexes;
5352 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005353 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5354 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005355 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005356 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005357 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005358 }
5359
5360 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005361 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005362 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005363 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005364}
5365
John Kessenichad7645f2018-06-04 19:11:25 -06005366// For converting integers where both the bitwidth and the signedness could
5367// change, but only do the width change here. The caller is still responsible
5368// for the signedness conversion.
5369spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005370{
John Kessenichad7645f2018-06-04 19:11:25 -06005371 // Get the result type width, based on the type to convert to.
5372 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005373 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005374 case glslang::EOpConvInt16ToUint8:
5375 case glslang::EOpConvIntToUint8:
5376 case glslang::EOpConvInt64ToUint8:
5377 case glslang::EOpConvUint16ToInt8:
5378 case glslang::EOpConvUintToInt8:
5379 case glslang::EOpConvUint64ToInt8:
5380 width = 8;
5381 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005382 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005383 case glslang::EOpConvIntToUint16:
5384 case glslang::EOpConvInt64ToUint16:
5385 case glslang::EOpConvUint8ToInt16:
5386 case glslang::EOpConvUintToInt16:
5387 case glslang::EOpConvUint64ToInt16:
5388 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005389 break;
5390 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005391 case glslang::EOpConvInt16ToUint:
5392 case glslang::EOpConvInt64ToUint:
5393 case glslang::EOpConvUint8ToInt:
5394 case glslang::EOpConvUint16ToInt:
5395 case glslang::EOpConvUint64ToInt:
5396 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005397 break;
5398 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005399 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005400 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005401 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005402 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005403 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005404 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005405 break;
5406
5407 default:
5408 assert(false && "Default missing");
5409 break;
5410 }
5411
John Kessenichad7645f2018-06-04 19:11:25 -06005412 // Get the conversion operation and result type,
5413 // based on the target width, but the source type.
5414 spv::Id type = spv::NoType;
5415 spv::Op convOp = spv::OpNop;
5416 switch(op) {
5417 case glslang::EOpConvInt8ToUint16:
5418 case glslang::EOpConvInt8ToUint:
5419 case glslang::EOpConvInt8ToUint64:
5420 case glslang::EOpConvInt16ToUint8:
5421 case glslang::EOpConvInt16ToUint:
5422 case glslang::EOpConvInt16ToUint64:
5423 case glslang::EOpConvIntToUint8:
5424 case glslang::EOpConvIntToUint16:
5425 case glslang::EOpConvIntToUint64:
5426 case glslang::EOpConvInt64ToUint8:
5427 case glslang::EOpConvInt64ToUint16:
5428 case glslang::EOpConvInt64ToUint:
5429 convOp = spv::OpSConvert;
5430 type = builder.makeIntType(width);
5431 break;
5432 default:
5433 convOp = spv::OpUConvert;
5434 type = builder.makeUintType(width);
5435 break;
5436 }
5437
John Kessenich66011cb2018-03-06 16:12:04 -07005438 if (vectorSize > 0)
5439 type = builder.makeVectorType(type, vectorSize);
5440
John Kessenichad7645f2018-06-04 19:11:25 -06005441 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005442}
5443
John Kessenichead86222018-03-28 18:01:20 -06005444spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5445 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005446{
5447 spv::Op convOp = spv::OpNop;
5448 spv::Id zero = 0;
5449 spv::Id one = 0;
5450
5451 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5452
5453 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005454 case glslang::EOpConvInt8ToBool:
5455 case glslang::EOpConvUint8ToBool:
5456 zero = builder.makeUint8Constant(0);
5457 zero = makeSmearedConstant(zero, vectorSize);
5458 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005459 case glslang::EOpConvInt16ToBool:
5460 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005461 zero = builder.makeUint16Constant(0);
5462 zero = makeSmearedConstant(zero, vectorSize);
5463 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5464 case glslang::EOpConvIntToBool:
5465 case glslang::EOpConvUintToBool:
5466 zero = builder.makeUintConstant(0);
5467 zero = makeSmearedConstant(zero, vectorSize);
5468 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5469 case glslang::EOpConvInt64ToBool:
5470 case glslang::EOpConvUint64ToBool:
5471 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005472 zero = makeSmearedConstant(zero, vectorSize);
5473 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5474
5475 case glslang::EOpConvFloatToBool:
5476 zero = builder.makeFloatConstant(0.0F);
5477 zero = makeSmearedConstant(zero, vectorSize);
5478 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5479
5480 case glslang::EOpConvDoubleToBool:
5481 zero = builder.makeDoubleConstant(0.0);
5482 zero = makeSmearedConstant(zero, vectorSize);
5483 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5484
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005485 case glslang::EOpConvFloat16ToBool:
5486 zero = builder.makeFloat16Constant(0.0F);
5487 zero = makeSmearedConstant(zero, vectorSize);
5488 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005489
John Kessenich140f3df2015-06-26 16:58:36 -06005490 case glslang::EOpConvBoolToFloat:
5491 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005492 zero = builder.makeFloatConstant(0.0F);
5493 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005494 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005495
John Kessenich140f3df2015-06-26 16:58:36 -06005496 case glslang::EOpConvBoolToDouble:
5497 convOp = spv::OpSelect;
5498 zero = builder.makeDoubleConstant(0.0);
5499 one = builder.makeDoubleConstant(1.0);
5500 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005501
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005502 case glslang::EOpConvBoolToFloat16:
5503 convOp = spv::OpSelect;
5504 zero = builder.makeFloat16Constant(0.0F);
5505 one = builder.makeFloat16Constant(1.0F);
5506 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005507
5508 case glslang::EOpConvBoolToInt8:
5509 zero = builder.makeInt8Constant(0);
5510 one = builder.makeInt8Constant(1);
5511 convOp = spv::OpSelect;
5512 break;
5513
5514 case glslang::EOpConvBoolToUint8:
5515 zero = builder.makeUint8Constant(0);
5516 one = builder.makeUint8Constant(1);
5517 convOp = spv::OpSelect;
5518 break;
5519
5520 case glslang::EOpConvBoolToInt16:
5521 zero = builder.makeInt16Constant(0);
5522 one = builder.makeInt16Constant(1);
5523 convOp = spv::OpSelect;
5524 break;
5525
5526 case glslang::EOpConvBoolToUint16:
5527 zero = builder.makeUint16Constant(0);
5528 one = builder.makeUint16Constant(1);
5529 convOp = spv::OpSelect;
5530 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005531
John Kessenich140f3df2015-06-26 16:58:36 -06005532 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005533 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005534 if (op == glslang::EOpConvBoolToInt64)
5535 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005536 else
5537 zero = builder.makeIntConstant(0);
5538
5539 if (op == glslang::EOpConvBoolToInt64)
5540 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005541 else
5542 one = builder.makeIntConstant(1);
5543
John Kessenich140f3df2015-06-26 16:58:36 -06005544 convOp = spv::OpSelect;
5545 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005546
John Kessenich140f3df2015-06-26 16:58:36 -06005547 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005548 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005549 if (op == glslang::EOpConvBoolToUint64)
5550 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005551 else
5552 zero = builder.makeUintConstant(0);
5553
5554 if (op == glslang::EOpConvBoolToUint64)
5555 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005556 else
5557 one = builder.makeUintConstant(1);
5558
John Kessenich140f3df2015-06-26 16:58:36 -06005559 convOp = spv::OpSelect;
5560 break;
5561
John Kessenich66011cb2018-03-06 16:12:04 -07005562 case glslang::EOpConvInt8ToFloat16:
5563 case glslang::EOpConvInt8ToFloat:
5564 case glslang::EOpConvInt8ToDouble:
5565 case glslang::EOpConvInt16ToFloat16:
5566 case glslang::EOpConvInt16ToFloat:
5567 case glslang::EOpConvInt16ToDouble:
5568 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005569 case glslang::EOpConvIntToFloat:
5570 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005571 case glslang::EOpConvInt64ToFloat:
5572 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005573 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005574 convOp = spv::OpConvertSToF;
5575 break;
5576
John Kessenich66011cb2018-03-06 16:12:04 -07005577 case glslang::EOpConvUint8ToFloat16:
5578 case glslang::EOpConvUint8ToFloat:
5579 case glslang::EOpConvUint8ToDouble:
5580 case glslang::EOpConvUint16ToFloat16:
5581 case glslang::EOpConvUint16ToFloat:
5582 case glslang::EOpConvUint16ToDouble:
5583 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005584 case glslang::EOpConvUintToFloat:
5585 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005586 case glslang::EOpConvUint64ToFloat:
5587 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005588 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005589 convOp = spv::OpConvertUToF;
5590 break;
5591
5592 case glslang::EOpConvDoubleToFloat:
5593 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005594 case glslang::EOpConvDoubleToFloat16:
5595 case glslang::EOpConvFloat16ToDouble:
5596 case glslang::EOpConvFloatToFloat16:
5597 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005598 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005599 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005600 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005601 break;
5602
John Kessenich66011cb2018-03-06 16:12:04 -07005603 case glslang::EOpConvFloat16ToInt8:
5604 case glslang::EOpConvFloatToInt8:
5605 case glslang::EOpConvDoubleToInt8:
5606 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005607 case glslang::EOpConvFloatToInt16:
5608 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005609 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005610 case glslang::EOpConvFloatToInt:
5611 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005612 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005613 case glslang::EOpConvFloatToInt64:
5614 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005615 convOp = spv::OpConvertFToS;
5616 break;
5617
John Kessenich66011cb2018-03-06 16:12:04 -07005618 case glslang::EOpConvUint8ToInt8:
5619 case glslang::EOpConvInt8ToUint8:
5620 case glslang::EOpConvUint16ToInt16:
5621 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005622 case glslang::EOpConvUintToInt:
5623 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005624 case glslang::EOpConvUint64ToInt64:
5625 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005626 if (builder.isInSpecConstCodeGenMode()) {
5627 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005628 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5629 zero = builder.makeUint8Constant(0);
5630 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005631 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005632 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5633 zero = builder.makeUint64Constant(0);
5634 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005635 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005636 }
qining189b2032016-04-12 23:16:20 -04005637 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005638 // Use OpIAdd, instead of OpBitcast to do the conversion when
5639 // generating for OpSpecConstantOp instruction.
5640 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5641 }
5642 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005643 convOp = spv::OpBitcast;
5644 break;
5645
John Kessenich66011cb2018-03-06 16:12:04 -07005646 case glslang::EOpConvFloat16ToUint8:
5647 case glslang::EOpConvFloatToUint8:
5648 case glslang::EOpConvDoubleToUint8:
5649 case glslang::EOpConvFloat16ToUint16:
5650 case glslang::EOpConvFloatToUint16:
5651 case glslang::EOpConvDoubleToUint16:
5652 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005653 case glslang::EOpConvFloatToUint:
5654 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005655 case glslang::EOpConvFloatToUint64:
5656 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005657 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005658 convOp = spv::OpConvertFToU;
5659 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005660
John Kessenich66011cb2018-03-06 16:12:04 -07005661 case glslang::EOpConvInt8ToInt16:
5662 case glslang::EOpConvInt8ToInt:
5663 case glslang::EOpConvInt8ToInt64:
5664 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005665 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005666 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005667 case glslang::EOpConvIntToInt8:
5668 case glslang::EOpConvIntToInt16:
5669 case glslang::EOpConvIntToInt64:
5670 case glslang::EOpConvInt64ToInt8:
5671 case glslang::EOpConvInt64ToInt16:
5672 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005673 convOp = spv::OpSConvert;
5674 break;
5675
John Kessenich66011cb2018-03-06 16:12:04 -07005676 case glslang::EOpConvUint8ToUint16:
5677 case glslang::EOpConvUint8ToUint:
5678 case glslang::EOpConvUint8ToUint64:
5679 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005680 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005681 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005682 case glslang::EOpConvUintToUint8:
5683 case glslang::EOpConvUintToUint16:
5684 case glslang::EOpConvUintToUint64:
5685 case glslang::EOpConvUint64ToUint8:
5686 case glslang::EOpConvUint64ToUint16:
5687 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005688 convOp = spv::OpUConvert;
5689 break;
5690
John Kessenich66011cb2018-03-06 16:12:04 -07005691 case glslang::EOpConvInt8ToUint16:
5692 case glslang::EOpConvInt8ToUint:
5693 case glslang::EOpConvInt8ToUint64:
5694 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005695 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005696 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005697 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005698 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005699 case glslang::EOpConvIntToUint64:
5700 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005701 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005702 case glslang::EOpConvInt64ToUint:
5703 case glslang::EOpConvUint8ToInt16:
5704 case glslang::EOpConvUint8ToInt:
5705 case glslang::EOpConvUint8ToInt64:
5706 case glslang::EOpConvUint16ToInt8:
5707 case glslang::EOpConvUint16ToInt:
5708 case glslang::EOpConvUint16ToInt64:
5709 case glslang::EOpConvUintToInt8:
5710 case glslang::EOpConvUintToInt16:
5711 case glslang::EOpConvUintToInt64:
5712 case glslang::EOpConvUint64ToInt8:
5713 case glslang::EOpConvUint64ToInt16:
5714 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005715 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005716 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005717
5718 if (builder.isInSpecConstCodeGenMode()) {
5719 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005720 switch(op) {
5721 case glslang::EOpConvInt16ToUint8:
5722 case glslang::EOpConvIntToUint8:
5723 case glslang::EOpConvInt64ToUint8:
5724 case glslang::EOpConvUint16ToInt8:
5725 case glslang::EOpConvUintToInt8:
5726 case glslang::EOpConvUint64ToInt8:
5727 zero = builder.makeUint8Constant(0);
5728 break;
5729 case glslang::EOpConvInt8ToUint16:
5730 case glslang::EOpConvIntToUint16:
5731 case glslang::EOpConvInt64ToUint16:
5732 case glslang::EOpConvUint8ToInt16:
5733 case glslang::EOpConvUintToInt16:
5734 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005735 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005736 break;
5737 case glslang::EOpConvInt8ToUint:
5738 case glslang::EOpConvInt16ToUint:
5739 case glslang::EOpConvInt64ToUint:
5740 case glslang::EOpConvUint8ToInt:
5741 case glslang::EOpConvUint16ToInt:
5742 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005743 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005744 break;
5745 case glslang::EOpConvInt8ToUint64:
5746 case glslang::EOpConvInt16ToUint64:
5747 case glslang::EOpConvIntToUint64:
5748 case glslang::EOpConvUint8ToInt64:
5749 case glslang::EOpConvUint16ToInt64:
5750 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005751 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005752 break;
5753 default:
5754 assert(false && "Default missing");
5755 break;
5756 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005757 zero = makeSmearedConstant(zero, vectorSize);
5758 // Use OpIAdd, instead of OpBitcast to do the conversion when
5759 // generating for OpSpecConstantOp instruction.
5760 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5761 }
5762 // For normal run-time conversion instruction, use OpBitcast.
5763 convOp = spv::OpBitcast;
5764 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005765 default:
5766 break;
5767 }
5768
5769 spv::Id result = 0;
5770 if (convOp == spv::OpNop)
5771 return result;
5772
5773 if (convOp == spv::OpSelect) {
5774 zero = makeSmearedConstant(zero, vectorSize);
5775 one = makeSmearedConstant(one, vectorSize);
5776 result = builder.createTriOp(convOp, destType, operand, one, zero);
5777 } else
5778 result = builder.createUnaryOp(convOp, destType, operand);
5779
John Kessenichead86222018-03-28 18:01:20 -06005780 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005781 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005782 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005783}
5784
5785spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5786{
5787 if (vectorSize == 0)
5788 return constant;
5789
5790 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5791 std::vector<spv::Id> components;
5792 for (int c = 0; c < vectorSize; ++c)
5793 components.push_back(constant);
5794 return builder.makeCompositeConstant(vectorTypeId, components);
5795}
5796
John Kessenich426394d2015-07-23 10:22:48 -06005797// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005798spv::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 -06005799{
5800 spv::Op opCode = spv::OpNop;
5801
5802 switch (op) {
5803 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005804 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005805 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005806 opCode = spv::OpAtomicIAdd;
5807 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005808 case glslang::EOpAtomicCounterSubtract:
5809 opCode = spv::OpAtomicISub;
5810 break;
John Kessenich426394d2015-07-23 10:22:48 -06005811 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005812 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005813 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005814 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005815 break;
5816 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005817 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005818 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005819 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005820 break;
5821 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005822 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005823 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005824 opCode = spv::OpAtomicAnd;
5825 break;
5826 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005827 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005828 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005829 opCode = spv::OpAtomicOr;
5830 break;
5831 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005832 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005833 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005834 opCode = spv::OpAtomicXor;
5835 break;
5836 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005837 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005838 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005839 opCode = spv::OpAtomicExchange;
5840 break;
5841 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005842 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005843 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005844 opCode = spv::OpAtomicCompareExchange;
5845 break;
5846 case glslang::EOpAtomicCounterIncrement:
5847 opCode = spv::OpAtomicIIncrement;
5848 break;
5849 case glslang::EOpAtomicCounterDecrement:
5850 opCode = spv::OpAtomicIDecrement;
5851 break;
5852 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05005853 case glslang::EOpImageAtomicLoad:
5854 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06005855 opCode = spv::OpAtomicLoad;
5856 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05005857 case glslang::EOpAtomicStore:
5858 case glslang::EOpImageAtomicStore:
5859 opCode = spv::OpAtomicStore;
5860 break;
John Kessenich426394d2015-07-23 10:22:48 -06005861 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005862 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005863 break;
5864 }
5865
Rex Xue8fe8b02017-09-26 15:42:56 +08005866 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5867 builder.addCapability(spv::CapabilityInt64Atomics);
5868
John Kessenich426394d2015-07-23 10:22:48 -06005869 // Sort out the operands
5870 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05005871 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06005872 // - compare-exchange swaps the value and comparator
5873 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005874 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05005875 spv::Id pointerId = 0, compareId = 0, valueId = 0;
5876 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
5877 spv::Id scopeId;
5878 if (glslangIntermediate->usingVulkanMemoryModel()) {
5879 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
5880 } else {
5881 scopeId = builder.makeUintConstant(spv::ScopeDevice);
5882 }
5883 // semantics default to relaxed
5884 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
5885 spv::Id semanticsId2 = semanticsId;
5886
5887 pointerId = operands[0];
5888 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
5889 // no additional operands
5890 } else if (opCode == spv::OpAtomicCompareExchange) {
5891 compareId = operands[1];
5892 valueId = operands[2];
5893 if (operands.size() > 3) {
5894 scopeId = operands[3];
5895 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
5896 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
5897 }
5898 } else if (opCode == spv::OpAtomicLoad) {
5899 if (operands.size() > 1) {
5900 scopeId = operands[1];
5901 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
5902 }
5903 } else {
5904 // atomic store or RMW
5905 valueId = operands[1];
5906 if (operands.size() > 2) {
5907 scopeId = operands[2];
5908 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
5909 }
Rex Xu04db3f52015-09-16 11:44:02 +08005910 }
John Kessenich426394d2015-07-23 10:22:48 -06005911
Jeff Bolz36831c92018-09-05 10:11:41 -05005912 // Check for capabilities
5913 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
5914 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
5915 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
5916 }
John Kessenich426394d2015-07-23 10:22:48 -06005917
Jeff Bolz36831c92018-09-05 10:11:41 -05005918 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
5919 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
5920 }
John Kessenich48d6e792017-10-06 21:21:48 -06005921
Jeff Bolz36831c92018-09-05 10:11:41 -05005922 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5923 spvAtomicOperands.push_back(pointerId);
5924 spvAtomicOperands.push_back(scopeId);
5925 spvAtomicOperands.push_back(semanticsId);
5926 if (opCode == spv::OpAtomicCompareExchange) {
5927 spvAtomicOperands.push_back(semanticsId2);
5928 spvAtomicOperands.push_back(valueId);
5929 spvAtomicOperands.push_back(compareId);
5930 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
5931 spvAtomicOperands.push_back(valueId);
5932 }
John Kessenich48d6e792017-10-06 21:21:48 -06005933
Jeff Bolz36831c92018-09-05 10:11:41 -05005934 if (opCode == spv::OpAtomicStore) {
5935 builder.createNoResultOp(opCode, spvAtomicOperands);
5936 return 0;
5937 } else {
5938 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5939
5940 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5941 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5942 if (op == glslang::EOpAtomicCounterDecrement)
5943 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5944
5945 return resultId;
5946 }
John Kessenich426394d2015-07-23 10:22:48 -06005947}
5948
John Kessenich91cef522016-05-05 16:45:40 -06005949// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005950spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005951{
Corentin Walleze7061422018-08-08 15:20:15 +02005952#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07005953 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5954 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02005955#endif
Rex Xu9d93a232016-05-05 12:30:44 +08005956
Rex Xu51596642016-09-21 18:56:12 +08005957 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06005958 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005959 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5960
chaocf200da82016-12-20 12:44:35 -08005961 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5962 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005963 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5964 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005965 } else if (op == glslang::EOpAnyInvocation ||
5966 op == glslang::EOpAllInvocations ||
5967 op == glslang::EOpAllInvocationsEqual) {
5968 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5969 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005970 } else {
5971 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005972#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005973 if (op == glslang::EOpMinInvocationsNonUniform ||
5974 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005975 op == glslang::EOpAddInvocationsNonUniform ||
5976 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5977 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5978 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5979 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5980 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5981 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005982 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005983#endif
Rex Xu51596642016-09-21 18:56:12 +08005984
Rex Xu9d93a232016-05-05 12:30:44 +08005985#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005986 switch (op) {
5987 case glslang::EOpMinInvocations:
5988 case glslang::EOpMaxInvocations:
5989 case glslang::EOpAddInvocations:
5990 case glslang::EOpMinInvocationsNonUniform:
5991 case glslang::EOpMaxInvocationsNonUniform:
5992 case glslang::EOpAddInvocationsNonUniform:
5993 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08005994 break;
5995 case glslang::EOpMinInvocationsInclusiveScan:
5996 case glslang::EOpMaxInvocationsInclusiveScan:
5997 case glslang::EOpAddInvocationsInclusiveScan:
5998 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5999 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6000 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6001 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006002 break;
6003 case glslang::EOpMinInvocationsExclusiveScan:
6004 case glslang::EOpMaxInvocationsExclusiveScan:
6005 case glslang::EOpAddInvocationsExclusiveScan:
6006 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6007 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6008 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6009 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006010 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006011 default:
6012 break;
Rex Xu430ef402016-10-14 17:22:23 +08006013 }
John Kessenich149afc32018-08-14 13:31:43 -06006014 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6015 spvGroupOperands.push_back(scope);
6016 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006017 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006018 spvGroupOperands.push_back(groupOp);
6019 }
Rex Xu9d93a232016-05-05 12:30:44 +08006020#endif
Rex Xu51596642016-09-21 18:56:12 +08006021 }
6022
John Kessenich149afc32018-08-14 13:31:43 -06006023 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6024 spv::IdImmediate op = { true, *opIt };
6025 spvGroupOperands.push_back(op);
6026 }
John Kessenich91cef522016-05-05 16:45:40 -06006027
6028 switch (op) {
6029 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006030 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006031 break;
John Kessenich91cef522016-05-05 16:45:40 -06006032 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006033 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006034 break;
John Kessenich91cef522016-05-05 16:45:40 -06006035 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006036 opCode = spv::OpSubgroupAllEqualKHR;
6037 break;
Rex Xu51596642016-09-21 18:56:12 +08006038 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006039 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006040 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006041 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006042 break;
6043 case glslang::EOpReadFirstInvocation:
6044 opCode = spv::OpSubgroupFirstInvocationKHR;
6045 break;
6046 case glslang::EOpBallot:
6047 {
6048 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6049 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6050 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6051 //
6052 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6053 //
6054 spv::Id uintType = builder.makeUintType(32);
6055 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6056 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6057
6058 std::vector<spv::Id> components;
6059 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6060 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6061
6062 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6063 return builder.createUnaryOp(spv::OpBitcast, typeId,
6064 builder.createCompositeConstruct(uvec2Type, components));
6065 }
6066
Rex Xu9d93a232016-05-05 12:30:44 +08006067#ifdef AMD_EXTENSIONS
6068 case glslang::EOpMinInvocations:
6069 case glslang::EOpMaxInvocations:
6070 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006071 case glslang::EOpMinInvocationsInclusiveScan:
6072 case glslang::EOpMaxInvocationsInclusiveScan:
6073 case glslang::EOpAddInvocationsInclusiveScan:
6074 case glslang::EOpMinInvocationsExclusiveScan:
6075 case glslang::EOpMaxInvocationsExclusiveScan:
6076 case glslang::EOpAddInvocationsExclusiveScan:
6077 if (op == glslang::EOpMinInvocations ||
6078 op == glslang::EOpMinInvocationsInclusiveScan ||
6079 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006080 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006081 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006082 else {
6083 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006084 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006085 else
Rex Xu51596642016-09-21 18:56:12 +08006086 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006087 }
Rex Xu430ef402016-10-14 17:22:23 +08006088 } else if (op == glslang::EOpMaxInvocations ||
6089 op == glslang::EOpMaxInvocationsInclusiveScan ||
6090 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006091 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006092 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006093 else {
6094 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006095 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006096 else
Rex Xu51596642016-09-21 18:56:12 +08006097 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006098 }
6099 } else {
6100 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006101 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006102 else
Rex Xu51596642016-09-21 18:56:12 +08006103 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006104 }
6105
Rex Xu2bbbe062016-08-23 15:41:05 +08006106 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006107 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006108
6109 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006110 case glslang::EOpMinInvocationsNonUniform:
6111 case glslang::EOpMaxInvocationsNonUniform:
6112 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006113 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6114 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6115 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6116 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6117 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6118 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6119 if (op == glslang::EOpMinInvocationsNonUniform ||
6120 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6121 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006122 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006123 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006124 else {
6125 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006126 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006127 else
Rex Xu51596642016-09-21 18:56:12 +08006128 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006129 }
6130 }
Rex Xu430ef402016-10-14 17:22:23 +08006131 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6132 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6133 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006134 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006135 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006136 else {
6137 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006138 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006139 else
Rex Xu51596642016-09-21 18:56:12 +08006140 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006141 }
6142 }
6143 else {
6144 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006145 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006146 else
Rex Xu51596642016-09-21 18:56:12 +08006147 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006148 }
6149
Rex Xu2bbbe062016-08-23 15:41:05 +08006150 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006151 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006152
6153 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006154#endif
John Kessenich91cef522016-05-05 16:45:40 -06006155 default:
6156 logger->missingFunctionality("invocation operation");
6157 return spv::NoResult;
6158 }
Rex Xu51596642016-09-21 18:56:12 +08006159
6160 assert(opCode != spv::OpNop);
6161 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006162}
6163
Rex Xu2bbbe062016-08-23 15:41:05 +08006164// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006165spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6166 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006167{
Rex Xub7072052016-09-26 15:53:40 +08006168#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006169 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6170 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006171 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006172 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006173 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6174 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6175 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006176#else
6177 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6178 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006179 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6180 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006181#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006182
6183 // Handle group invocation operations scalar by scalar.
6184 // The result type is the same type as the original type.
6185 // The algorithm is to:
6186 // - break the vector into scalars
6187 // - apply the operation to each scalar
6188 // - make a vector out the scalar results
6189
6190 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006191 int numComponents = builder.getNumComponents(operands[0]);
6192 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006193 std::vector<spv::Id> results;
6194
6195 // do each scalar op
6196 for (int comp = 0; comp < numComponents; ++comp) {
6197 std::vector<unsigned int> indexes;
6198 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006199 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6200 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006201 if (op == spv::OpSubgroupReadInvocationKHR) {
6202 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006203 spv::IdImmediate operand = { true, operands[1] };
6204 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006205 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006206 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6207 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006208 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006209 spv::IdImmediate operand = { true, operands[1] };
6210 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006211 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006212 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6213 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006214 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006215 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006216 spvGroupOperands.push_back(scalar);
6217 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006218
Rex Xub7072052016-09-26 15:53:40 +08006219 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006220 }
6221
6222 // put the pieces together
6223 return builder.createCompositeConstruct(typeId, results);
6224}
Rex Xu2bbbe062016-08-23 15:41:05 +08006225
John Kessenich66011cb2018-03-06 16:12:04 -07006226// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006227spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6228 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006229{
6230 // Add the required capabilities.
6231 switch (op) {
6232 case glslang::EOpSubgroupElect:
6233 builder.addCapability(spv::CapabilityGroupNonUniform);
6234 break;
6235 case glslang::EOpSubgroupAll:
6236 case glslang::EOpSubgroupAny:
6237 case glslang::EOpSubgroupAllEqual:
6238 builder.addCapability(spv::CapabilityGroupNonUniform);
6239 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6240 break;
6241 case glslang::EOpSubgroupBroadcast:
6242 case glslang::EOpSubgroupBroadcastFirst:
6243 case glslang::EOpSubgroupBallot:
6244 case glslang::EOpSubgroupInverseBallot:
6245 case glslang::EOpSubgroupBallotBitExtract:
6246 case glslang::EOpSubgroupBallotBitCount:
6247 case glslang::EOpSubgroupBallotInclusiveBitCount:
6248 case glslang::EOpSubgroupBallotExclusiveBitCount:
6249 case glslang::EOpSubgroupBallotFindLSB:
6250 case glslang::EOpSubgroupBallotFindMSB:
6251 builder.addCapability(spv::CapabilityGroupNonUniform);
6252 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6253 break;
6254 case glslang::EOpSubgroupShuffle:
6255 case glslang::EOpSubgroupShuffleXor:
6256 builder.addCapability(spv::CapabilityGroupNonUniform);
6257 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6258 break;
6259 case glslang::EOpSubgroupShuffleUp:
6260 case glslang::EOpSubgroupShuffleDown:
6261 builder.addCapability(spv::CapabilityGroupNonUniform);
6262 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6263 break;
6264 case glslang::EOpSubgroupAdd:
6265 case glslang::EOpSubgroupMul:
6266 case glslang::EOpSubgroupMin:
6267 case glslang::EOpSubgroupMax:
6268 case glslang::EOpSubgroupAnd:
6269 case glslang::EOpSubgroupOr:
6270 case glslang::EOpSubgroupXor:
6271 case glslang::EOpSubgroupInclusiveAdd:
6272 case glslang::EOpSubgroupInclusiveMul:
6273 case glslang::EOpSubgroupInclusiveMin:
6274 case glslang::EOpSubgroupInclusiveMax:
6275 case glslang::EOpSubgroupInclusiveAnd:
6276 case glslang::EOpSubgroupInclusiveOr:
6277 case glslang::EOpSubgroupInclusiveXor:
6278 case glslang::EOpSubgroupExclusiveAdd:
6279 case glslang::EOpSubgroupExclusiveMul:
6280 case glslang::EOpSubgroupExclusiveMin:
6281 case glslang::EOpSubgroupExclusiveMax:
6282 case glslang::EOpSubgroupExclusiveAnd:
6283 case glslang::EOpSubgroupExclusiveOr:
6284 case glslang::EOpSubgroupExclusiveXor:
6285 builder.addCapability(spv::CapabilityGroupNonUniform);
6286 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6287 break;
6288 case glslang::EOpSubgroupClusteredAdd:
6289 case glslang::EOpSubgroupClusteredMul:
6290 case glslang::EOpSubgroupClusteredMin:
6291 case glslang::EOpSubgroupClusteredMax:
6292 case glslang::EOpSubgroupClusteredAnd:
6293 case glslang::EOpSubgroupClusteredOr:
6294 case glslang::EOpSubgroupClusteredXor:
6295 builder.addCapability(spv::CapabilityGroupNonUniform);
6296 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6297 break;
6298 case glslang::EOpSubgroupQuadBroadcast:
6299 case glslang::EOpSubgroupQuadSwapHorizontal:
6300 case glslang::EOpSubgroupQuadSwapVertical:
6301 case glslang::EOpSubgroupQuadSwapDiagonal:
6302 builder.addCapability(spv::CapabilityGroupNonUniform);
6303 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6304 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006305#ifdef NV_EXTENSIONS
6306 case glslang::EOpSubgroupPartitionedAdd:
6307 case glslang::EOpSubgroupPartitionedMul:
6308 case glslang::EOpSubgroupPartitionedMin:
6309 case glslang::EOpSubgroupPartitionedMax:
6310 case glslang::EOpSubgroupPartitionedAnd:
6311 case glslang::EOpSubgroupPartitionedOr:
6312 case glslang::EOpSubgroupPartitionedXor:
6313 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6314 case glslang::EOpSubgroupPartitionedInclusiveMul:
6315 case glslang::EOpSubgroupPartitionedInclusiveMin:
6316 case glslang::EOpSubgroupPartitionedInclusiveMax:
6317 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6318 case glslang::EOpSubgroupPartitionedInclusiveOr:
6319 case glslang::EOpSubgroupPartitionedInclusiveXor:
6320 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6321 case glslang::EOpSubgroupPartitionedExclusiveMul:
6322 case glslang::EOpSubgroupPartitionedExclusiveMin:
6323 case glslang::EOpSubgroupPartitionedExclusiveMax:
6324 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6325 case glslang::EOpSubgroupPartitionedExclusiveOr:
6326 case glslang::EOpSubgroupPartitionedExclusiveXor:
6327 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6328 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6329 break;
6330#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006331 default: assert(0 && "Unhandled subgroup operation!");
6332 }
6333
6334 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6335 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6336 const bool isBool = typeProxy == glslang::EbtBool;
6337
6338 spv::Op opCode = spv::OpNop;
6339
6340 // Figure out which opcode to use.
6341 switch (op) {
6342 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6343 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6344 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6345 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6346 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6347 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6348 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6349 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6350 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6351 case glslang::EOpSubgroupBallotBitCount:
6352 case glslang::EOpSubgroupBallotInclusiveBitCount:
6353 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6354 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6355 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6356 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6357 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6358 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6359 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6360 case glslang::EOpSubgroupAdd:
6361 case glslang::EOpSubgroupInclusiveAdd:
6362 case glslang::EOpSubgroupExclusiveAdd:
6363 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006364#ifdef NV_EXTENSIONS
6365 case glslang::EOpSubgroupPartitionedAdd:
6366 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6367 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6368#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006369 if (isFloat) {
6370 opCode = spv::OpGroupNonUniformFAdd;
6371 } else {
6372 opCode = spv::OpGroupNonUniformIAdd;
6373 }
6374 break;
6375 case glslang::EOpSubgroupMul:
6376 case glslang::EOpSubgroupInclusiveMul:
6377 case glslang::EOpSubgroupExclusiveMul:
6378 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006379#ifdef NV_EXTENSIONS
6380 case glslang::EOpSubgroupPartitionedMul:
6381 case glslang::EOpSubgroupPartitionedInclusiveMul:
6382 case glslang::EOpSubgroupPartitionedExclusiveMul:
6383#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006384 if (isFloat) {
6385 opCode = spv::OpGroupNonUniformFMul;
6386 } else {
6387 opCode = spv::OpGroupNonUniformIMul;
6388 }
6389 break;
6390 case glslang::EOpSubgroupMin:
6391 case glslang::EOpSubgroupInclusiveMin:
6392 case glslang::EOpSubgroupExclusiveMin:
6393 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006394#ifdef NV_EXTENSIONS
6395 case glslang::EOpSubgroupPartitionedMin:
6396 case glslang::EOpSubgroupPartitionedInclusiveMin:
6397 case glslang::EOpSubgroupPartitionedExclusiveMin:
6398#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006399 if (isFloat) {
6400 opCode = spv::OpGroupNonUniformFMin;
6401 } else if (isUnsigned) {
6402 opCode = spv::OpGroupNonUniformUMin;
6403 } else {
6404 opCode = spv::OpGroupNonUniformSMin;
6405 }
6406 break;
6407 case glslang::EOpSubgroupMax:
6408 case glslang::EOpSubgroupInclusiveMax:
6409 case glslang::EOpSubgroupExclusiveMax:
6410 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006411#ifdef NV_EXTENSIONS
6412 case glslang::EOpSubgroupPartitionedMax:
6413 case glslang::EOpSubgroupPartitionedInclusiveMax:
6414 case glslang::EOpSubgroupPartitionedExclusiveMax:
6415#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006416 if (isFloat) {
6417 opCode = spv::OpGroupNonUniformFMax;
6418 } else if (isUnsigned) {
6419 opCode = spv::OpGroupNonUniformUMax;
6420 } else {
6421 opCode = spv::OpGroupNonUniformSMax;
6422 }
6423 break;
6424 case glslang::EOpSubgroupAnd:
6425 case glslang::EOpSubgroupInclusiveAnd:
6426 case glslang::EOpSubgroupExclusiveAnd:
6427 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006428#ifdef NV_EXTENSIONS
6429 case glslang::EOpSubgroupPartitionedAnd:
6430 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6431 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6432#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006433 if (isBool) {
6434 opCode = spv::OpGroupNonUniformLogicalAnd;
6435 } else {
6436 opCode = spv::OpGroupNonUniformBitwiseAnd;
6437 }
6438 break;
6439 case glslang::EOpSubgroupOr:
6440 case glslang::EOpSubgroupInclusiveOr:
6441 case glslang::EOpSubgroupExclusiveOr:
6442 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006443#ifdef NV_EXTENSIONS
6444 case glslang::EOpSubgroupPartitionedOr:
6445 case glslang::EOpSubgroupPartitionedInclusiveOr:
6446 case glslang::EOpSubgroupPartitionedExclusiveOr:
6447#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006448 if (isBool) {
6449 opCode = spv::OpGroupNonUniformLogicalOr;
6450 } else {
6451 opCode = spv::OpGroupNonUniformBitwiseOr;
6452 }
6453 break;
6454 case glslang::EOpSubgroupXor:
6455 case glslang::EOpSubgroupInclusiveXor:
6456 case glslang::EOpSubgroupExclusiveXor:
6457 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006458#ifdef NV_EXTENSIONS
6459 case glslang::EOpSubgroupPartitionedXor:
6460 case glslang::EOpSubgroupPartitionedInclusiveXor:
6461 case glslang::EOpSubgroupPartitionedExclusiveXor:
6462#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006463 if (isBool) {
6464 opCode = spv::OpGroupNonUniformLogicalXor;
6465 } else {
6466 opCode = spv::OpGroupNonUniformBitwiseXor;
6467 }
6468 break;
6469 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6470 case glslang::EOpSubgroupQuadSwapHorizontal:
6471 case glslang::EOpSubgroupQuadSwapVertical:
6472 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6473 default: assert(0 && "Unhandled subgroup operation!");
6474 }
6475
John Kessenich149afc32018-08-14 13:31:43 -06006476 // get the right Group Operation
6477 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006478 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006479 default:
6480 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006481 case glslang::EOpSubgroupBallotBitCount:
6482 case glslang::EOpSubgroupAdd:
6483 case glslang::EOpSubgroupMul:
6484 case glslang::EOpSubgroupMin:
6485 case glslang::EOpSubgroupMax:
6486 case glslang::EOpSubgroupAnd:
6487 case glslang::EOpSubgroupOr:
6488 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006489 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006490 break;
6491 case glslang::EOpSubgroupBallotInclusiveBitCount:
6492 case glslang::EOpSubgroupInclusiveAdd:
6493 case glslang::EOpSubgroupInclusiveMul:
6494 case glslang::EOpSubgroupInclusiveMin:
6495 case glslang::EOpSubgroupInclusiveMax:
6496 case glslang::EOpSubgroupInclusiveAnd:
6497 case glslang::EOpSubgroupInclusiveOr:
6498 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006499 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006500 break;
6501 case glslang::EOpSubgroupBallotExclusiveBitCount:
6502 case glslang::EOpSubgroupExclusiveAdd:
6503 case glslang::EOpSubgroupExclusiveMul:
6504 case glslang::EOpSubgroupExclusiveMin:
6505 case glslang::EOpSubgroupExclusiveMax:
6506 case glslang::EOpSubgroupExclusiveAnd:
6507 case glslang::EOpSubgroupExclusiveOr:
6508 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006509 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006510 break;
6511 case glslang::EOpSubgroupClusteredAdd:
6512 case glslang::EOpSubgroupClusteredMul:
6513 case glslang::EOpSubgroupClusteredMin:
6514 case glslang::EOpSubgroupClusteredMax:
6515 case glslang::EOpSubgroupClusteredAnd:
6516 case glslang::EOpSubgroupClusteredOr:
6517 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006518 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006519 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006520#ifdef NV_EXTENSIONS
6521 case glslang::EOpSubgroupPartitionedAdd:
6522 case glslang::EOpSubgroupPartitionedMul:
6523 case glslang::EOpSubgroupPartitionedMin:
6524 case glslang::EOpSubgroupPartitionedMax:
6525 case glslang::EOpSubgroupPartitionedAnd:
6526 case glslang::EOpSubgroupPartitionedOr:
6527 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006528 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006529 break;
6530 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6531 case glslang::EOpSubgroupPartitionedInclusiveMul:
6532 case glslang::EOpSubgroupPartitionedInclusiveMin:
6533 case glslang::EOpSubgroupPartitionedInclusiveMax:
6534 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6535 case glslang::EOpSubgroupPartitionedInclusiveOr:
6536 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006537 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006538 break;
6539 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6540 case glslang::EOpSubgroupPartitionedExclusiveMul:
6541 case glslang::EOpSubgroupPartitionedExclusiveMin:
6542 case glslang::EOpSubgroupPartitionedExclusiveMax:
6543 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6544 case glslang::EOpSubgroupPartitionedExclusiveOr:
6545 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006546 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006547 break;
6548#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006549 }
6550
John Kessenich149afc32018-08-14 13:31:43 -06006551 // build the instruction
6552 std::vector<spv::IdImmediate> spvGroupOperands;
6553
6554 // Every operation begins with the Execution Scope operand.
6555 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6556 spvGroupOperands.push_back(executionScope);
6557
6558 // Next, for all operations that use a Group Operation, push that as an operand.
6559 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006560 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006561 spvGroupOperands.push_back(groupOperand);
6562 }
6563
John Kessenich66011cb2018-03-06 16:12:04 -07006564 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006565 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6566 spv::IdImmediate operand = { true, *opIt };
6567 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006568 }
6569
6570 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006571 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006572 switch (op) {
6573 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006574 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6575 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6576 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6577 }
6578 if (directionId != spv::NoResult) {
6579 spv::IdImmediate direction = { true, directionId };
6580 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006581 }
6582
6583 return builder.createOp(opCode, typeId, spvGroupOperands);
6584}
6585
John Kessenich5e4b1242015-08-06 22:53:06 -06006586spv::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 -06006587{
John Kessenich66011cb2018-03-06 16:12:04 -07006588 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6589 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006590
John Kessenich140f3df2015-06-26 16:58:36 -06006591 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006592 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006593 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006594 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006595 spv::Id typeId0 = 0;
6596 if (consumedOperands > 0)
6597 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006598 spv::Id typeId1 = 0;
6599 if (consumedOperands > 1)
6600 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006601 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006602
6603 switch (op) {
6604 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006605 if (isFloat)
6606 libCall = spv::GLSLstd450FMin;
6607 else if (isUnsigned)
6608 libCall = spv::GLSLstd450UMin;
6609 else
6610 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006611 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006612 break;
6613 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006614 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006615 break;
6616 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006617 if (isFloat)
6618 libCall = spv::GLSLstd450FMax;
6619 else if (isUnsigned)
6620 libCall = spv::GLSLstd450UMax;
6621 else
6622 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006623 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006624 break;
6625 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006626 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006627 break;
6628 case glslang::EOpDot:
6629 opCode = spv::OpDot;
6630 break;
6631 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006632 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006633 break;
6634
6635 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006636 if (isFloat)
6637 libCall = spv::GLSLstd450FClamp;
6638 else if (isUnsigned)
6639 libCall = spv::GLSLstd450UClamp;
6640 else
6641 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006642 builder.promoteScalar(precision, operands.front(), operands[1]);
6643 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006644 break;
6645 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006646 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6647 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006648 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006649 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006650 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006651 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006652 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006653 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006654 break;
6655 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006656 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006657 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006658 break;
6659 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006660 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006661 builder.promoteScalar(precision, operands[0], operands[2]);
6662 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006663 break;
6664
6665 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006666 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006667 break;
6668 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006669 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006670 break;
6671 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006672 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006673 break;
6674 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006675 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006676 break;
6677 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006678 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006679 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006680 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006681#ifdef AMD_EXTENSIONS
6682 if (typeProxy == glslang::EbtFloat16)
6683 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6684#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006685 libCall = spv::GLSLstd450InterpolateAtSample;
6686 break;
6687 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006688#ifdef AMD_EXTENSIONS
6689 if (typeProxy == glslang::EbtFloat16)
6690 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6691#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006692 libCall = spv::GLSLstd450InterpolateAtOffset;
6693 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006694 case glslang::EOpAddCarry:
6695 opCode = spv::OpIAddCarry;
6696 typeId = builder.makeStructResultType(typeId0, typeId0);
6697 consumedOperands = 2;
6698 break;
6699 case glslang::EOpSubBorrow:
6700 opCode = spv::OpISubBorrow;
6701 typeId = builder.makeStructResultType(typeId0, typeId0);
6702 consumedOperands = 2;
6703 break;
6704 case glslang::EOpUMulExtended:
6705 opCode = spv::OpUMulExtended;
6706 typeId = builder.makeStructResultType(typeId0, typeId0);
6707 consumedOperands = 2;
6708 break;
6709 case glslang::EOpIMulExtended:
6710 opCode = spv::OpSMulExtended;
6711 typeId = builder.makeStructResultType(typeId0, typeId0);
6712 consumedOperands = 2;
6713 break;
6714 case glslang::EOpBitfieldExtract:
6715 if (isUnsigned)
6716 opCode = spv::OpBitFieldUExtract;
6717 else
6718 opCode = spv::OpBitFieldSExtract;
6719 break;
6720 case glslang::EOpBitfieldInsert:
6721 opCode = spv::OpBitFieldInsert;
6722 break;
6723
6724 case glslang::EOpFma:
6725 libCall = spv::GLSLstd450Fma;
6726 break;
6727 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006728 {
6729 libCall = spv::GLSLstd450FrexpStruct;
6730 assert(builder.isPointerType(typeId1));
6731 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006732 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006733#ifdef AMD_EXTENSIONS
6734 if (width == 16)
6735 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6736 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6737#endif
Rex Xu470026f2017-03-29 17:12:40 +08006738 if (builder.getNumComponents(operands[0]) == 1)
6739 frexpIntType = builder.makeIntegerType(width, true);
6740 else
6741 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6742 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6743 consumedOperands = 1;
6744 }
John Kessenich55e7d112015-11-15 21:33:39 -07006745 break;
6746 case glslang::EOpLdexp:
6747 libCall = spv::GLSLstd450Ldexp;
6748 break;
6749
Rex Xu574ab042016-04-14 16:53:07 +08006750 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006751 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006752
John Kessenich66011cb2018-03-06 16:12:04 -07006753 case glslang::EOpSubgroupBroadcast:
6754 case glslang::EOpSubgroupBallotBitExtract:
6755 case glslang::EOpSubgroupShuffle:
6756 case glslang::EOpSubgroupShuffleXor:
6757 case glslang::EOpSubgroupShuffleUp:
6758 case glslang::EOpSubgroupShuffleDown:
6759 case glslang::EOpSubgroupClusteredAdd:
6760 case glslang::EOpSubgroupClusteredMul:
6761 case glslang::EOpSubgroupClusteredMin:
6762 case glslang::EOpSubgroupClusteredMax:
6763 case glslang::EOpSubgroupClusteredAnd:
6764 case glslang::EOpSubgroupClusteredOr:
6765 case glslang::EOpSubgroupClusteredXor:
6766 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006767#ifdef NV_EXTENSIONS
6768 case glslang::EOpSubgroupPartitionedAdd:
6769 case glslang::EOpSubgroupPartitionedMul:
6770 case glslang::EOpSubgroupPartitionedMin:
6771 case glslang::EOpSubgroupPartitionedMax:
6772 case glslang::EOpSubgroupPartitionedAnd:
6773 case glslang::EOpSubgroupPartitionedOr:
6774 case glslang::EOpSubgroupPartitionedXor:
6775 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6776 case glslang::EOpSubgroupPartitionedInclusiveMul:
6777 case glslang::EOpSubgroupPartitionedInclusiveMin:
6778 case glslang::EOpSubgroupPartitionedInclusiveMax:
6779 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6780 case glslang::EOpSubgroupPartitionedInclusiveOr:
6781 case glslang::EOpSubgroupPartitionedInclusiveXor:
6782 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6783 case glslang::EOpSubgroupPartitionedExclusiveMul:
6784 case glslang::EOpSubgroupPartitionedExclusiveMin:
6785 case glslang::EOpSubgroupPartitionedExclusiveMax:
6786 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6787 case glslang::EOpSubgroupPartitionedExclusiveOr:
6788 case glslang::EOpSubgroupPartitionedExclusiveXor:
6789#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006790 return createSubgroupOperation(op, typeId, operands, typeProxy);
6791
Rex Xu9d93a232016-05-05 12:30:44 +08006792#ifdef AMD_EXTENSIONS
6793 case glslang::EOpSwizzleInvocations:
6794 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6795 libCall = spv::SwizzleInvocationsAMD;
6796 break;
6797 case glslang::EOpSwizzleInvocationsMasked:
6798 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6799 libCall = spv::SwizzleInvocationsMaskedAMD;
6800 break;
6801 case glslang::EOpWriteInvocation:
6802 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6803 libCall = spv::WriteInvocationAMD;
6804 break;
6805
6806 case glslang::EOpMin3:
6807 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6808 if (isFloat)
6809 libCall = spv::FMin3AMD;
6810 else {
6811 if (isUnsigned)
6812 libCall = spv::UMin3AMD;
6813 else
6814 libCall = spv::SMin3AMD;
6815 }
6816 break;
6817 case glslang::EOpMax3:
6818 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6819 if (isFloat)
6820 libCall = spv::FMax3AMD;
6821 else {
6822 if (isUnsigned)
6823 libCall = spv::UMax3AMD;
6824 else
6825 libCall = spv::SMax3AMD;
6826 }
6827 break;
6828 case glslang::EOpMid3:
6829 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6830 if (isFloat)
6831 libCall = spv::FMid3AMD;
6832 else {
6833 if (isUnsigned)
6834 libCall = spv::UMid3AMD;
6835 else
6836 libCall = spv::SMid3AMD;
6837 }
6838 break;
6839
6840 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006841 if (typeProxy == glslang::EbtFloat16)
6842 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08006843 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6844 libCall = spv::InterpolateAtVertexAMD;
6845 break;
6846#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05006847 case glslang::EOpBarrier:
6848 {
6849 // This is for the extended controlBarrier function, with four operands.
6850 // The unextended barrier() goes through createNoArgOperation.
6851 assert(operands.size() == 4);
6852 unsigned int executionScope = builder.getConstantScalar(operands[0]);
6853 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
6854 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
6855 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6856 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6857 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6858 }
6859 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
6860 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6861 }
6862 return 0;
6863 }
6864 break;
6865 case glslang::EOpMemoryBarrier:
6866 {
6867 // This is for the extended memoryBarrier function, with three operands.
6868 // The unextended memoryBarrier() goes through createNoArgOperation.
6869 assert(operands.size() == 3);
6870 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
6871 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
6872 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6873 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6874 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6875 }
6876 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
6877 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6878 }
6879 return 0;
6880 }
6881 break;
Chao Chen3c366992018-09-19 11:41:59 -07006882
6883#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07006884 case glslang::EOpReportIntersectionNV:
6885 {
6886 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07006887 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07006888 }
6889 break;
6890 case glslang::EOpTraceNV:
6891 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07006892 builder.createNoResultOp(spv::OpTraceNV, operands);
6893 return 0;
6894 }
6895 break;
6896 case glslang::EOpExecuteCallableNV:
6897 {
6898 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07006899 return 0;
6900 }
6901 break;
Chao Chen3c366992018-09-19 11:41:59 -07006902 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
6903 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
6904 return 0;
6905#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006906 default:
6907 return 0;
6908 }
6909
6910 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006911 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006912 // Use an extended instruction from the standard library.
6913 // Construct the call arguments, without modifying the original operands vector.
6914 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6915 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006916 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01006917 } else if (opCode == spv::OpDot && !isFloat) {
6918 // int dot(int, int)
6919 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
6920 const int componentCount = builder.getNumComponents(operands[0]);
6921 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
6922 builder.setPrecision(mulOp, precision);
6923 id = builder.createCompositeExtract(mulOp, typeId, 0);
6924 for (int i = 1; i < componentCount; ++i) {
6925 builder.setPrecision(id, precision);
6926 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
6927 }
John Kessenich2359bd02015-12-06 19:29:11 -07006928 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006929 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006930 case 0:
6931 // should all be handled by visitAggregate and createNoArgOperation
6932 assert(0);
6933 return 0;
6934 case 1:
6935 // should all be handled by createUnaryOperation
6936 assert(0);
6937 return 0;
6938 case 2:
6939 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6940 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006941 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006942 // anything 3 or over doesn't have l-value operands, so all should be consumed
6943 assert(consumedOperands == operands.size());
6944 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006945 break;
6946 }
6947 }
6948
John Kessenich55e7d112015-11-15 21:33:39 -07006949 // Decode the return types that were structures
6950 switch (op) {
6951 case glslang::EOpAddCarry:
6952 case glslang::EOpSubBorrow:
6953 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6954 id = builder.createCompositeExtract(id, typeId0, 0);
6955 break;
6956 case glslang::EOpUMulExtended:
6957 case glslang::EOpIMulExtended:
6958 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6959 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6960 break;
6961 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006962 {
6963 assert(operands.size() == 2);
6964 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6965 // "exp" is floating-point type (from HLSL intrinsic)
6966 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6967 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6968 builder.createStore(member1, operands[1]);
6969 } else
6970 // "exp" is integer type (from GLSL built-in function)
6971 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6972 id = builder.createCompositeExtract(id, typeId0, 0);
6973 }
John Kessenich55e7d112015-11-15 21:33:39 -07006974 break;
6975 default:
6976 break;
6977 }
6978
John Kessenich32cfd492016-02-02 12:37:46 -07006979 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006980}
6981
Rex Xu9d93a232016-05-05 12:30:44 +08006982// Intrinsics with no arguments (or no return value, and no precision).
6983spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006984{
Jeff Bolz36831c92018-09-05 10:11:41 -05006985 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
6986 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06006987
6988 switch (op) {
6989 case glslang::EOpEmitVertex:
6990 builder.createNoResultOp(spv::OpEmitVertex);
6991 return 0;
6992 case glslang::EOpEndPrimitive:
6993 builder.createNoResultOp(spv::OpEndPrimitive);
6994 return 0;
6995 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006996 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006997 if (glslangIntermediate->usingVulkanMemoryModel()) {
6998 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6999 spv::MemorySemanticsOutputMemoryKHRMask |
7000 spv::MemorySemanticsAcquireReleaseMask);
7001 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7002 } else {
7003 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7004 }
John Kessenich82979362017-12-11 04:02:24 -07007005 } else {
7006 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7007 spv::MemorySemanticsWorkgroupMemoryMask |
7008 spv::MemorySemanticsAcquireReleaseMask);
7009 }
John Kessenich140f3df2015-06-26 16:58:36 -06007010 return 0;
7011 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007012 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7013 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007014 return 0;
7015 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007016 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7017 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007018 return 0;
7019 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007020 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7021 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007022 return 0;
7023 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007024 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7025 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007026 return 0;
7027 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007028 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7029 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007030 return 0;
7031 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007032 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7033 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007034 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007035 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007036 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007037 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007038 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007039 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007040 case glslang::EOpDeviceMemoryBarrier:
7041 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7042 spv::MemorySemanticsImageMemoryMask |
7043 spv::MemorySemanticsAcquireReleaseMask);
7044 return 0;
7045 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7046 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7047 spv::MemorySemanticsImageMemoryMask |
7048 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007049 return 0;
7050 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007051 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7052 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007053 return 0;
7054 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007055 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7056 spv::MemorySemanticsWorkgroupMemoryMask |
7057 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007058 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007059 case glslang::EOpSubgroupBarrier:
7060 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7061 spv::MemorySemanticsAcquireReleaseMask);
7062 return spv::NoResult;
7063 case glslang::EOpSubgroupMemoryBarrier:
7064 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7065 spv::MemorySemanticsAcquireReleaseMask);
7066 return spv::NoResult;
7067 case glslang::EOpSubgroupMemoryBarrierBuffer:
7068 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7069 spv::MemorySemanticsAcquireReleaseMask);
7070 return spv::NoResult;
7071 case glslang::EOpSubgroupMemoryBarrierImage:
7072 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7073 spv::MemorySemanticsAcquireReleaseMask);
7074 return spv::NoResult;
7075 case glslang::EOpSubgroupMemoryBarrierShared:
7076 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7077 spv::MemorySemanticsAcquireReleaseMask);
7078 return spv::NoResult;
7079 case glslang::EOpSubgroupElect: {
7080 std::vector<spv::Id> operands;
7081 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7082 }
Rex Xu9d93a232016-05-05 12:30:44 +08007083#ifdef AMD_EXTENSIONS
7084 case glslang::EOpTime:
7085 {
7086 std::vector<spv::Id> args; // Dummy arguments
7087 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7088 return builder.setPrecision(id, precision);
7089 }
7090#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007091#ifdef NV_EXTENSIONS
7092 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007093 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007094 return 0;
7095 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007096 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007097 return 0;
7098#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007099 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007100 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007101 return 0;
7102 }
7103}
7104
7105spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7106{
John Kessenich2f273362015-07-18 22:34:27 -06007107 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007108 spv::Id id;
7109 if (symbolValues.end() != iter) {
7110 id = iter->second;
7111 return id;
7112 }
7113
7114 // it was not found, create it
7115 id = createSpvVariable(symbol);
7116 symbolValues[symbol->getId()] = id;
7117
Rex Xuc884b4a2016-06-29 15:03:44 +08007118 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007119 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7120 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7121 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007122#ifdef NV_EXTENSIONS
7123 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7124#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007125 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007126 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007127 if (symbol->getQualifier().hasIndex())
7128 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7129 if (symbol->getQualifier().hasComponent())
7130 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007131 // atomic counters use this:
7132 if (symbol->getQualifier().hasOffset())
7133 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007134 }
7135
scygan2c864272016-05-18 18:09:17 +02007136 if (symbol->getQualifier().hasLocation())
7137 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007138 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007139 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007140 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007141 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007142 }
John Kessenich140f3df2015-06-26 16:58:36 -06007143 if (symbol->getQualifier().hasSet())
7144 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007145 else if (IsDescriptorResource(symbol->getType())) {
7146 // default to 0
7147 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7148 }
John Kessenich140f3df2015-06-26 16:58:36 -06007149 if (symbol->getQualifier().hasBinding())
7150 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07007151 if (symbol->getQualifier().hasAttachment())
7152 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007153 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007154 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06007155 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06007156 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07007157 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007158 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007159 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7160 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7161 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7162 }
7163 if (symbol->getQualifier().hasXfbOffset())
7164 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007165 }
7166
Rex Xu1da878f2016-02-21 20:59:01 +08007167 if (symbol->getType().isImage()) {
7168 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007169 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007170 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007171 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007172 }
7173
John Kessenich140f3df2015-06-26 16:58:36 -06007174 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007175 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007176 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007177 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007178
John Kessenich5611c6d2018-04-05 11:25:02 -06007179 // nonuniform
7180 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7181
John Kessenichecba76f2017-01-06 00:34:48 -07007182#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007183 if (builtIn == spv::BuiltInSampleMask) {
7184 spv::Decoration decoration;
7185 // GL_NV_sample_mask_override_coverage extension
7186 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007187 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007188 else
7189 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007190 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007191 if (decoration != spv::DecorationMax) {
7192 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7193 }
7194 }
chaoc771d89f2017-01-13 01:10:53 -08007195 else if (builtIn == spv::BuiltInLayer) {
7196 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007197 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007198 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007199 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7200 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7201 }
John Kessenichb41bff62017-08-11 13:07:17 -06007202 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007203 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7204 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007205 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7206 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7207 }
7208 }
7209
chaoc6e5acae2016-12-20 13:28:52 -08007210 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007211 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007212 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007213 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7214 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007215 if (symbol->getQualifier().pervertexNV) {
7216 builder.addDecoration(id, spv::DecorationPerVertexNV);
7217 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7218 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7219 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007220#endif
7221
John Kessenich5d610ee2018-03-07 18:05:55 -07007222 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7223 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7224 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7225 symbol->getType().getQualifier().semanticName);
7226 }
7227
John Kessenich140f3df2015-06-26 16:58:36 -06007228 return id;
7229}
7230
Chao Chen3c366992018-09-19 11:41:59 -07007231#ifdef NV_EXTENSIONS
7232// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7233void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7234{
7235 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007236 if (qualifier.perPrimitiveNV) {
7237 // Need to add capability/extension for fragment shader.
7238 // Mesh shader already adds this by default.
7239 if (glslangIntermediate->getStage() == EShLangFragment) {
7240 builder.addCapability(spv::CapabilityMeshShadingNV);
7241 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7242 }
Chao Chen3c366992018-09-19 11:41:59 -07007243 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007244 }
Chao Chen3c366992018-09-19 11:41:59 -07007245 if (qualifier.perViewNV)
7246 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7247 if (qualifier.perTaskNV)
7248 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7249 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007250 if (qualifier.perPrimitiveNV) {
7251 // Need to add capability/extension for fragment shader.
7252 // Mesh shader already adds this by default.
7253 if (glslangIntermediate->getStage() == EShLangFragment) {
7254 builder.addCapability(spv::CapabilityMeshShadingNV);
7255 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7256 }
Chao Chen3c366992018-09-19 11:41:59 -07007257 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007258 }
Chao Chen3c366992018-09-19 11:41:59 -07007259 if (qualifier.perViewNV)
7260 builder.addDecoration(id, spv::DecorationPerViewNV);
7261 if (qualifier.perTaskNV)
7262 builder.addDecoration(id, spv::DecorationPerTaskNV);
7263 }
7264}
7265#endif
7266
John Kessenich55e7d112015-11-15 21:33:39 -07007267// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007268// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007269//
7270// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7271//
7272// Recursively walk the nodes. The nodes form a tree whose leaves are
7273// regular constants, which themselves are trees that createSpvConstant()
7274// recursively walks. So, this function walks the "top" of the tree:
7275// - emit specialization constant-building instructions for specConstant
7276// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007277spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007278{
John Kessenich7cc0e282016-03-20 00:46:02 -06007279 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007280
qining4f4bb812016-04-03 23:55:17 -04007281 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007282 if (! node.getQualifier().specConstant) {
7283 // hand off to the non-spec-constant path
7284 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7285 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007286 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007287 nextConst, false);
7288 }
7289
7290 // We now know we have a specialization constant to build
7291
John Kessenichd94c0032016-05-30 19:29:40 -06007292 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007293 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7294 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7295 std::vector<spv::Id> dimConstId;
7296 for (int dim = 0; dim < 3; ++dim) {
7297 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7298 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007299 if (specConst) {
7300 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7301 glslangIntermediate->getLocalSizeSpecId(dim));
7302 }
qining4f4bb812016-04-03 23:55:17 -04007303 }
7304 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7305 }
7306
7307 // An AST node labelled as specialization constant should be a symbol node.
7308 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7309 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007310 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007311 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007312 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7313 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7314 // will set the builder into spec constant op instruction generating mode.
7315 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007316 result = accessChainLoad(sub_tree->getType());
7317 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007318 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007319 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007320 } else {
7321 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007322 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007323 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007324 builder.addName(result, sn->getName().c_str());
7325 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007326 }
qining4f4bb812016-04-03 23:55:17 -04007327
7328 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7329 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007330 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007331 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007332}
7333
John Kessenich140f3df2015-06-26 16:58:36 -06007334// Use 'consts' as the flattened glslang source of scalar constants to recursively
7335// build the aggregate SPIR-V constant.
7336//
7337// If there are not enough elements present in 'consts', 0 will be substituted;
7338// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7339//
qining08408382016-03-21 09:51:37 -04007340spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007341{
7342 // vector of constants for SPIR-V
7343 std::vector<spv::Id> spvConsts;
7344
7345 // Type is used for struct and array constants
7346 spv::Id typeId = convertGlslangToSpvType(glslangType);
7347
7348 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007349 glslang::TType elementType(glslangType, 0);
7350 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007351 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007352 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007353 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007354 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007355 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007356 } else if (glslangType.getStruct()) {
7357 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7358 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007359 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007360 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007361 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7362 bool zero = nextConst >= consts.size();
7363 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007364 case glslang::EbtInt8:
7365 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7366 break;
7367 case glslang::EbtUint8:
7368 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7369 break;
7370 case glslang::EbtInt16:
7371 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7372 break;
7373 case glslang::EbtUint16:
7374 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7375 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007376 case glslang::EbtInt:
7377 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7378 break;
7379 case glslang::EbtUint:
7380 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7381 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007382 case glslang::EbtInt64:
7383 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7384 break;
7385 case glslang::EbtUint64:
7386 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7387 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007388 case glslang::EbtFloat:
7389 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7390 break;
7391 case glslang::EbtDouble:
7392 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7393 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007394 case glslang::EbtFloat16:
7395 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7396 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007397 case glslang::EbtBool:
7398 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7399 break;
7400 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007401 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007402 break;
7403 }
7404 ++nextConst;
7405 }
7406 } else {
7407 // we have a non-aggregate (scalar) constant
7408 bool zero = nextConst >= consts.size();
7409 spv::Id scalar = 0;
7410 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007411 case glslang::EbtInt8:
7412 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7413 break;
7414 case glslang::EbtUint8:
7415 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7416 break;
7417 case glslang::EbtInt16:
7418 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7419 break;
7420 case glslang::EbtUint16:
7421 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7422 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007423 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007424 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007425 break;
7426 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007427 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007428 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007429 case glslang::EbtInt64:
7430 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7431 break;
7432 case glslang::EbtUint64:
7433 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7434 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007435 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007436 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007437 break;
7438 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007439 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007440 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007441 case glslang::EbtFloat16:
7442 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7443 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007444 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007445 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007446 break;
7447 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007448 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007449 break;
7450 }
7451 ++nextConst;
7452 return scalar;
7453 }
7454
7455 return builder.makeCompositeConstant(typeId, spvConsts);
7456}
7457
John Kessenich7c1aa102015-10-15 13:29:11 -06007458// Return true if the node is a constant or symbol whose reading has no
7459// non-trivial observable cost or effect.
7460bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7461{
7462 // don't know what this is
7463 if (node == nullptr)
7464 return false;
7465
7466 // a constant is safe
7467 if (node->getAsConstantUnion() != nullptr)
7468 return true;
7469
7470 // not a symbol means non-trivial
7471 if (node->getAsSymbolNode() == nullptr)
7472 return false;
7473
7474 // a symbol, depends on what's being read
7475 switch (node->getType().getQualifier().storage) {
7476 case glslang::EvqTemporary:
7477 case glslang::EvqGlobal:
7478 case glslang::EvqIn:
7479 case glslang::EvqInOut:
7480 case glslang::EvqConst:
7481 case glslang::EvqConstReadOnly:
7482 case glslang::EvqUniform:
7483 return true;
7484 default:
7485 return false;
7486 }
qining25262b32016-05-06 17:25:16 -04007487}
John Kessenich7c1aa102015-10-15 13:29:11 -06007488
7489// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007490// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007491// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007492// Return true if trivial.
7493bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7494{
7495 if (node == nullptr)
7496 return false;
7497
John Kessenich84cc15f2017-05-24 16:44:47 -06007498 // count non scalars as trivial, as well as anything coming from HLSL
7499 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007500 return true;
7501
John Kessenich7c1aa102015-10-15 13:29:11 -06007502 // symbols and constants are trivial
7503 if (isTrivialLeaf(node))
7504 return true;
7505
7506 // otherwise, it needs to be a simple operation or one or two leaf nodes
7507
7508 // not a simple operation
7509 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7510 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7511 if (binaryNode == nullptr && unaryNode == nullptr)
7512 return false;
7513
7514 // not on leaf nodes
7515 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7516 return false;
7517
7518 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7519 return false;
7520 }
7521
7522 switch (node->getAsOperator()->getOp()) {
7523 case glslang::EOpLogicalNot:
7524 case glslang::EOpConvIntToBool:
7525 case glslang::EOpConvUintToBool:
7526 case glslang::EOpConvFloatToBool:
7527 case glslang::EOpConvDoubleToBool:
7528 case glslang::EOpEqual:
7529 case glslang::EOpNotEqual:
7530 case glslang::EOpLessThan:
7531 case glslang::EOpGreaterThan:
7532 case glslang::EOpLessThanEqual:
7533 case glslang::EOpGreaterThanEqual:
7534 case glslang::EOpIndexDirect:
7535 case glslang::EOpIndexDirectStruct:
7536 case glslang::EOpLogicalXor:
7537 case glslang::EOpAny:
7538 case glslang::EOpAll:
7539 return true;
7540 default:
7541 return false;
7542 }
7543}
7544
7545// Emit short-circuiting code, where 'right' is never evaluated unless
7546// the left side is true (for &&) or false (for ||).
7547spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7548{
7549 spv::Id boolTypeId = builder.makeBoolType();
7550
7551 // emit left operand
7552 builder.clearAccessChain();
7553 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007554 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007555
7556 // Operands to accumulate OpPhi operands
7557 std::vector<spv::Id> phiOperands;
7558 // accumulate left operand's phi information
7559 phiOperands.push_back(leftId);
7560 phiOperands.push_back(builder.getBuildPoint()->getId());
7561
7562 // Make the two kinds of operation symmetric with a "!"
7563 // || => emit "if (! left) result = right"
7564 // && => emit "if ( left) result = right"
7565 //
7566 // TODO: this runtime "not" for || could be avoided by adding functionality
7567 // to 'builder' to have an "else" without an "then"
7568 if (op == glslang::EOpLogicalOr)
7569 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7570
7571 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007572 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007573
7574 // emit right operand as the "then" part of the "if"
7575 builder.clearAccessChain();
7576 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007577 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007578
7579 // accumulate left operand's phi information
7580 phiOperands.push_back(rightId);
7581 phiOperands.push_back(builder.getBuildPoint()->getId());
7582
7583 // finish the "if"
7584 ifBuilder.makeEndIf();
7585
7586 // phi together the two results
7587 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7588}
7589
Frank Henigman541f7bb2018-01-16 00:18:26 -05007590#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007591// Return type Id of the imported set of extended instructions corresponds to the name.
7592// Import this set if it has not been imported yet.
7593spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7594{
7595 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7596 return extBuiltinMap[name];
7597 else {
Rex Xu51596642016-09-21 18:56:12 +08007598 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007599 spv::Id extBuiltins = builder.import(name);
7600 extBuiltinMap[name] = extBuiltins;
7601 return extBuiltins;
7602 }
7603}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007604#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007605
John Kessenich140f3df2015-06-26 16:58:36 -06007606}; // end anonymous namespace
7607
7608namespace glslang {
7609
John Kessenich68d78fd2015-07-12 19:28:10 -06007610void GetSpirvVersion(std::string& version)
7611{
John Kessenich9e55f632015-07-15 10:03:39 -06007612 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007613 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007614 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007615 version = buf;
7616}
7617
John Kessenicha372a3e2017-11-02 22:32:14 -06007618// For low-order part of the generator's magic number. Bump up
7619// when there is a change in the style (e.g., if SSA form changes,
7620// or a different instruction sequence to do something gets used).
7621int GetSpirvGeneratorVersion()
7622{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007623 // return 1; // start
7624 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007625 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007626 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007627 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007628 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7629 // versions 4 and 6 each generate OpArrayLength as it has long been done
7630 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007631}
7632
John Kessenich140f3df2015-06-26 16:58:36 -06007633// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007634void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007635{
7636 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007637 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007638 if (out.fail())
7639 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007640 for (int i = 0; i < (int)spirv.size(); ++i) {
7641 unsigned int word = spirv[i];
7642 out.write((const char*)&word, 4);
7643 }
7644 out.close();
7645}
7646
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007647// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007648void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007649{
7650 std::ofstream out;
7651 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007652 if (out.fail())
7653 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007654 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007655 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007656 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007657 if (varName != nullptr) {
7658 out << "\t #pragma once" << std::endl;
7659 out << "const uint32_t " << varName << "[] = {" << std::endl;
7660 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007661 const int WORDS_PER_LINE = 8;
7662 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7663 out << "\t";
7664 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7665 const unsigned int word = spirv[i + j];
7666 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7667 if (i + j + 1 < (int)spirv.size()) {
7668 out << ",";
7669 }
7670 }
7671 out << std::endl;
7672 }
Flavio15017db2017-02-15 14:29:33 -08007673 if (varName != nullptr) {
7674 out << "};";
7675 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007676 out.close();
7677}
7678
John Kessenich140f3df2015-06-26 16:58:36 -06007679//
7680// Set up the glslang traversal
7681//
John Kessenich4e11b612018-08-30 16:56:59 -06007682void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007683{
Lei Zhang17535f72016-05-04 15:55:59 -04007684 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007685 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007686}
7687
John Kessenich4e11b612018-08-30 16:56:59 -06007688void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007689 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007690{
John Kessenich140f3df2015-06-26 16:58:36 -06007691 TIntermNode* root = intermediate.getTreeRoot();
7692
7693 if (root == 0)
7694 return;
7695
John Kessenich4e11b612018-08-30 16:56:59 -06007696 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007697 if (options == nullptr)
7698 options = &defaultOptions;
7699
John Kessenich4e11b612018-08-30 16:56:59 -06007700 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007701
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007702 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007703 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007704 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007705 it.dumpSpv(spirv);
7706
GregFfb03a552018-03-29 11:49:14 -06007707#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007708 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7709 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007710 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007711 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007712
John Kessenich4e11b612018-08-30 16:56:59 -06007713 if (options->validate)
7714 SpirvToolsValidate(intermediate, spirv, logger);
7715
John Kessenich717c80a2018-08-23 15:17:10 -06007716 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007717 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007718
GregFcd1f1692017-09-21 18:40:22 -06007719#endif
7720
John Kessenich4e11b612018-08-30 16:56:59 -06007721 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06007722}
7723
7724}; // end namespace glslang