blob: 5c00024c6914a47bbad6e2443135cf935886dde2 [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
Daniel Koch5154db52018-11-26 10:01:58 -0500836 case glslang::EbvFragSizeEXT:
837 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
838 builder.addCapability(spv::CapabilityFragmentDensityEXT);
839 return spv::BuiltInFragSizeEXT;
840
841 case glslang::EbvFragInvocationCountEXT:
842 builder.addExtension(spv::E_SPV_EXT_fragment_invocation_density);
843 builder.addCapability(spv::CapabilityFragmentDensityEXT);
844 return spv::BuiltInFragInvocationCountEXT;
845
chaoc771d89f2017-01-13 01:10:53 -0800846#ifdef NV_EXTENSIONS
847 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800848 if (!memberDeclaration) {
849 builder.addExtension(spv::E_SPV_NV_viewport_array2);
850 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
851 }
chaoc771d89f2017-01-13 01:10:53 -0800852 return spv::BuiltInViewportMaskNV;
853 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800854 if (!memberDeclaration) {
855 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
856 builder.addCapability(spv::CapabilityShaderStereoViewNV);
857 }
chaoc771d89f2017-01-13 01:10:53 -0800858 return spv::BuiltInSecondaryPositionNV;
859 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800860 if (!memberDeclaration) {
861 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
862 builder.addCapability(spv::CapabilityShaderStereoViewNV);
863 }
chaoc771d89f2017-01-13 01:10:53 -0800864 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800865 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800866 if (!memberDeclaration) {
867 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
868 builder.addCapability(spv::CapabilityPerViewAttributesNV);
869 }
chaocdf3956c2017-02-14 14:52:34 -0800870 return spv::BuiltInPositionPerViewNV;
871 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800872 if (!memberDeclaration) {
873 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
874 builder.addCapability(spv::CapabilityPerViewAttributesNV);
875 }
chaocdf3956c2017-02-14 14:52:34 -0800876 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700877 case glslang::EbvFragFullyCoveredNV:
878 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
879 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
880 return spv::BuiltInFullyCoveredEXT;
Chao Chen5b2203d2018-09-19 11:43:21 -0700881 case glslang::EbvFragmentSizeNV:
882 builder.addExtension(spv::E_SPV_NV_shading_rate);
883 builder.addCapability(spv::CapabilityShadingRateNV);
884 return spv::BuiltInFragmentSizeNV;
885 case glslang::EbvInvocationsPerPixelNV:
886 builder.addExtension(spv::E_SPV_NV_shading_rate);
887 builder.addCapability(spv::CapabilityShadingRateNV);
888 return spv::BuiltInInvocationsPerPixelNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700889
890 // raytracing
891 case glslang::EbvLaunchIdNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700892 return spv::BuiltInLaunchIdNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700893 case glslang::EbvLaunchSizeNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700894 return spv::BuiltInLaunchSizeNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700895 case glslang::EbvWorldRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700896 return spv::BuiltInWorldRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700897 case glslang::EbvWorldRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700898 return spv::BuiltInWorldRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700899 case glslang::EbvObjectRayOriginNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700900 return spv::BuiltInObjectRayOriginNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700901 case glslang::EbvObjectRayDirectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700902 return spv::BuiltInObjectRayDirectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700903 case glslang::EbvRayTminNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700904 return spv::BuiltInRayTminNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700905 case glslang::EbvRayTmaxNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700906 return spv::BuiltInRayTmaxNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700907 case glslang::EbvInstanceCustomIndexNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700908 return spv::BuiltInInstanceCustomIndexNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700909 case glslang::EbvHitTNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700910 return spv::BuiltInHitTNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700911 case glslang::EbvHitKindNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700912 return spv::BuiltInHitKindNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700913 case glslang::EbvObjectToWorldNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700914 return spv::BuiltInObjectToWorldNV;
Chao Chenb50c02e2018-09-19 11:42:24 -0700915 case glslang::EbvWorldToObjectNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -0700916 return spv::BuiltInWorldToObjectNV;
917 case glslang::EbvIncomingRayFlagsNV:
918 return spv::BuiltInIncomingRayFlagsNV;
Chao Chen9eada4b2018-09-19 11:39:56 -0700919 case glslang::EbvBaryCoordNV:
920 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
921 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
922 return spv::BuiltInBaryCoordNV;
923 case glslang::EbvBaryCoordNoPerspNV:
924 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
925 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
926 return spv::BuiltInBaryCoordNoPerspNV;
Chao Chen3c366992018-09-19 11:41:59 -0700927 case glslang::EbvTaskCountNV:
928 return spv::BuiltInTaskCountNV;
929 case glslang::EbvPrimitiveCountNV:
930 return spv::BuiltInPrimitiveCountNV;
931 case glslang::EbvPrimitiveIndicesNV:
932 return spv::BuiltInPrimitiveIndicesNV;
933 case glslang::EbvClipDistancePerViewNV:
934 return spv::BuiltInClipDistancePerViewNV;
935 case glslang::EbvCullDistancePerViewNV:
936 return spv::BuiltInCullDistancePerViewNV;
937 case glslang::EbvLayerPerViewNV:
938 return spv::BuiltInLayerPerViewNV;
939 case glslang::EbvMeshViewCountNV:
940 return spv::BuiltInMeshViewCountNV;
941 case glslang::EbvMeshViewIndicesNV:
942 return spv::BuiltInMeshViewIndicesNV;
chaoc771d89f2017-01-13 01:10:53 -0800943#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800944 default:
945 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600946 }
947}
948
Rex Xufc618912015-09-09 16:42:49 +0800949// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700950spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800951{
952 assert(type.getBasicType() == glslang::EbtSampler);
953
John Kessenich5d0fa972016-02-15 11:57:00 -0700954 // Check for capabilities
955 switch (type.getQualifier().layoutFormat) {
956 case glslang::ElfRg32f:
957 case glslang::ElfRg16f:
958 case glslang::ElfR11fG11fB10f:
959 case glslang::ElfR16f:
960 case glslang::ElfRgba16:
961 case glslang::ElfRgb10A2:
962 case glslang::ElfRg16:
963 case glslang::ElfRg8:
964 case glslang::ElfR16:
965 case glslang::ElfR8:
966 case glslang::ElfRgba16Snorm:
967 case glslang::ElfRg16Snorm:
968 case glslang::ElfRg8Snorm:
969 case glslang::ElfR16Snorm:
970 case glslang::ElfR8Snorm:
971
972 case glslang::ElfRg32i:
973 case glslang::ElfRg16i:
974 case glslang::ElfRg8i:
975 case glslang::ElfR16i:
976 case glslang::ElfR8i:
977
978 case glslang::ElfRgb10a2ui:
979 case glslang::ElfRg32ui:
980 case glslang::ElfRg16ui:
981 case glslang::ElfRg8ui:
982 case glslang::ElfR16ui:
983 case glslang::ElfR8ui:
984 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
985 break;
986
987 default:
988 break;
989 }
990
991 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800992 switch (type.getQualifier().layoutFormat) {
993 case glslang::ElfNone: return spv::ImageFormatUnknown;
994 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
995 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
996 case glslang::ElfR32f: return spv::ImageFormatR32f;
997 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
998 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
999 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
1000 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
1001 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
1002 case glslang::ElfR16f: return spv::ImageFormatR16f;
1003 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
1004 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
1005 case glslang::ElfRg16: return spv::ImageFormatRg16;
1006 case glslang::ElfRg8: return spv::ImageFormatRg8;
1007 case glslang::ElfR16: return spv::ImageFormatR16;
1008 case glslang::ElfR8: return spv::ImageFormatR8;
1009 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
1010 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
1011 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
1012 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
1013 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
1014 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
1015 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
1016 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
1017 case glslang::ElfR32i: return spv::ImageFormatR32i;
1018 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
1019 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
1020 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
1021 case glslang::ElfR16i: return spv::ImageFormatR16i;
1022 case glslang::ElfR8i: return spv::ImageFormatR8i;
1023 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
1024 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
1025 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
1026 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
1027 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
1028 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
1029 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
1030 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
1031 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
1032 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -06001033 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +08001034 }
1035}
1036
John Kesseniche18fd202018-01-30 11:01:39 -07001037spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +08001038{
John Kesseniche18fd202018-01-30 11:01:39 -07001039 if (selectionNode.getFlatten())
1040 return spv::SelectionControlFlattenMask;
1041 if (selectionNode.getDontFlatten())
1042 return spv::SelectionControlDontFlattenMask;
1043 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +08001044}
1045
John Kesseniche18fd202018-01-30 11:01:39 -07001046spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -06001047{
John Kesseniche18fd202018-01-30 11:01:39 -07001048 if (switchNode.getFlatten())
1049 return spv::SelectionControlFlattenMask;
1050 if (switchNode.getDontFlatten())
1051 return spv::SelectionControlDontFlattenMask;
1052 return spv::SelectionControlMaskNone;
1053}
1054
John Kessenicha2858d92018-01-31 08:11:18 -07001055// return a non-0 dependency if the dependency argument must be set
1056spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
1057 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -07001058{
1059 spv::LoopControlMask control = spv::LoopControlMaskNone;
1060
1061 if (loopNode.getDontUnroll())
1062 control = control | spv::LoopControlDontUnrollMask;
1063 if (loopNode.getUnroll())
1064 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -07001065 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -07001066 control = control | spv::LoopControlDependencyInfiniteMask;
1067 else if (loopNode.getLoopDependency() > 0) {
1068 control = control | spv::LoopControlDependencyLengthMask;
1069 dependencyLength = loopNode.getLoopDependency();
1070 }
John Kesseniche18fd202018-01-30 11:01:39 -07001071
1072 return control;
steve-lunargf1709e72017-05-02 20:14:50 -06001073}
1074
John Kessenicha5c5fb62017-05-05 05:09:58 -06001075// Translate glslang type to SPIR-V storage class.
1076spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
1077{
1078 if (type.getQualifier().isPipeInput())
1079 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001080 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -06001081 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001082
1083 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
1084 type.getQualifier().storage == glslang::EvqUniform) {
1085 if (type.getBasicType() == glslang::EbtAtomicUint)
1086 return spv::StorageClassAtomicCounter;
1087 if (type.containsOpaque())
1088 return spv::StorageClassUniformConstant;
1089 }
1090
1091 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -07001092 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -06001093 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001094 }
1095
1096 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -06001097 if (type.getQualifier().layoutPushConstant)
1098 return spv::StorageClassPushConstant;
Chao Chenb50c02e2018-09-19 11:42:24 -07001099#ifdef NV_EXTENSIONS
1100 if (type.getQualifier().layoutShaderRecordNV)
Ashwin Leleff1783d2018-10-22 16:41:44 -07001101 return spv::StorageClassShaderRecordBufferNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001102#endif
John Kessenicha5c5fb62017-05-05 05:09:58 -06001103 if (type.getBasicType() == glslang::EbtBlock)
1104 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -06001105 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001106 }
John Kessenichbed4e4f2017-09-08 02:38:07 -06001107
1108 switch (type.getQualifier().storage) {
1109 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1110 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1111 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1112 case glslang::EvqTemporary: return spv::StorageClassFunction;
Chao Chenb50c02e2018-09-19 11:42:24 -07001113#ifdef NV_EXTENSIONS
Ashwin Leleff1783d2018-10-22 16:41:44 -07001114 case glslang::EvqPayloadNV: return spv::StorageClassRayPayloadNV;
1115 case glslang::EvqPayloadInNV: return spv::StorageClassIncomingRayPayloadNV;
1116 case glslang::EvqHitAttrNV: return spv::StorageClassHitAttributeNV;
1117 case glslang::EvqCallableDataNV: return spv::StorageClassCallableDataNV;
1118 case glslang::EvqCallableDataInNV: return spv::StorageClassIncomingCallableDataNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07001119#endif
John Kessenichbed4e4f2017-09-08 02:38:07 -06001120 default:
1121 assert(0);
1122 break;
1123 }
1124
1125 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001126}
1127
John Kessenich5611c6d2018-04-05 11:25:02 -06001128// Add capabilities pertaining to how an array is indexed.
1129void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1130 const glslang::TType& indexType)
1131{
1132 if (indexType.getQualifier().isNonUniform()) {
1133 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001134 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001135 if (baseType.getBasicType() == glslang::EbtSampler) {
1136 if (baseType.getQualifier().hasAttachment())
1137 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1138 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1139 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1140 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1141 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1142 else if (baseType.isImage())
1143 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1144 else if (baseType.isTexture())
1145 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1146 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1147 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1148 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1149 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1150 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1151 }
1152 } else {
1153 // assume a dynamically uniform index
1154 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001155 if (baseType.getQualifier().hasAttachment()) {
1156 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001157 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001158 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1159 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001160 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001161 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1162 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001163 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001164 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001165 }
1166 }
1167}
1168
qining25262b32016-05-06 17:25:16 -04001169// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001170// descriptor set.
1171bool IsDescriptorResource(const glslang::TType& type)
1172{
John Kessenichf7497e22016-03-08 21:36:22 -07001173 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001174 if (type.getBasicType() == glslang::EbtBlock)
Chao Chenb50c02e2018-09-19 11:42:24 -07001175 return type.getQualifier().isUniformOrBuffer() &&
1176#ifdef NV_EXTENSIONS
1177 ! type.getQualifier().layoutShaderRecordNV &&
1178#endif
1179 ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001180
1181 // non block...
1182 // basically samplerXXX/subpass/sampler/texture are all included
1183 // if they are the global-scope-class, not the function parameter
1184 // (or local, if they ever exist) class.
1185 if (type.getBasicType() == glslang::EbtSampler)
1186 return type.getQualifier().isUniformOrBuffer();
1187
1188 // None of the above.
1189 return false;
1190}
1191
John Kesseniche0b6cad2015-12-24 10:30:13 -07001192void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1193{
1194 if (child.layoutMatrix == glslang::ElmNone)
1195 child.layoutMatrix = parent.layoutMatrix;
1196
1197 if (parent.invariant)
1198 child.invariant = true;
1199 if (parent.nopersp)
1200 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001201#ifdef AMD_EXTENSIONS
1202 if (parent.explicitInterp)
1203 child.explicitInterp = true;
1204#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001205 if (parent.flat)
1206 child.flat = true;
1207 if (parent.centroid)
1208 child.centroid = true;
1209 if (parent.patch)
1210 child.patch = true;
1211 if (parent.sample)
1212 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001213 if (parent.coherent)
1214 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001215 if (parent.devicecoherent)
1216 child.devicecoherent = true;
1217 if (parent.queuefamilycoherent)
1218 child.queuefamilycoherent = true;
1219 if (parent.workgroupcoherent)
1220 child.workgroupcoherent = true;
1221 if (parent.subgroupcoherent)
1222 child.subgroupcoherent = true;
1223 if (parent.nonprivate)
1224 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001225 if (parent.volatil)
1226 child.volatil = true;
1227 if (parent.restrict)
1228 child.restrict = true;
1229 if (parent.readonly)
1230 child.readonly = true;
1231 if (parent.writeonly)
1232 child.writeonly = true;
Chao Chen3c366992018-09-19 11:41:59 -07001233#ifdef NV_EXTENSIONS
1234 if (parent.perPrimitiveNV)
1235 child.perPrimitiveNV = true;
1236 if (parent.perViewNV)
1237 child.perViewNV = true;
1238 if (parent.perTaskNV)
1239 child.perTaskNV = true;
1240#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001241}
1242
John Kessenichf2b7f332016-09-01 17:05:23 -06001243bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001244{
John Kessenich7b9fa252016-01-21 18:56:57 -07001245 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001246 // - struct members might inherit from a struct declaration
1247 // (note that non-block structs don't explicitly inherit,
1248 // only implicitly, meaning no decoration involved)
1249 // - affect decorations on the struct members
1250 // (note smooth does not, and expecting something like volatile
1251 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001252 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001253 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001254}
1255
John Kessenich140f3df2015-06-26 16:58:36 -06001256//
1257// Implement the TGlslangToSpvTraverser class.
1258//
1259
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001260TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001261 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1262 : TIntermTraverser(true, false, true),
1263 options(options),
1264 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001265 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001266 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001267 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001268 glslangIntermediate(glslangIntermediate)
1269{
1270 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1271
1272 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001273 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1274 glslangIntermediate->getVersion());
1275
John Kessenich121853f2017-05-31 17:11:16 -06001276 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001277 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001278 builder.setSourceFile(glslangIntermediate->getSourceFile());
1279
1280 // Set the source shader's text. If for SPV version 1.0, include
1281 // a preamble in comments stating the OpModuleProcessed instructions.
1282 // Otherwise, emit those as actual instructions.
1283 std::string text;
1284 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1285 for (int p = 0; p < (int)processes.size(); ++p) {
John Kessenich8717a5d2018-10-26 10:12:32 -06001286 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1) {
John Kessenich2a271162017-07-20 20:00:36 -06001287 text.append("// OpModuleProcessed ");
1288 text.append(processes[p]);
1289 text.append("\n");
1290 } else
1291 builder.addModuleProcessed(processes[p]);
1292 }
John Kessenich8717a5d2018-10-26 10:12:32 -06001293 if (glslangIntermediate->getSpv().spv < glslang::EShTargetSpv_1_1 && (int)processes.size() > 0)
John Kessenich2a271162017-07-20 20:00:36 -06001294 text.append("#line 1\n");
1295 text.append(glslangIntermediate->getSourceText());
1296 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -06001297 }
John Kessenich140f3df2015-06-26 16:58:36 -06001298 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz36831c92018-09-05 10:11:41 -05001299 if (glslangIntermediate->usingVulkanMemoryModel()) {
1300 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelVulkanKHR);
1301 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
1302 } else {
1303 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
1304 }
John Kessenicheee9d532016-09-19 18:09:30 -06001305 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1306 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001307
1308 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001309 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1310 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001311 builder.addSourceExtension(it->c_str());
1312
1313 // Add the top-level modes for this shader.
1314
John Kessenich92187592016-02-01 13:45:25 -07001315 if (glslangIntermediate->getXfbMode()) {
1316 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001317 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001318 }
John Kessenich140f3df2015-06-26 16:58:36 -06001319
1320 unsigned int mode;
1321 switch (glslangIntermediate->getStage()) {
1322 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001323 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001324 break;
1325
steve-lunarge7412492017-03-23 11:56:07 -06001326 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001327 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001328 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001329
steve-lunarge7412492017-03-23 11:56:07 -06001330 glslang::TLayoutGeometry primitive;
1331
1332 if (glslangIntermediate->getStage() == EShLangTessControl) {
1333 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1334 primitive = glslangIntermediate->getOutputPrimitive();
1335 } else {
1336 primitive = glslangIntermediate->getInputPrimitive();
1337 }
1338
1339 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001340 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1341 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1342 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001343 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001344 }
John Kessenich4016e382016-07-15 11:53:56 -06001345 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001346 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1347
John Kesseniche6903322015-10-13 16:29:02 -06001348 switch (glslangIntermediate->getVertexSpacing()) {
1349 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1350 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1351 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001352 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001353 }
John Kessenich4016e382016-07-15 11:53:56 -06001354 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001355 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1356
1357 switch (glslangIntermediate->getVertexOrder()) {
1358 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1359 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001360 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001361 }
John Kessenich4016e382016-07-15 11:53:56 -06001362 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001363 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1364
1365 if (glslangIntermediate->getPointMode())
1366 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001367 break;
1368
1369 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001370 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001371 switch (glslangIntermediate->getInputPrimitive()) {
1372 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1373 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1374 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001375 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001376 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001377 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001378 }
John Kessenich4016e382016-07-15 11:53:56 -06001379 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001380 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001381
John Kessenich140f3df2015-06-26 16:58:36 -06001382 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1383
1384 switch (glslangIntermediate->getOutputPrimitive()) {
1385 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1386 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1387 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001388 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001389 }
John Kessenich4016e382016-07-15 11:53:56 -06001390 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001391 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1392 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1393 break;
1394
1395 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001396 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001397 if (glslangIntermediate->getPixelCenterInteger())
1398 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001399
John Kessenich140f3df2015-06-26 16:58:36 -06001400 if (glslangIntermediate->getOriginUpperLeft())
1401 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001402 else
1403 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001404
1405 if (glslangIntermediate->getEarlyFragmentTests())
1406 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1407
chaocc1204522017-06-30 17:14:30 -07001408 if (glslangIntermediate->getPostDepthCoverage()) {
1409 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1410 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1411 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1412 }
1413
John Kesseniche6903322015-10-13 16:29:02 -06001414 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001415 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1416 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001417 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001418 }
John Kessenich4016e382016-07-15 11:53:56 -06001419 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001420 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1421
1422 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1423 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001424 break;
1425
1426 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001427 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001428 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1429 glslangIntermediate->getLocalSize(1),
1430 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001431#ifdef NV_EXTENSIONS
1432 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1433 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1434 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1435 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1436 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1437 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1438 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1439 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1440 }
1441#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001442 break;
1443
Chao Chen3c366992018-09-19 11:41:59 -07001444#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07001445 case EShLangRayGenNV:
1446 case EShLangIntersectNV:
1447 case EShLangAnyHitNV:
1448 case EShLangClosestHitNV:
1449 case EShLangMissNV:
1450 case EShLangCallableNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07001451 builder.addCapability(spv::CapabilityRayTracingNV);
1452 builder.addExtension("SPV_NV_ray_tracing");
Chao Chenb50c02e2018-09-19 11:42:24 -07001453 break;
Chao Chen3c366992018-09-19 11:41:59 -07001454 case EShLangTaskNV:
1455 case EShLangMeshNV:
1456 builder.addCapability(spv::CapabilityMeshShadingNV);
1457 builder.addExtension(spv::E_SPV_NV_mesh_shader);
1458 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1459 glslangIntermediate->getLocalSize(1),
1460 glslangIntermediate->getLocalSize(2));
1461 if (glslangIntermediate->getStage() == EShLangMeshNV) {
1462 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1463 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputPrimitivesNV, glslangIntermediate->getPrimitives());
1464
1465 switch (glslangIntermediate->getOutputPrimitive()) {
1466 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1467 case glslang::ElgLines: mode = spv::ExecutionModeOutputLinesNV; break;
1468 case glslang::ElgTriangles: mode = spv::ExecutionModeOutputTrianglesNV; break;
1469 default: mode = spv::ExecutionModeMax; break;
1470 }
1471 if (mode != spv::ExecutionModeMax)
1472 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1473 }
1474 break;
1475#endif
1476
John Kessenich140f3df2015-06-26 16:58:36 -06001477 default:
1478 break;
1479 }
John Kessenich140f3df2015-06-26 16:58:36 -06001480}
1481
John Kessenichfca82622016-11-26 13:23:20 -07001482// Finish creating SPV, after the traversal is complete.
1483void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001484{
John Kessenichf04c51b2018-08-03 15:56:12 -06001485 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001486 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001487 builder.setBuildPoint(shaderEntry->getLastBlock());
1488 builder.leaveFunction();
1489 }
1490
John Kessenich7ba63412015-12-20 17:37:07 -07001491 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001492 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1493 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001494
John Kessenichf04c51b2018-08-03 15:56:12 -06001495 // Add capabilities, extensions, remove unneeded decorations, etc.,
1496 // based on the resulting SPIR-V.
1497 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001498}
1499
John Kessenichfca82622016-11-26 13:23:20 -07001500// Write the SPV into 'out'.
1501void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001502{
John Kessenichfca82622016-11-26 13:23:20 -07001503 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001504}
1505
1506//
1507// Implement the traversal functions.
1508//
1509// Return true from interior nodes to have the external traversal
1510// continue on to children. Return false if children were
1511// already processed.
1512//
1513
1514//
qining25262b32016-05-06 17:25:16 -04001515// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001516// - uniform/input reads
1517// - output writes
1518// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1519// - something simple that degenerates into the last bullet
1520//
1521void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1522{
qining75d1d802016-04-06 14:42:01 -04001523 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1524 if (symbol->getType().getQualifier().isSpecConstant())
1525 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1526
John Kessenich140f3df2015-06-26 16:58:36 -06001527 // getSymbolId() will set up all the IO decorations on the first call.
1528 // Formal function parameters were mapped during makeFunctions().
1529 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001530
1531 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1532 if (builder.isPointer(id)) {
1533 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001534 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1535 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1536 iOSet.insert(id);
1537 }
John Kessenich7ba63412015-12-20 17:37:07 -07001538 }
1539
1540 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001541 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001542 // Prepare to generate code for the access
1543
1544 // L-value chains will be computed left to right. We're on the symbol now,
1545 // which is the left-most part of the access chain, so now is "clear" time,
1546 // followed by setting the base.
1547 builder.clearAccessChain();
1548
1549 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001550 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001551 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001552 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001553 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001554 // These are also pure R-values.
1555 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001556 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001557 builder.setAccessChainRValue(id);
1558 else
1559 builder.setAccessChainLValue(id);
1560 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001561
1562 // Process linkage-only nodes for any special additional interface work.
1563 if (linkageOnly) {
1564 if (glslangIntermediate->getHlslFunctionality1()) {
1565 // Map implicit counter buffers to their originating buffers, which should have been
1566 // seen by now, given earlier pruning of unused counters, and preservation of order
1567 // of declaration.
1568 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1569 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1570 // Save possible originating buffers for counter buffers, keyed by
1571 // making the potential counter-buffer name.
1572 std::string keyName = symbol->getName().c_str();
1573 keyName = glslangIntermediate->addCounterBufferName(keyName);
1574 counterOriginator[keyName] = symbol;
1575 } else {
1576 // Handle a counter buffer, by finding the saved originating buffer.
1577 std::string keyName = symbol->getName().c_str();
1578 auto it = counterOriginator.find(keyName);
1579 if (it != counterOriginator.end()) {
1580 id = getSymbolId(it->second);
1581 if (id != spv::NoResult) {
1582 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001583 if (counterId != spv::NoResult) {
1584 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001585 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001586 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001587 }
1588 }
1589 }
1590 }
1591 }
1592 }
John Kessenich140f3df2015-06-26 16:58:36 -06001593}
1594
1595bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1596{
John Kesseniche485c7a2017-05-31 18:50:53 -06001597 builder.setLine(node->getLoc().line);
1598
qining40887662016-04-03 22:20:42 -04001599 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1600 if (node->getType().getQualifier().isSpecConstant())
1601 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1602
John Kessenich140f3df2015-06-26 16:58:36 -06001603 // First, handle special cases
1604 switch (node->getOp()) {
1605 case glslang::EOpAssign:
1606 case glslang::EOpAddAssign:
1607 case glslang::EOpSubAssign:
1608 case glslang::EOpMulAssign:
1609 case glslang::EOpVectorTimesMatrixAssign:
1610 case glslang::EOpVectorTimesScalarAssign:
1611 case glslang::EOpMatrixTimesScalarAssign:
1612 case glslang::EOpMatrixTimesMatrixAssign:
1613 case glslang::EOpDivAssign:
1614 case glslang::EOpModAssign:
1615 case glslang::EOpAndAssign:
1616 case glslang::EOpInclusiveOrAssign:
1617 case glslang::EOpExclusiveOrAssign:
1618 case glslang::EOpLeftShiftAssign:
1619 case glslang::EOpRightShiftAssign:
1620 // A bin-op assign "a += b" means the same thing as "a = a + b"
1621 // where a is evaluated before b. For a simple assignment, GLSL
1622 // says to evaluate the left before the right. So, always, left
1623 // node then right node.
1624 {
1625 // get the left l-value, save it away
1626 builder.clearAccessChain();
1627 node->getLeft()->traverse(this);
1628 spv::Builder::AccessChain lValue = builder.getAccessChain();
1629
1630 // evaluate the right
1631 builder.clearAccessChain();
1632 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001633 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001634
1635 if (node->getOp() != glslang::EOpAssign) {
1636 // the left is also an r-value
1637 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001638 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001639
1640 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001641 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001642 TranslateNoContractionDecoration(node->getType().getQualifier()),
1643 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001644 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001645 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1646 node->getType().getBasicType());
1647
1648 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001649 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001650 }
1651
1652 // store the result
1653 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001654 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001655
1656 // assignments are expressions having an rValue after they are evaluated...
1657 builder.clearAccessChain();
1658 builder.setAccessChainRValue(rValue);
1659 }
1660 return false;
1661 case glslang::EOpIndexDirect:
1662 case glslang::EOpIndexDirectStruct:
1663 {
1664 // Get the left part of the access chain.
1665 node->getLeft()->traverse(this);
1666
1667 // Add the next element in the chain
1668
David Netoa901ffe2016-06-08 14:11:40 +01001669 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001670 if (! node->getLeft()->getType().isArray() &&
1671 node->getLeft()->getType().isVector() &&
1672 node->getOp() == glslang::EOpIndexDirect) {
1673 // This is essentially a hard-coded vector swizzle of size 1,
1674 // so short circuit the access-chain stuff with a swizzle.
1675 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001676 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001677 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001678 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001679 int spvIndex = glslangIndex;
1680 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1681 node->getOp() == glslang::EOpIndexDirectStruct)
1682 {
1683 // This may be, e.g., an anonymous block-member selection, which generally need
1684 // index remapping due to hidden members in anonymous blocks.
1685 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1686 assert(remapper.size() > 0);
1687 spvIndex = remapper[glslangIndex];
1688 }
John Kessenichebb50532016-05-16 19:22:05 -06001689
David Netoa901ffe2016-06-08 14:11:40 +01001690 // normal case for indexing array or structure or block
Jeff Bolz36831c92018-09-05 10:11:41 -05001691 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()));
David Netoa901ffe2016-06-08 14:11:40 +01001692
1693 // Add capabilities here for accessing PointSize and clip/cull distance.
1694 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001695 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001696 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001697 }
1698 }
1699 return false;
1700 case glslang::EOpIndexIndirect:
1701 {
1702 // Structure or array or vector indirection.
1703 // Will use native SPIR-V access-chain for struct and array indirection;
1704 // matrices are arrays of vectors, so will also work for a matrix.
1705 // Will use the access chain's 'component' for variable index into a vector.
1706
1707 // This adapter is building access chains left to right.
1708 // Set up the access chain to the left.
1709 node->getLeft()->traverse(this);
1710
1711 // save it so that computing the right side doesn't trash it
1712 spv::Builder::AccessChain partial = builder.getAccessChain();
1713
1714 // compute the next index in the chain
1715 builder.clearAccessChain();
1716 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001717 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001718
John Kessenich5611c6d2018-04-05 11:25:02 -06001719 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1720
John Kessenich140f3df2015-06-26 16:58:36 -06001721 // restore the saved access chain
1722 builder.setAccessChain(partial);
1723
1724 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001725 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001726 else
Jeff Bolz36831c92018-09-05 10:11:41 -05001727 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001728 }
1729 return false;
1730 case glslang::EOpVectorSwizzle:
1731 {
1732 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001733 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001734 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001735 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001736 }
1737 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001738 case glslang::EOpMatrixSwizzle:
1739 logger->missingFunctionality("matrix swizzle");
1740 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001741 case glslang::EOpLogicalOr:
1742 case glslang::EOpLogicalAnd:
1743 {
1744
1745 // These may require short circuiting, but can sometimes be done as straight
1746 // binary operations. The right operand must be short circuited if it has
1747 // side effects, and should probably be if it is complex.
1748 if (isTrivial(node->getRight()->getAsTyped()))
1749 break; // handle below as a normal binary operation
1750 // otherwise, we need to do dynamic short circuiting on the right operand
1751 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1752 builder.clearAccessChain();
1753 builder.setAccessChainRValue(result);
1754 }
1755 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001756 default:
1757 break;
1758 }
1759
1760 // Assume generic binary op...
1761
John Kessenich32cfd492016-02-02 12:37:46 -07001762 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001763 builder.clearAccessChain();
1764 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001765 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001766
John Kessenich32cfd492016-02-02 12:37:46 -07001767 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001768 builder.clearAccessChain();
1769 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001770 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001771
John Kessenich32cfd492016-02-02 12:37:46 -07001772 // get result
John Kessenichead86222018-03-28 18:01:20 -06001773 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001774 TranslateNoContractionDecoration(node->getType().getQualifier()),
1775 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001776 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001777 convertGlslangToSpvType(node->getType()), left, right,
1778 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001779
John Kessenich50e57562015-12-21 21:21:11 -07001780 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001781 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001782 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001783 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001784 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001785 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001786 return false;
1787 }
John Kessenich140f3df2015-06-26 16:58:36 -06001788}
1789
1790bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1791{
John Kesseniche485c7a2017-05-31 18:50:53 -06001792 builder.setLine(node->getLoc().line);
1793
qining40887662016-04-03 22:20:42 -04001794 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1795 if (node->getType().getQualifier().isSpecConstant())
1796 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1797
John Kessenichfc51d282015-08-19 13:34:18 -06001798 spv::Id result = spv::NoResult;
1799
1800 // try texturing first
1801 result = createImageTextureFunctionCall(node);
1802 if (result != spv::NoResult) {
1803 builder.clearAccessChain();
1804 builder.setAccessChainRValue(result);
1805
1806 return false; // done with this node
1807 }
1808
1809 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001810
1811 if (node->getOp() == glslang::EOpArrayLength) {
1812 // Quite special; won't want to evaluate the operand.
1813
John Kessenich5611c6d2018-04-05 11:25:02 -06001814 // Currently, the front-end does not allow .length() on an array until it is sized,
1815 // except for the last block membeor of an SSBO.
1816 // TODO: If this changes, link-time sized arrays might show up here, and need their
1817 // size extracted.
1818
John Kessenichc9a80832015-09-12 12:17:44 -06001819 // Normal .length() would have been constant folded by the front-end.
1820 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001821 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001822
John Kessenichc9a80832015-09-12 12:17:44 -06001823 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1824 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001825 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1826 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001827
1828 builder.clearAccessChain();
1829 builder.setAccessChainRValue(length);
1830
1831 return false;
1832 }
1833
John Kessenichfc51d282015-08-19 13:34:18 -06001834 // Start by evaluating the operand
1835
John Kessenich8c8505c2016-07-26 12:50:38 -06001836 // Does it need a swizzle inversion? If so, evaluation is inverted;
1837 // operate first on the swizzle base, then apply the swizzle.
1838 spv::Id invertedType = spv::NoType;
1839 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1840 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1841 invertedType = getInvertedSwizzleType(*node->getOperand());
1842
John Kessenich140f3df2015-06-26 16:58:36 -06001843 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001844 if (invertedType != spv::NoType)
1845 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1846 else
1847 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001848
Rex Xufc618912015-09-09 16:42:49 +08001849 spv::Id operand = spv::NoResult;
1850
1851 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1852 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001853 node->getOp() == glslang::EOpAtomicCounter ||
1854 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001855 operand = builder.accessChainGetLValue(); // Special case l-value operands
1856 else
John Kessenich32cfd492016-02-02 12:37:46 -07001857 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001858
John Kessenichead86222018-03-28 18:01:20 -06001859 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001860 TranslateNoContractionDecoration(node->getType().getQualifier()),
1861 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001862
1863 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001864 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001865 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001866
1867 // if not, then possibly an operation
1868 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001869 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001870
1871 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001872 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001873 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001874 builder.addDecoration(result, decorations.nonUniform);
1875 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001876
John Kessenich140f3df2015-06-26 16:58:36 -06001877 builder.clearAccessChain();
1878 builder.setAccessChainRValue(result);
1879
1880 return false; // done with this node
1881 }
1882
1883 // it must be a special case, check...
1884 switch (node->getOp()) {
1885 case glslang::EOpPostIncrement:
1886 case glslang::EOpPostDecrement:
1887 case glslang::EOpPreIncrement:
1888 case glslang::EOpPreDecrement:
1889 {
1890 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001891 spv::Id one = 0;
1892 if (node->getBasicType() == glslang::EbtFloat)
1893 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001894 else if (node->getBasicType() == glslang::EbtDouble)
1895 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001896 else if (node->getBasicType() == glslang::EbtFloat16)
1897 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001898 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1899 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001900 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1901 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001902 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1903 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001904 else
1905 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001906 glslang::TOperator op;
1907 if (node->getOp() == glslang::EOpPreIncrement ||
1908 node->getOp() == glslang::EOpPostIncrement)
1909 op = glslang::EOpAdd;
1910 else
1911 op = glslang::EOpSub;
1912
John Kessenichead86222018-03-28 18:01:20 -06001913 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001914 convertGlslangToSpvType(node->getType()), operand, one,
1915 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001916 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001917
1918 // The result of operation is always stored, but conditionally the
1919 // consumed result. The consumed result is always an r-value.
1920 builder.accessChainStore(result);
1921 builder.clearAccessChain();
1922 if (node->getOp() == glslang::EOpPreIncrement ||
1923 node->getOp() == glslang::EOpPreDecrement)
1924 builder.setAccessChainRValue(result);
1925 else
1926 builder.setAccessChainRValue(operand);
1927 }
1928
1929 return false;
1930
1931 case glslang::EOpEmitStreamVertex:
1932 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1933 return false;
1934 case glslang::EOpEndStreamPrimitive:
1935 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1936 return false;
1937
1938 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001939 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001940 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001941 }
John Kessenich140f3df2015-06-26 16:58:36 -06001942}
1943
1944bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1945{
qining27e04a02016-04-14 16:40:20 -04001946 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1947 if (node->getType().getQualifier().isSpecConstant())
1948 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1949
John Kessenichfc51d282015-08-19 13:34:18 -06001950 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001951 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1952 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001953
1954 // try texturing
1955 result = createImageTextureFunctionCall(node);
1956 if (result != spv::NoResult) {
1957 builder.clearAccessChain();
1958 builder.setAccessChainRValue(result);
1959
1960 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05001961 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08001962#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05001963 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08001964#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05001965 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08001966 // "imageStore" is a special case, which has no result
1967 return false;
1968 }
John Kessenichfc51d282015-08-19 13:34:18 -06001969
John Kessenich140f3df2015-06-26 16:58:36 -06001970 glslang::TOperator binOp = glslang::EOpNull;
1971 bool reduceComparison = true;
1972 bool isMatrix = false;
1973 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001974 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001975
1976 assert(node->getOp());
1977
John Kessenichf6640762016-08-01 19:44:00 -06001978 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001979
1980 switch (node->getOp()) {
1981 case glslang::EOpSequence:
1982 {
1983 if (preVisit)
1984 ++sequenceDepth;
1985 else
1986 --sequenceDepth;
1987
1988 if (sequenceDepth == 1) {
1989 // If this is the parent node of all the functions, we want to see them
1990 // early, so all call points have actual SPIR-V functions to reference.
1991 // In all cases, still let the traverser visit the children for us.
1992 makeFunctions(node->getAsAggregate()->getSequence());
1993
John Kessenich6fccb3c2016-09-19 16:01:41 -06001994 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001995 // anything else gets there, so visit out of order, doing them all now.
1996 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1997
John Kessenich6a60c2f2016-12-08 21:01:59 -07001998 // 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 -06001999 // so do them manually.
2000 visitFunctions(node->getAsAggregate()->getSequence());
2001
2002 return false;
2003 }
2004
2005 return true;
2006 }
2007 case glslang::EOpLinkerObjects:
2008 {
2009 if (visit == glslang::EvPreVisit)
2010 linkageOnly = true;
2011 else
2012 linkageOnly = false;
2013
2014 return true;
2015 }
2016 case glslang::EOpComma:
2017 {
2018 // processing from left to right naturally leaves the right-most
2019 // lying around in the access chain
2020 glslang::TIntermSequence& glslangOperands = node->getSequence();
2021 for (int i = 0; i < (int)glslangOperands.size(); ++i)
2022 glslangOperands[i]->traverse(this);
2023
2024 return false;
2025 }
2026 case glslang::EOpFunction:
2027 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06002028 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07002029 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06002030 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06002031 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06002032 } else {
2033 handleFunctionEntry(node);
2034 }
2035 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07002036 if (inEntryPoint)
2037 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06002038 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07002039 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002040 }
2041
2042 return true;
2043 case glslang::EOpParameters:
2044 // Parameters will have been consumed by EOpFunction processing, but not
2045 // the body, so we still visited the function node's children, making this
2046 // child redundant.
2047 return false;
2048 case glslang::EOpFunctionCall:
2049 {
John Kesseniche485c7a2017-05-31 18:50:53 -06002050 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06002051 if (node->isUserDefined())
2052 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07002053 // 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 -07002054 if (result) {
2055 builder.clearAccessChain();
2056 builder.setAccessChainRValue(result);
2057 } else
Lei Zhang17535f72016-05-04 15:55:59 -04002058 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06002059
2060 return false;
2061 }
2062 case glslang::EOpConstructMat2x2:
2063 case glslang::EOpConstructMat2x3:
2064 case glslang::EOpConstructMat2x4:
2065 case glslang::EOpConstructMat3x2:
2066 case glslang::EOpConstructMat3x3:
2067 case glslang::EOpConstructMat3x4:
2068 case glslang::EOpConstructMat4x2:
2069 case glslang::EOpConstructMat4x3:
2070 case glslang::EOpConstructMat4x4:
2071 case glslang::EOpConstructDMat2x2:
2072 case glslang::EOpConstructDMat2x3:
2073 case glslang::EOpConstructDMat2x4:
2074 case glslang::EOpConstructDMat3x2:
2075 case glslang::EOpConstructDMat3x3:
2076 case glslang::EOpConstructDMat3x4:
2077 case glslang::EOpConstructDMat4x2:
2078 case glslang::EOpConstructDMat4x3:
2079 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06002080 case glslang::EOpConstructIMat2x2:
2081 case glslang::EOpConstructIMat2x3:
2082 case glslang::EOpConstructIMat2x4:
2083 case glslang::EOpConstructIMat3x2:
2084 case glslang::EOpConstructIMat3x3:
2085 case glslang::EOpConstructIMat3x4:
2086 case glslang::EOpConstructIMat4x2:
2087 case glslang::EOpConstructIMat4x3:
2088 case glslang::EOpConstructIMat4x4:
2089 case glslang::EOpConstructUMat2x2:
2090 case glslang::EOpConstructUMat2x3:
2091 case glslang::EOpConstructUMat2x4:
2092 case glslang::EOpConstructUMat3x2:
2093 case glslang::EOpConstructUMat3x3:
2094 case glslang::EOpConstructUMat3x4:
2095 case glslang::EOpConstructUMat4x2:
2096 case glslang::EOpConstructUMat4x3:
2097 case glslang::EOpConstructUMat4x4:
2098 case glslang::EOpConstructBMat2x2:
2099 case glslang::EOpConstructBMat2x3:
2100 case glslang::EOpConstructBMat2x4:
2101 case glslang::EOpConstructBMat3x2:
2102 case glslang::EOpConstructBMat3x3:
2103 case glslang::EOpConstructBMat3x4:
2104 case glslang::EOpConstructBMat4x2:
2105 case glslang::EOpConstructBMat4x3:
2106 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002107 case glslang::EOpConstructF16Mat2x2:
2108 case glslang::EOpConstructF16Mat2x3:
2109 case glslang::EOpConstructF16Mat2x4:
2110 case glslang::EOpConstructF16Mat3x2:
2111 case glslang::EOpConstructF16Mat3x3:
2112 case glslang::EOpConstructF16Mat3x4:
2113 case glslang::EOpConstructF16Mat4x2:
2114 case glslang::EOpConstructF16Mat4x3:
2115 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06002116 isMatrix = true;
2117 // fall through
2118 case glslang::EOpConstructFloat:
2119 case glslang::EOpConstructVec2:
2120 case glslang::EOpConstructVec3:
2121 case glslang::EOpConstructVec4:
2122 case glslang::EOpConstructDouble:
2123 case glslang::EOpConstructDVec2:
2124 case glslang::EOpConstructDVec3:
2125 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002126 case glslang::EOpConstructFloat16:
2127 case glslang::EOpConstructF16Vec2:
2128 case glslang::EOpConstructF16Vec3:
2129 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002130 case glslang::EOpConstructBool:
2131 case glslang::EOpConstructBVec2:
2132 case glslang::EOpConstructBVec3:
2133 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07002134 case glslang::EOpConstructInt8:
2135 case glslang::EOpConstructI8Vec2:
2136 case glslang::EOpConstructI8Vec3:
2137 case glslang::EOpConstructI8Vec4:
2138 case glslang::EOpConstructUint8:
2139 case glslang::EOpConstructU8Vec2:
2140 case glslang::EOpConstructU8Vec3:
2141 case glslang::EOpConstructU8Vec4:
2142 case glslang::EOpConstructInt16:
2143 case glslang::EOpConstructI16Vec2:
2144 case glslang::EOpConstructI16Vec3:
2145 case glslang::EOpConstructI16Vec4:
2146 case glslang::EOpConstructUint16:
2147 case glslang::EOpConstructU16Vec2:
2148 case glslang::EOpConstructU16Vec3:
2149 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002150 case glslang::EOpConstructInt:
2151 case glslang::EOpConstructIVec2:
2152 case glslang::EOpConstructIVec3:
2153 case glslang::EOpConstructIVec4:
2154 case glslang::EOpConstructUint:
2155 case glslang::EOpConstructUVec2:
2156 case glslang::EOpConstructUVec3:
2157 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08002158 case glslang::EOpConstructInt64:
2159 case glslang::EOpConstructI64Vec2:
2160 case glslang::EOpConstructI64Vec3:
2161 case glslang::EOpConstructI64Vec4:
2162 case glslang::EOpConstructUint64:
2163 case glslang::EOpConstructU64Vec2:
2164 case glslang::EOpConstructU64Vec3:
2165 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002166 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002167 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06002168 {
John Kesseniche485c7a2017-05-31 18:50:53 -06002169 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06002170 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002171 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002172 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002173 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002174 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07002175 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002176 std::vector<spv::Id> constituents;
2177 for (int c = 0; c < (int)arguments.size(); ++c)
2178 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002179 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002180 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002181 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002182 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002183 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002184
2185 builder.clearAccessChain();
2186 builder.setAccessChainRValue(constructed);
2187
2188 return false;
2189 }
2190
2191 // These six are component-wise compares with component-wise results.
2192 // Forward on to createBinaryOperation(), requesting a vector result.
2193 case glslang::EOpLessThan:
2194 case glslang::EOpGreaterThan:
2195 case glslang::EOpLessThanEqual:
2196 case glslang::EOpGreaterThanEqual:
2197 case glslang::EOpVectorEqual:
2198 case glslang::EOpVectorNotEqual:
2199 {
2200 // Map the operation to a binary
2201 binOp = node->getOp();
2202 reduceComparison = false;
2203 switch (node->getOp()) {
2204 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2205 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2206 default: binOp = node->getOp(); break;
2207 }
2208
2209 break;
2210 }
2211 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002212 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002213 binOp = glslang::EOpMul;
2214 break;
2215 case glslang::EOpOuterProduct:
2216 // two vectors multiplied to make a matrix
2217 binOp = glslang::EOpOuterProduct;
2218 break;
2219 case glslang::EOpDot:
2220 {
qining25262b32016-05-06 17:25:16 -04002221 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002222 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002223 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002224 binOp = glslang::EOpMul;
2225 break;
2226 }
2227 case glslang::EOpMod:
2228 // when an aggregate, this is the floating-point mod built-in function,
2229 // which can be emitted by the one in createBinaryOperation()
2230 binOp = glslang::EOpMod;
2231 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002232 case glslang::EOpEmitVertex:
2233 case glslang::EOpEndPrimitive:
2234 case glslang::EOpBarrier:
2235 case glslang::EOpMemoryBarrier:
2236 case glslang::EOpMemoryBarrierAtomicCounter:
2237 case glslang::EOpMemoryBarrierBuffer:
2238 case glslang::EOpMemoryBarrierImage:
2239 case glslang::EOpMemoryBarrierShared:
2240 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002241 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002242 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002243 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002244 case glslang::EOpWorkgroupMemoryBarrier:
2245 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002246 case glslang::EOpSubgroupBarrier:
2247 case glslang::EOpSubgroupMemoryBarrier:
2248 case glslang::EOpSubgroupMemoryBarrierBuffer:
2249 case glslang::EOpSubgroupMemoryBarrierImage:
2250 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002251 noReturnValue = true;
2252 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2253 break;
2254
Jeff Bolz36831c92018-09-05 10:11:41 -05002255 case glslang::EOpAtomicStore:
2256 noReturnValue = true;
2257 // fallthrough
2258 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002259 case glslang::EOpAtomicAdd:
2260 case glslang::EOpAtomicMin:
2261 case glslang::EOpAtomicMax:
2262 case glslang::EOpAtomicAnd:
2263 case glslang::EOpAtomicOr:
2264 case glslang::EOpAtomicXor:
2265 case glslang::EOpAtomicExchange:
2266 case glslang::EOpAtomicCompSwap:
2267 atomic = true;
2268 break;
2269
John Kessenich0d0c6d32017-07-23 16:08:26 -06002270 case glslang::EOpAtomicCounterAdd:
2271 case glslang::EOpAtomicCounterSubtract:
2272 case glslang::EOpAtomicCounterMin:
2273 case glslang::EOpAtomicCounterMax:
2274 case glslang::EOpAtomicCounterAnd:
2275 case glslang::EOpAtomicCounterOr:
2276 case glslang::EOpAtomicCounterXor:
2277 case glslang::EOpAtomicCounterExchange:
2278 case glslang::EOpAtomicCounterCompSwap:
2279 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2280 builder.addCapability(spv::CapabilityAtomicStorageOps);
2281 atomic = true;
2282 break;
2283
Chao Chen3c366992018-09-19 11:41:59 -07002284#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07002285 case glslang::EOpIgnoreIntersectionNV:
2286 case glslang::EOpTerminateRayNV:
2287 case glslang::EOpTraceNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07002288 case glslang::EOpExecuteCallableNV:
Chao Chen3c366992018-09-19 11:41:59 -07002289 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
2290 noReturnValue = true;
2291 break;
2292#endif
2293
John Kessenich140f3df2015-06-26 16:58:36 -06002294 default:
2295 break;
2296 }
2297
2298 //
2299 // See if it maps to a regular operation.
2300 //
John Kessenich140f3df2015-06-26 16:58:36 -06002301 if (binOp != glslang::EOpNull) {
2302 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2303 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2304 assert(left && right);
2305
2306 builder.clearAccessChain();
2307 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002308 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002309
2310 builder.clearAccessChain();
2311 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002312 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002313
John Kesseniche485c7a2017-05-31 18:50:53 -06002314 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06002315 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002316 TranslateNoContractionDecoration(node->getType().getQualifier()),
2317 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002318 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002319 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002320 left->getType().getBasicType(), reduceComparison);
2321
2322 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002323 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002324 builder.clearAccessChain();
2325 builder.setAccessChainRValue(result);
2326
2327 return false;
2328 }
2329
John Kessenich426394d2015-07-23 10:22:48 -06002330 //
2331 // Create the list of operands.
2332 //
John Kessenich140f3df2015-06-26 16:58:36 -06002333 glslang::TIntermSequence& glslangOperands = node->getSequence();
2334 std::vector<spv::Id> operands;
2335 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002336 // special case l-value operands; there are just a few
2337 bool lvalue = false;
2338 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002339 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002340 case glslang::EOpModf:
2341 if (arg == 1)
2342 lvalue = true;
2343 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002344 case glslang::EOpInterpolateAtSample:
2345 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002346#ifdef AMD_EXTENSIONS
2347 case glslang::EOpInterpolateAtVertex:
2348#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002349 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002350 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002351
2352 // Does it need a swizzle inversion? If so, evaluation is inverted;
2353 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002354 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002355 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2356 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2357 }
Rex Xu7a26c172015-12-08 17:12:09 +08002358 break;
Rex Xud4782c12015-09-06 16:30:11 +08002359 case glslang::EOpAtomicAdd:
2360 case glslang::EOpAtomicMin:
2361 case glslang::EOpAtomicMax:
2362 case glslang::EOpAtomicAnd:
2363 case glslang::EOpAtomicOr:
2364 case glslang::EOpAtomicXor:
2365 case glslang::EOpAtomicExchange:
2366 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002367 case glslang::EOpAtomicLoad:
2368 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002369 case glslang::EOpAtomicCounterAdd:
2370 case glslang::EOpAtomicCounterSubtract:
2371 case glslang::EOpAtomicCounterMin:
2372 case glslang::EOpAtomicCounterMax:
2373 case glslang::EOpAtomicCounterAnd:
2374 case glslang::EOpAtomicCounterOr:
2375 case glslang::EOpAtomicCounterXor:
2376 case glslang::EOpAtomicCounterExchange:
2377 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002378 if (arg == 0)
2379 lvalue = true;
2380 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002381 case glslang::EOpAddCarry:
2382 case glslang::EOpSubBorrow:
2383 if (arg == 2)
2384 lvalue = true;
2385 break;
2386 case glslang::EOpUMulExtended:
2387 case glslang::EOpIMulExtended:
2388 if (arg >= 2)
2389 lvalue = true;
2390 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002391 default:
2392 break;
2393 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002394 builder.clearAccessChain();
2395 if (invertedType != spv::NoType && arg == 0)
2396 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2397 else
2398 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002399 if (lvalue)
2400 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002401 else {
2402 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002403 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002404 }
John Kessenich140f3df2015-06-26 16:58:36 -06002405 }
John Kessenich426394d2015-07-23 10:22:48 -06002406
John Kesseniche485c7a2017-05-31 18:50:53 -06002407 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002408 if (atomic) {
2409 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002410 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002411 } else {
2412 // Pass through to generic operations.
2413 switch (glslangOperands.size()) {
2414 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002415 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002416 break;
2417 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002418 {
2419 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002420 TranslateNoContractionDecoration(node->getType().getQualifier()),
2421 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002422 result = createUnaryOperation(
2423 node->getOp(), decorations,
2424 resultType(), operands.front(),
2425 glslangOperands[0]->getAsTyped()->getBasicType());
2426 }
John Kessenich426394d2015-07-23 10:22:48 -06002427 break;
2428 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002429 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002430 break;
2431 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002432 if (invertedType)
2433 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002434 }
2435
2436 if (noReturnValue)
2437 return false;
2438
2439 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002440 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002441 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002442 } else {
2443 builder.clearAccessChain();
2444 builder.setAccessChainRValue(result);
2445 return false;
2446 }
2447}
2448
John Kessenich433e9ff2017-01-26 20:31:11 -07002449// This path handles both if-then-else and ?:
2450// The if-then-else has a node type of void, while
2451// ?: has either a void or a non-void node type
2452//
2453// Leaving the result, when not void:
2454// GLSL only has r-values as the result of a :?, but
2455// if we have an l-value, that can be more efficient if it will
2456// become the base of a complex r-value expression, because the
2457// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002458bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2459{
John Kessenich4bee5312018-02-20 21:29:05 -07002460 // See if it simple and safe, or required, to execute both sides.
2461 // Crucially, side effects must be either semantically required or avoided,
2462 // and there are performance trade-offs.
2463 // Return true if required or a good idea (and safe) to execute both sides,
2464 // false otherwise.
2465 const auto bothSidesPolicy = [&]() -> bool {
2466 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002467 if (node->getTrueBlock() == nullptr ||
2468 node->getFalseBlock() == nullptr)
2469 return false;
2470
John Kessenich4bee5312018-02-20 21:29:05 -07002471 // required? (unless we write additional code to look for side effects
2472 // and make performance trade-offs if none are present)
2473 if (!node->getShortCircuit())
2474 return true;
2475
2476 // if not required to execute both, decide based on performance/practicality...
2477
2478 // see if OpSelect can handle it
2479 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2480 node->getBasicType() == glslang::EbtVoid)
2481 return false;
2482
John Kessenich433e9ff2017-01-26 20:31:11 -07002483 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2484 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2485
2486 // return true if a single operand to ? : is okay for OpSelect
2487 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002488 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002489 };
2490
2491 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2492 operandOkay(node->getFalseBlock()->getAsTyped());
2493 };
2494
John Kessenich4bee5312018-02-20 21:29:05 -07002495 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2496 // emit the condition before doing anything with selection
2497 node->getCondition()->traverse(this);
2498 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2499
2500 // Find a way of executing both sides and selecting the right result.
2501 const auto executeBothSides = [&]() -> void {
2502 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002503 node->getTrueBlock()->traverse(this);
2504 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2505 node->getFalseBlock()->traverse(this);
2506 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2507
John Kesseniche485c7a2017-05-31 18:50:53 -06002508 builder.setLine(node->getLoc().line);
2509
John Kessenich4bee5312018-02-20 21:29:05 -07002510 // done if void
2511 if (node->getBasicType() == glslang::EbtVoid)
2512 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002513
John Kessenich4bee5312018-02-20 21:29:05 -07002514 // emit code to select between trueValue and falseValue
2515
2516 // see if OpSelect can handle it
2517 if (node->getType().isScalar() || node->getType().isVector()) {
2518 // Emit OpSelect for this selection.
2519
2520 // smear condition to vector, if necessary (AST is always scalar)
2521 if (builder.isVector(trueValue))
2522 condition = builder.smearScalar(spv::NoPrecision, condition,
2523 builder.makeVectorType(builder.makeBoolType(),
2524 builder.getNumComponents(trueValue)));
2525
2526 // OpSelect
2527 result = builder.createTriOp(spv::OpSelect,
2528 convertGlslangToSpvType(node->getType()), condition,
2529 trueValue, falseValue);
2530
2531 builder.clearAccessChain();
2532 builder.setAccessChainRValue(result);
2533 } else {
2534 // We need control flow to select the result.
2535 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2536 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2537
2538 // Selection control:
2539 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2540
2541 // make an "if" based on the value created by the condition
2542 spv::Builder::If ifBuilder(condition, control, builder);
2543
2544 // emit the "then" statement
2545 builder.createStore(trueValue, result);
2546 ifBuilder.makeBeginElse();
2547 // emit the "else" statement
2548 builder.createStore(falseValue, result);
2549
2550 // finish off the control flow
2551 ifBuilder.makeEndIf();
2552
2553 builder.clearAccessChain();
2554 builder.setAccessChainLValue(result);
2555 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002556 };
2557
John Kessenich4bee5312018-02-20 21:29:05 -07002558 // Execute the one side needed, as per the condition
2559 const auto executeOneSide = [&]() {
2560 // Always emit control flow.
2561 if (node->getBasicType() != glslang::EbtVoid)
2562 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002563
John Kessenich4bee5312018-02-20 21:29:05 -07002564 // Selection control:
2565 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2566
2567 // make an "if" based on the value created by the condition
2568 spv::Builder::If ifBuilder(condition, control, builder);
2569
2570 // emit the "then" statement
2571 if (node->getTrueBlock() != nullptr) {
2572 node->getTrueBlock()->traverse(this);
2573 if (result != spv::NoResult)
2574 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2575 }
2576
2577 if (node->getFalseBlock() != nullptr) {
2578 ifBuilder.makeBeginElse();
2579 // emit the "else" statement
2580 node->getFalseBlock()->traverse(this);
2581 if (result != spv::NoResult)
2582 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2583 }
2584
2585 // finish off the control flow
2586 ifBuilder.makeEndIf();
2587
2588 if (result != spv::NoResult) {
2589 builder.clearAccessChain();
2590 builder.setAccessChainLValue(result);
2591 }
2592 };
2593
2594 // Try for OpSelect (or a requirement to execute both sides)
2595 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002596 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2597 if (node->getType().getQualifier().isSpecConstant())
2598 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002599 executeBothSides();
2600 } else
2601 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002602
2603 return false;
2604}
2605
2606bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2607{
2608 // emit and get the condition before doing anything with switch
2609 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002610 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002611
Rex Xu57e65922017-07-04 23:23:40 +08002612 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002613 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002614
John Kessenich140f3df2015-06-26 16:58:36 -06002615 // browse the children to sort out code segments
2616 int defaultSegment = -1;
2617 std::vector<TIntermNode*> codeSegments;
2618 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2619 std::vector<int> caseValues;
2620 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2621 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2622 TIntermNode* child = *c;
2623 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002624 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002625 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002626 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002627 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2628 } else
2629 codeSegments.push_back(child);
2630 }
2631
qining25262b32016-05-06 17:25:16 -04002632 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002633 // statements between the last case and the end of the switch statement
2634 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2635 (int)codeSegments.size() == defaultSegment)
2636 codeSegments.push_back(nullptr);
2637
2638 // make the switch statement
2639 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002640 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002641
2642 // emit all the code in the segments
2643 breakForLoop.push(false);
2644 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2645 builder.nextSwitchSegment(segmentBlocks, s);
2646 if (codeSegments[s])
2647 codeSegments[s]->traverse(this);
2648 else
2649 builder.addSwitchBreak();
2650 }
2651 breakForLoop.pop();
2652
2653 builder.endSwitch(segmentBlocks);
2654
2655 return false;
2656}
2657
2658void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2659{
2660 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002661 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002662
2663 builder.clearAccessChain();
2664 builder.setAccessChainRValue(constant);
2665}
2666
2667bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2668{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002669 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002670 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002671
2672 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002673 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2674 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002675
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002676 // Spec requires back edges to target header blocks, and every header block
2677 // must dominate its merge block. Make a header block first to ensure these
2678 // conditions are met. By definition, it will contain OpLoopMerge, followed
2679 // by a block-ending branch. But we don't want to put any other body/test
2680 // instructions in it, since the body/test may have arbitrary instructions,
2681 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002682 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002683 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002684 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002685 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002686 spv::Block& test = builder.makeNewBlock();
2687 builder.createBranch(&test);
2688
2689 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002690 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002691 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002692 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2693
2694 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002695 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002696 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002697 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002698 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002699 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002700
2701 builder.setBuildPoint(&blocks.continue_target);
2702 if (node->getTerminal())
2703 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002704 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002705 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002706 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002707 builder.createBranch(&blocks.body);
2708
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002709 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002710 builder.setBuildPoint(&blocks.body);
2711 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002712 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002713 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002714 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002715
2716 builder.setBuildPoint(&blocks.continue_target);
2717 if (node->getTerminal())
2718 node->getTerminal()->traverse(this);
2719 if (node->getTest()) {
2720 node->getTest()->traverse(this);
2721 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002722 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002723 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002724 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002725 // TODO: unless there was a break/return/discard instruction
2726 // somewhere in the body, this is an infinite loop, so we should
2727 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002728 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002729 }
John Kessenich140f3df2015-06-26 16:58:36 -06002730 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002731 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002732 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002733 return false;
2734}
2735
2736bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2737{
2738 if (node->getExpression())
2739 node->getExpression()->traverse(this);
2740
John Kesseniche485c7a2017-05-31 18:50:53 -06002741 builder.setLine(node->getLoc().line);
2742
John Kessenich140f3df2015-06-26 16:58:36 -06002743 switch (node->getFlowOp()) {
2744 case glslang::EOpKill:
2745 builder.makeDiscard();
2746 break;
2747 case glslang::EOpBreak:
2748 if (breakForLoop.top())
2749 builder.createLoopExit();
2750 else
2751 builder.addSwitchBreak();
2752 break;
2753 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002754 builder.createLoopContinue();
2755 break;
2756 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002757 if (node->getExpression()) {
2758 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2759 spv::Id returnId = accessChainLoad(glslangReturnType);
2760 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2761 builder.clearAccessChain();
2762 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2763 builder.setAccessChainLValue(copyId);
2764 multiTypeStore(glslangReturnType, returnId);
2765 returnId = builder.createLoad(copyId);
2766 }
2767 builder.makeReturn(false, returnId);
2768 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002769 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002770
2771 builder.clearAccessChain();
2772 break;
2773
2774 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002775 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002776 break;
2777 }
2778
2779 return false;
2780}
2781
2782spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2783{
qining25262b32016-05-06 17:25:16 -04002784 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002785 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002786 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002787 if (node->getQualifier().isConstant()) {
Dan Sinclair12fcaa22018-11-13 09:17:44 -05002788 spv::Id result = createSpvConstant(*node);
2789 if (result != spv::NoResult)
2790 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06002791 }
2792
2793 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002794 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002795 spv::Id spvType = convertGlslangToSpvType(node->getType());
2796
Rex Xucabbb782017-03-24 13:41:14 +08002797 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2798 node->getType().containsBasicType(glslang::EbtInt16) ||
2799 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002800 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002801 switch (storageClass) {
2802 case spv::StorageClassInput:
2803 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002804 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002805 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002806 break;
2807 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002808 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002809 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002810 break;
2811 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002812 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002813 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2814 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002815 else
2816 builder.addCapability(spv::CapabilityStorageUniform16);
2817 break;
2818 case spv::StorageClassStorageBuffer:
2819 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2820 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2821 break;
2822 default:
2823 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002824 }
2825 }
Rex Xuf89ad982017-04-07 23:22:33 +08002826
John Kessenich312dcfb2018-07-03 13:19:51 -06002827 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2828 node->getType().containsBasicType(glslang::EbtUint8);
2829 if (contains8BitType) {
2830 if (storageClass == spv::StorageClassPushConstant) {
2831 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2832 builder.addCapability(spv::CapabilityStoragePushConstant8);
2833 } else if (storageClass == spv::StorageClassUniform) {
2834 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2835 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
Neil Henningb6b01f02018-10-23 15:02:29 +01002836 } else if (storageClass == spv::StorageClassStorageBuffer) {
2837 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2838 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
John Kessenich312dcfb2018-07-03 13:19:51 -06002839 }
2840 }
2841
John Kessenich140f3df2015-06-26 16:58:36 -06002842 const char* name = node->getName().c_str();
2843 if (glslang::IsAnonymous(name))
2844 name = "";
2845
2846 return builder.createVariable(storageClass, spvType, name);
2847}
2848
2849// Return type Id of the sampled type.
2850spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2851{
2852 switch (sampler.type) {
2853 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002854#ifdef AMD_EXTENSIONS
2855 case glslang::EbtFloat16:
2856 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2857 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2858 return builder.makeFloatType(16);
2859#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002860 case glslang::EbtInt: return builder.makeIntType(32);
2861 case glslang::EbtUint: return builder.makeUintType(32);
2862 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002863 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002864 return builder.makeFloatType(32);
2865 }
2866}
2867
John Kessenich8c8505c2016-07-26 12:50:38 -06002868// If node is a swizzle operation, return the type that should be used if
2869// the swizzle base is first consumed by another operation, before the swizzle
2870// is applied.
2871spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2872{
John Kessenichecba76f2017-01-06 00:34:48 -07002873 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002874 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2875 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2876 else
2877 return spv::NoType;
2878}
2879
2880// When inverting a swizzle with a parent op, this function
2881// will apply the swizzle operation to a completed parent operation.
2882spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2883{
2884 std::vector<unsigned> swizzle;
2885 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2886 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2887}
2888
John Kessenich8c8505c2016-07-26 12:50:38 -06002889// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2890void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2891{
2892 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2893 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2894 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2895}
2896
John Kessenich3ac051e2015-12-20 11:29:16 -07002897// Convert from a glslang type to an SPV type, by calling into a
2898// recursive version of this function. This establishes the inherited
2899// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002900spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2901{
John Kessenichead86222018-03-28 18:01:20 -06002902 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002903}
2904
2905// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002906// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002907// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002908spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2909 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002910{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002911 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002912
2913 switch (type.getBasicType()) {
2914 case glslang::EbtVoid:
2915 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002916 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002917 break;
2918 case glslang::EbtFloat:
2919 spvType = builder.makeFloatType(32);
2920 break;
2921 case glslang::EbtDouble:
2922 spvType = builder.makeFloatType(64);
2923 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002924 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002925 spvType = builder.makeFloatType(16);
2926 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002927 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002928 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2929 // a 32-bit int where non-0 means true.
2930 if (explicitLayout != glslang::ElpNone)
2931 spvType = builder.makeUintType(32);
2932 else
2933 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002934 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002935 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07002936 spvType = builder.makeIntType(8);
2937 break;
2938 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07002939 spvType = builder.makeUintType(8);
2940 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002941 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07002942 spvType = builder.makeIntType(16);
2943 break;
2944 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07002945 spvType = builder.makeUintType(16);
2946 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002947 case glslang::EbtInt:
2948 spvType = builder.makeIntType(32);
2949 break;
2950 case glslang::EbtUint:
2951 spvType = builder.makeUintType(32);
2952 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002953 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002954 spvType = builder.makeIntType(64);
2955 break;
2956 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002957 spvType = builder.makeUintType(64);
2958 break;
John Kessenich426394d2015-07-23 10:22:48 -06002959 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002960 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002961 spvType = builder.makeUintType(32);
2962 break;
Chao Chenb50c02e2018-09-19 11:42:24 -07002963#ifdef NV_EXTENSIONS
2964 case glslang::EbtAccStructNV:
2965 spvType = builder.makeAccelerationStructureNVType();
2966 break;
2967#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002968 case glslang::EbtSampler:
2969 {
2970 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002971 if (sampler.sampler) {
2972 // pure sampler
2973 spvType = builder.makeSamplerType();
2974 } else {
2975 // an image is present, make its type
2976 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2977 sampler.image ? 2 : 1, TranslateImageFormat(type));
2978 if (sampler.combined) {
2979 // already has both image and sampler, make the combined type
2980 spvType = builder.makeSampledImageType(spvType);
2981 }
John Kessenich55e7d112015-11-15 21:33:39 -07002982 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002983 }
John Kessenich140f3df2015-06-26 16:58:36 -06002984 break;
2985 case glslang::EbtStruct:
2986 case glslang::EbtBlock:
2987 {
2988 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002989 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002990
2991 // Try to share structs for different layouts, but not yet for other
2992 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002993 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002994 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002995 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002996 break;
2997
2998 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002999 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06003000 memberRemapper[glslangMembers].resize(glslangMembers->size());
3001 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06003002 }
3003 break;
3004 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003005 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003006 break;
3007 }
3008
3009 if (type.isMatrix())
3010 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
3011 else {
3012 // If this variable has a vector element count greater than 1, create a SPIR-V vector
3013 if (type.getVectorSize() > 1)
3014 spvType = builder.makeVectorType(spvType, type.getVectorSize());
3015 }
3016
3017 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003018 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
3019
John Kessenichc9a80832015-09-12 12:17:44 -06003020 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07003021 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07003022 // We need to decorate array strides for types needing explicit layout, except blocks.
3023 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07003024 // Use a dummy glslang type for querying internal strides of
3025 // arrays of arrays, but using just a one-dimensional array.
3026 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06003027 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
3028 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07003029
3030 // Will compute the higher-order strides here, rather than making a whole
3031 // pile of types and doing repetitive recursion on their contents.
3032 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
3033 }
John Kessenichf8842e52016-01-04 19:22:56 -07003034
3035 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07003036 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07003037 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07003038 if (stride > 0)
3039 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07003040 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07003041 }
3042 } else {
3043 // single-dimensional array, and don't yet have stride
3044
John Kessenichf8842e52016-01-04 19:22:56 -07003045 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07003046 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
3047 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06003048 }
John Kessenich31ed4832015-09-09 17:51:38 -06003049
John Kessenichead86222018-03-28 18:01:20 -06003050 // Do the outer dimension, which might not be known for a runtime-sized array.
3051 // (Unsized arrays that survive through linking will be runtime-sized arrays)
3052 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07003053 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06003054 else {
3055 if (!lastBufferBlockMember) {
3056 builder.addExtension("SPV_EXT_descriptor_indexing");
3057 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
3058 }
John Kessenichead86222018-03-28 18:01:20 -06003059 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06003060 }
John Kessenichc9e0a422015-12-29 21:27:24 -07003061 if (stride > 0)
3062 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06003063 }
3064
3065 return spvType;
3066}
3067
John Kessenich0e737842017-03-24 18:38:16 -06003068// TODO: this functionality should exist at a higher level, in creating the AST
3069//
3070// Identify interface members that don't have their required extension turned on.
3071//
3072bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
3073{
Chao Chen3c366992018-09-19 11:41:59 -07003074#ifdef NV_EXTENSIONS
John Kessenich0e737842017-03-24 18:38:16 -06003075 auto& extensions = glslangIntermediate->getRequestedExtensions();
3076
Rex Xubcf291a2017-03-29 23:01:36 +08003077 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
3078 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3079 return true;
John Kessenich0e737842017-03-24 18:38:16 -06003080 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
3081 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
3082 return true;
Chao Chen3c366992018-09-19 11:41:59 -07003083
3084 if (glslangIntermediate->getStage() != EShLangMeshNV) {
3085 if (member.getFieldName() == "gl_ViewportMask" &&
3086 extensions.find("GL_NV_viewport_array2") == extensions.end())
3087 return true;
3088 if (member.getFieldName() == "gl_PositionPerViewNV" &&
3089 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3090 return true;
3091 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
3092 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
3093 return true;
3094 }
3095#endif
John Kessenich0e737842017-03-24 18:38:16 -06003096
3097 return false;
3098};
3099
John Kessenich6090df02016-06-30 21:18:02 -06003100// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
3101// explicitLayout can be kept the same throughout the hierarchical recursive walk.
3102// Mutually recursive with convertGlslangToSpvType().
3103spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
3104 const glslang::TTypeList* glslangMembers,
3105 glslang::TLayoutPacking explicitLayout,
3106 const glslang::TQualifier& qualifier)
3107{
3108 // Create a vector of struct types for SPIR-V to consume
3109 std::vector<spv::Id> spvMembers;
3110 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 -06003111 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3112 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3113 if (glslangMember.hiddenMember()) {
3114 ++memberDelta;
3115 if (type.getBasicType() == glslang::EbtBlock)
3116 memberRemapper[glslangMembers][i] = -1;
3117 } else {
John Kessenich0e737842017-03-24 18:38:16 -06003118 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003119 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06003120 if (filterMember(glslangMember))
3121 continue;
3122 }
John Kessenich6090df02016-06-30 21:18:02 -06003123 // modify just this child's view of the qualifier
3124 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3125 InheritQualifiers(memberQualifier, qualifier);
3126
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003127 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06003128 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06003129 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06003130
3131 // recurse
John Kessenichead86222018-03-28 18:01:20 -06003132 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
3133 i == (int)glslangMembers->size() - 1;
3134 spvMembers.push_back(
3135 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06003136 }
3137 }
3138
3139 // Make the SPIR-V type
3140 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06003141 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06003142 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
3143
3144 // Decorate it
3145 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
3146
3147 return spvType;
3148}
3149
3150void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
3151 const glslang::TTypeList* glslangMembers,
3152 glslang::TLayoutPacking explicitLayout,
3153 const glslang::TQualifier& qualifier,
3154 spv::Id spvType)
3155{
3156 // Name and decorate the non-hidden members
3157 int offset = -1;
3158 int locationOffset = 0; // for use within the members of this struct
3159 for (int i = 0; i < (int)glslangMembers->size(); i++) {
3160 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
3161 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06003162 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06003163 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06003164 if (filterMember(glslangMember))
3165 continue;
3166 }
John Kessenich6090df02016-06-30 21:18:02 -06003167
3168 // modify just this child's view of the qualifier
3169 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
3170 InheritQualifiers(memberQualifier, qualifier);
3171
3172 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07003173 if (member < 0)
3174 continue;
3175
3176 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
3177 builder.addMemberDecoration(spvType, member,
3178 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
3179 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
3180 // Add interpolation and auxiliary storage decorations only to
3181 // top-level members of Input and Output storage classes
3182 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
3183 type.getQualifier().storage == glslang::EvqVaryingOut) {
3184 if (type.getBasicType() == glslang::EbtBlock ||
3185 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3186 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3187 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
Chao Chen3c366992018-09-19 11:41:59 -07003188#ifdef NV_EXTENSIONS
3189 addMeshNVDecoration(spvType, member, memberQualifier);
3190#endif
John Kessenich6090df02016-06-30 21:18:02 -06003191 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003192 }
3193 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003194
John Kessenich5d610ee2018-03-07 18:05:55 -07003195 if (type.getBasicType() == glslang::EbtBlock &&
3196 qualifier.storage == glslang::EvqBuffer) {
3197 // Add memory decorations only to top-level members of shader storage block
3198 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003199 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003200 for (unsigned int i = 0; i < memory.size(); ++i)
3201 builder.addMemberDecoration(spvType, member, memory[i]);
3202 }
John Kessenich6090df02016-06-30 21:18:02 -06003203
John Kessenich5d610ee2018-03-07 18:05:55 -07003204 // Location assignment was already completed correctly by the front end,
3205 // just track whether a member needs to be decorated.
3206 // Ignore member locations if the container is an array, as that's
3207 // ill-specified and decisions have been made to not allow this.
3208 if (! type.isArray() && memberQualifier.hasLocation())
3209 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003210
John Kessenich5d610ee2018-03-07 18:05:55 -07003211 if (qualifier.hasLocation()) // track for upcoming inheritance
3212 locationOffset += glslangIntermediate->computeTypeLocationSize(
3213 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003214
John Kessenich5d610ee2018-03-07 18:05:55 -07003215 // component, XFB, others
3216 if (glslangMember.getQualifier().hasComponent())
3217 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3218 glslangMember.getQualifier().layoutComponent);
3219 if (glslangMember.getQualifier().hasXfbOffset())
3220 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3221 glslangMember.getQualifier().layoutXfbOffset);
3222 else if (explicitLayout != glslang::ElpNone) {
3223 // figure out what to do with offset, which is accumulating
3224 int nextOffset;
3225 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3226 if (offset >= 0)
3227 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3228 offset = nextOffset;
3229 }
John Kessenich6090df02016-06-30 21:18:02 -06003230
John Kessenich5d610ee2018-03-07 18:05:55 -07003231 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3232 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3233 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003234
John Kessenich5d610ee2018-03-07 18:05:55 -07003235 // built-in variable decorations
3236 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3237 if (builtIn != spv::BuiltInMax)
3238 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003239
John Kessenich5611c6d2018-04-05 11:25:02 -06003240 // nonuniform
3241 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3242
John Kessenichead86222018-03-28 18:01:20 -06003243 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3244 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3245 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3246 memberQualifier.semanticName);
3247 }
3248
chaoc771d89f2017-01-13 01:10:53 -08003249#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003250 if (builtIn == spv::BuiltInLayer) {
3251 // SPV_NV_viewport_array2 extension
3252 if (glslangMember.getQualifier().layoutViewportRelative){
3253 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3254 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3255 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003256 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003257 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3258 builder.addMemberDecoration(spvType, member,
3259 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3260 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3261 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3262 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003263 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003264 }
3265 if (glslangMember.getQualifier().layoutPassthrough) {
3266 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3267 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3268 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3269 }
chaoc771d89f2017-01-13 01:10:53 -08003270#endif
John Kessenich6090df02016-06-30 21:18:02 -06003271 }
3272
3273 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003274 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3275 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003276 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
3277 builder.addCapability(spv::CapabilityGeometryStreams);
3278 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
3279 }
John Kessenich6090df02016-06-30 21:18:02 -06003280}
3281
John Kessenich6c292d32016-02-15 20:58:50 -07003282// Turn the expression forming the array size into an id.
3283// This is not quite trivial, because of specialization constants.
3284// Sometimes, a raw constant is turned into an Id, and sometimes
3285// a specialization constant expression is.
3286spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3287{
3288 // First, see if this is sized with a node, meaning a specialization constant:
3289 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3290 if (specNode != nullptr) {
3291 builder.clearAccessChain();
3292 specNode->traverse(this);
3293 return accessChainLoad(specNode->getAsTyped()->getType());
3294 }
qining25262b32016-05-06 17:25:16 -04003295
John Kessenich6c292d32016-02-15 20:58:50 -07003296 // Otherwise, need a compile-time (front end) size, get it:
3297 int size = arraySizes.getDimSize(dim);
3298 assert(size > 0);
3299 return builder.makeUintConstant(size);
3300}
3301
John Kessenich103bef92016-02-08 21:38:15 -07003302// Wrap the builder's accessChainLoad to:
3303// - localize handling of RelaxedPrecision
3304// - use the SPIR-V inferred type instead of another conversion of the glslang type
3305// (avoids unnecessary work and possible type punning for structures)
3306// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003307spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3308{
John Kessenich103bef92016-02-08 21:38:15 -07003309 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003310
3311 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3312 coherentFlags |= TranslateCoherent(type);
3313
John Kessenich5611c6d2018-04-05 11:25:02 -06003314 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003315 TranslateNonUniformDecoration(type.getQualifier()),
3316 nominalTypeId,
3317 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
3318 TranslateMemoryScope(coherentFlags));
John Kessenich103bef92016-02-08 21:38:15 -07003319
3320 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003321 if (type.getBasicType() == glslang::EbtBool) {
3322 if (builder.isScalarType(nominalTypeId)) {
3323 // Conversion for bool
3324 spv::Id boolType = builder.makeBoolType();
3325 if (nominalTypeId != boolType)
3326 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3327 } else if (builder.isVectorType(nominalTypeId)) {
3328 // Conversion for bvec
3329 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3330 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3331 if (nominalTypeId != bvecType)
3332 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3333 }
3334 }
John Kessenich103bef92016-02-08 21:38:15 -07003335
3336 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003337}
3338
Rex Xu27253232016-02-23 17:51:09 +08003339// Wrap the builder's accessChainStore to:
3340// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003341//
3342// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003343void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3344{
3345 // Need to convert to abstract types when necessary
3346 if (type.getBasicType() == glslang::EbtBool) {
3347 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3348
3349 if (builder.isScalarType(nominalTypeId)) {
3350 // Conversion for bool
3351 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003352 if (nominalTypeId != boolType) {
3353 // keep these outside arguments, for determinant order-of-evaluation
3354 spv::Id one = builder.makeUintConstant(1);
3355 spv::Id zero = builder.makeUintConstant(0);
3356 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3357 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003358 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003359 } else if (builder.isVectorType(nominalTypeId)) {
3360 // Conversion for bvec
3361 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3362 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003363 if (nominalTypeId != bvecType) {
3364 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003365 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3366 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3367 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003368 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003369 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3370 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003371 }
3372 }
3373
Jeff Bolz36831c92018-09-05 10:11:41 -05003374 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3375 coherentFlags |= TranslateCoherent(type);
3376
3377 builder.accessChainStore(rvalue,
3378 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
3379 TranslateMemoryScope(coherentFlags));
Rex Xu27253232016-02-23 17:51:09 +08003380}
3381
John Kessenich4bf71552016-09-02 11:20:21 -06003382// For storing when types match at the glslang level, but not might match at the
3383// SPIR-V level.
3384//
3385// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003386// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003387// as in a member-decorated way.
3388//
3389// NOTE: This function can handle any store request; if it's not special it
3390// simplifies to a simple OpStore.
3391//
3392// Implicitly uses the existing builder.accessChain as the storage target.
3393void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3394{
John Kessenichb3e24e42016-09-11 12:33:43 -06003395 // we only do the complex path here if it's an aggregate
3396 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003397 accessChainStore(type, rValue);
3398 return;
3399 }
3400
John Kessenichb3e24e42016-09-11 12:33:43 -06003401 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003402 spv::Id rType = builder.getTypeId(rValue);
3403 spv::Id lValue = builder.accessChainGetLValue();
3404 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3405 if (lType == rType) {
3406 accessChainStore(type, rValue);
3407 return;
3408 }
3409
John Kessenichb3e24e42016-09-11 12:33:43 -06003410 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003411 // where the two types were the same type in GLSL. This requires member
3412 // by member copy, recursively.
3413
John Kessenichb3e24e42016-09-11 12:33:43 -06003414 // If an array, copy element by element.
3415 if (type.isArray()) {
3416 glslang::TType glslangElementType(type, 0);
3417 spv::Id elementRType = builder.getContainedTypeId(rType);
3418 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3419 // get the source member
3420 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003421
John Kessenichb3e24e42016-09-11 12:33:43 -06003422 // set up the target storage
3423 builder.clearAccessChain();
3424 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003425 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type));
John Kessenich4bf71552016-09-02 11:20:21 -06003426
John Kessenichb3e24e42016-09-11 12:33:43 -06003427 // store the member
3428 multiTypeStore(glslangElementType, elementRValue);
3429 }
3430 } else {
3431 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003432
John Kessenichb3e24e42016-09-11 12:33:43 -06003433 // loop over structure members
3434 const glslang::TTypeList& members = *type.getStruct();
3435 for (int m = 0; m < (int)members.size(); ++m) {
3436 const glslang::TType& glslangMemberType = *members[m].type;
3437
3438 // get the source member
3439 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3440 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3441
3442 // set up the target storage
3443 builder.clearAccessChain();
3444 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003445 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type));
John Kessenichb3e24e42016-09-11 12:33:43 -06003446
3447 // store the member
3448 multiTypeStore(glslangMemberType, memberRValue);
3449 }
John Kessenich4bf71552016-09-02 11:20:21 -06003450 }
3451}
3452
John Kessenichf85e8062015-12-19 13:57:10 -07003453// Decide whether or not this type should be
3454// decorated with offsets and strides, and if so
3455// whether std140 or std430 rules should be applied.
3456glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003457{
John Kessenichf85e8062015-12-19 13:57:10 -07003458 // has to be a block
3459 if (type.getBasicType() != glslang::EbtBlock)
3460 return glslang::ElpNone;
3461
Chao Chen3c366992018-09-19 11:41:59 -07003462 // has to be a uniform or buffer block or task in/out blocks
John Kessenichf85e8062015-12-19 13:57:10 -07003463 if (type.getQualifier().storage != glslang::EvqUniform &&
Chao Chen3c366992018-09-19 11:41:59 -07003464 type.getQualifier().storage != glslang::EvqBuffer &&
3465 !type.getQualifier().isTaskMemory())
John Kessenichf85e8062015-12-19 13:57:10 -07003466 return glslang::ElpNone;
3467
3468 // return the layout to use
3469 switch (type.getQualifier().layoutPacking) {
3470 case glslang::ElpStd140:
3471 case glslang::ElpStd430:
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003472 case glslang::ElpScalar:
John Kessenichf85e8062015-12-19 13:57:10 -07003473 return type.getQualifier().layoutPacking;
3474 default:
3475 return glslang::ElpNone;
3476 }
John Kessenich31ed4832015-09-09 17:51:38 -06003477}
3478
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003479// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003480int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003481{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003482 int size;
John Kessenich49987892015-12-29 17:11:44 -07003483 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003484 glslangIntermediate->getMemberAlignment(arrayType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003485
3486 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003487}
3488
John Kessenich49987892015-12-29 17:11:44 -07003489// 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 -07003490// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003491int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003492{
John Kessenich49987892015-12-29 17:11:44 -07003493 glslang::TType elementType;
3494 elementType.shallowCopy(matrixType);
3495 elementType.clearArraySizes();
3496
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003497 int size;
John Kessenich49987892015-12-29 17:11:44 -07003498 int stride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003499 glslangIntermediate->getMemberAlignment(elementType, size, stride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich49987892015-12-29 17:11:44 -07003500
3501 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003502}
3503
John Kessenich5e4b1242015-08-06 22:53:06 -06003504// Given a member type of a struct, realign the current offset for it, and compute
3505// the next (not yet aligned) offset for the next member, which will get aligned
3506// on the next call.
3507// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3508// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3509// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003510void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003511 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003512{
3513 // this will get a positive value when deemed necessary
3514 nextOffset = -1;
3515
John Kessenich5e4b1242015-08-06 22:53:06 -06003516 // override anything in currentOffset with user-set offset
3517 if (memberType.getQualifier().hasOffset())
3518 currentOffset = memberType.getQualifier().layoutOffset;
3519
3520 // It could be that current linker usage in glslang updated all the layoutOffset,
3521 // in which case the following code does not matter. But, that's not quite right
3522 // once cross-compilation unit GLSL validation is done, as the original user
3523 // settings are needed in layoutOffset, and then the following will come into play.
3524
John Kessenichf85e8062015-12-19 13:57:10 -07003525 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003526 if (! memberType.getQualifier().hasOffset())
3527 currentOffset = -1;
3528
3529 return;
3530 }
3531
John Kessenichf85e8062015-12-19 13:57:10 -07003532 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003533 if (currentOffset < 0)
3534 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003535
John Kessenich5e4b1242015-08-06 22:53:06 -06003536 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3537 // but possibly not yet correctly aligned.
3538
3539 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003540 int dummyStride;
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003541 int memberAlignment = glslangIntermediate->getMemberAlignment(memberType, memberSize, dummyStride, explicitLayout, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003542
3543 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003544 // TODO: make this consistent in early phases of code:
3545 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3546 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3547 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003548 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003549 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003550 int dummySize;
3551 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3552 if (componentAlignment <= 4)
3553 memberAlignment = componentAlignment;
3554 }
3555
3556 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003557 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003558
3559 // Bump up to vec4 if there is a bad straddle
Jeff Bolz7da39ed2018-11-14 09:30:53 -06003560 if (explicitLayout != glslang::ElpScalar && glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
John Kessenich4f1403e2017-04-05 17:38:20 -06003561 glslang::RoundToPow2(currentOffset, 16);
3562
John Kessenich5e4b1242015-08-06 22:53:06 -06003563 nextOffset = currentOffset + memberSize;
3564}
3565
David Netoa901ffe2016-06-08 14:11:40 +01003566void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003567{
David Netoa901ffe2016-06-08 14:11:40 +01003568 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3569 switch (glslangBuiltIn)
3570 {
3571 case glslang::EbvClipDistance:
3572 case glslang::EbvCullDistance:
3573 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003574#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003575 case glslang::EbvViewportMaskNV:
3576 case glslang::EbvSecondaryPositionNV:
3577 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003578 case glslang::EbvPositionPerViewNV:
3579 case glslang::EbvViewportMaskPerViewNV:
Chao Chen3c366992018-09-19 11:41:59 -07003580 case glslang::EbvTaskCountNV:
3581 case glslang::EbvPrimitiveCountNV:
3582 case glslang::EbvPrimitiveIndicesNV:
3583 case glslang::EbvClipDistancePerViewNV:
3584 case glslang::EbvCullDistancePerViewNV:
3585 case glslang::EbvLayerPerViewNV:
3586 case glslang::EbvMeshViewCountNV:
3587 case glslang::EbvMeshViewIndicesNV:
chaoc771d89f2017-01-13 01:10:53 -08003588#endif
David Netoa901ffe2016-06-08 14:11:40 +01003589 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3590 // Alternately, we could just call this for any glslang built-in, since the
3591 // capability already guards against duplicates.
3592 TranslateBuiltInDecoration(glslangBuiltIn, false);
3593 break;
3594 default:
3595 // Capabilities were already generated when the struct was declared.
3596 break;
3597 }
John Kessenichebb50532016-05-16 19:22:05 -06003598}
3599
John Kessenich6fccb3c2016-09-19 16:01:41 -06003600bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003601{
John Kessenicheee9d532016-09-19 18:09:30 -06003602 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003603}
3604
John Kessenichd41993d2017-09-10 15:21:05 -06003605// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003606// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3607// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003608bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003609{
John Kessenich6a14f782017-12-04 02:48:10 -07003610 assert(qualifier == glslang::EvqIn ||
3611 qualifier == glslang::EvqOut ||
3612 qualifier == glslang::EvqInOut ||
3613 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003614 return qualifier != glslang::EvqConstReadOnly;
3615}
3616
3617// Is parameter pass-by-original?
3618bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3619 bool implicitThisParam)
3620{
3621 if (implicitThisParam) // implicit this
3622 return true;
3623 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003624 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003625 return paramType.containsOpaque() || // sampler, etc.
3626 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3627}
3628
John Kessenich140f3df2015-06-26 16:58:36 -06003629// Make all the functions, skeletally, without actually visiting their bodies.
3630void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3631{
Jeff Bolz36831c92018-09-05 10:11:41 -05003632 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003633 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3634 if (paramPrecision != spv::NoPrecision)
3635 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003636 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenichfad62972017-07-18 02:35:46 -06003637 };
3638
John Kessenich140f3df2015-06-26 16:58:36 -06003639 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3640 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003641 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003642 continue;
3643
3644 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003645 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003646 //
qining25262b32016-05-06 17:25:16 -04003647 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003648 // function. What it is an address of varies:
3649 //
John Kessenich4bf71552016-09-02 11:20:21 -06003650 // - "in" parameters not marked as "const" can be written to without modifying the calling
3651 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003652 //
3653 // - "const in" parameters can just be the r-value, as no writes need occur.
3654 //
John Kessenich4bf71552016-09-02 11:20:21 -06003655 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3656 // 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 -06003657
3658 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003659 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003660 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3661
John Kessenichfad62972017-07-18 02:35:46 -06003662 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3663 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003664
John Kessenichfad62972017-07-18 02:35:46 -06003665 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003666 for (int p = 0; p < (int)parameters.size(); ++p) {
3667 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3668 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003669 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003670 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003671 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003672 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3673 else
John Kessenich4bf71552016-09-02 11:20:21 -06003674 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003675 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003676 paramTypes.push_back(typeId);
3677 }
3678
3679 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003680 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3681 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003682 glslFunction->getName().c_str(), paramTypes,
3683 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003684 if (implicitThis)
3685 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003686
3687 // Track function to emit/call later
3688 functionMap[glslFunction->getName().c_str()] = function;
3689
3690 // Set the parameter id's
3691 for (int p = 0; p < (int)parameters.size(); ++p) {
3692 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3693 // give a name too
3694 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3695 }
3696 }
3697}
3698
3699// Process all the initializers, while skipping the functions and link objects
3700void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3701{
3702 builder.setBuildPoint(shaderEntry->getLastBlock());
3703 for (int i = 0; i < (int)initializers.size(); ++i) {
3704 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3705 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3706
3707 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003708 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003709 initializer->traverse(this);
3710 }
3711 }
3712}
3713
3714// Process all the functions, while skipping initializers.
3715void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3716{
3717 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3718 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003719 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003720 node->traverse(this);
3721 }
3722}
3723
3724void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3725{
qining25262b32016-05-06 17:25:16 -04003726 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003727 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003728 currentFunction = functionMap[node->getName().c_str()];
3729 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003730 builder.setBuildPoint(functionBlock);
3731}
3732
Rex Xu04db3f52015-09-16 11:44:02 +08003733void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003734{
Rex Xufc618912015-09-09 16:42:49 +08003735 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003736
3737 glslang::TSampler sampler = {};
3738 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003739#ifdef AMD_EXTENSIONS
3740 bool f16ShadowCompare = false;
3741#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003742 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003743 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3744 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003745#ifdef AMD_EXTENSIONS
3746 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3747#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003748 }
3749
John Kessenich140f3df2015-06-26 16:58:36 -06003750 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3751 builder.clearAccessChain();
3752 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003753
3754 // Special case l-value operands
3755 bool lvalue = false;
3756 switch (node.getOp()) {
3757 case glslang::EOpImageAtomicAdd:
3758 case glslang::EOpImageAtomicMin:
3759 case glslang::EOpImageAtomicMax:
3760 case glslang::EOpImageAtomicAnd:
3761 case glslang::EOpImageAtomicOr:
3762 case glslang::EOpImageAtomicXor:
3763 case glslang::EOpImageAtomicExchange:
3764 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05003765 case glslang::EOpImageAtomicLoad:
3766 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08003767 if (i == 0)
3768 lvalue = true;
3769 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003770 case glslang::EOpSparseImageLoad:
3771 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3772 lvalue = true;
3773 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003774#ifdef AMD_EXTENSIONS
3775 case glslang::EOpSparseTexture:
3776 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3777 lvalue = true;
3778 break;
3779 case glslang::EOpSparseTextureClamp:
3780 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3781 lvalue = true;
3782 break;
3783 case glslang::EOpSparseTextureLod:
3784 case glslang::EOpSparseTextureOffset:
3785 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3786 lvalue = true;
3787 break;
3788#else
Rex Xu48edadf2015-12-31 16:11:41 +08003789 case glslang::EOpSparseTexture:
3790 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3791 lvalue = true;
3792 break;
3793 case glslang::EOpSparseTextureClamp:
3794 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3795 lvalue = true;
3796 break;
3797 case glslang::EOpSparseTextureLod:
3798 case glslang::EOpSparseTextureOffset:
3799 if (i == 3)
3800 lvalue = true;
3801 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003802#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003803 case glslang::EOpSparseTextureFetch:
3804 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3805 lvalue = true;
3806 break;
3807 case glslang::EOpSparseTextureFetchOffset:
3808 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3809 lvalue = true;
3810 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003811#ifdef AMD_EXTENSIONS
3812 case glslang::EOpSparseTextureLodOffset:
3813 case glslang::EOpSparseTextureGrad:
3814 case glslang::EOpSparseTextureOffsetClamp:
3815 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3816 lvalue = true;
3817 break;
3818 case glslang::EOpSparseTextureGradOffset:
3819 case glslang::EOpSparseTextureGradClamp:
3820 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3821 lvalue = true;
3822 break;
3823 case glslang::EOpSparseTextureGradOffsetClamp:
3824 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3825 lvalue = true;
3826 break;
3827#else
Rex Xu48edadf2015-12-31 16:11:41 +08003828 case glslang::EOpSparseTextureLodOffset:
3829 case glslang::EOpSparseTextureGrad:
3830 case glslang::EOpSparseTextureOffsetClamp:
3831 if (i == 4)
3832 lvalue = true;
3833 break;
3834 case glslang::EOpSparseTextureGradOffset:
3835 case glslang::EOpSparseTextureGradClamp:
3836 if (i == 5)
3837 lvalue = true;
3838 break;
3839 case glslang::EOpSparseTextureGradOffsetClamp:
3840 if (i == 6)
3841 lvalue = true;
3842 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003843#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003844 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003845 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3846 lvalue = true;
3847 break;
3848 case glslang::EOpSparseTextureGatherOffset:
3849 case glslang::EOpSparseTextureGatherOffsets:
3850 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3851 lvalue = true;
3852 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003853#ifdef AMD_EXTENSIONS
3854 case glslang::EOpSparseTextureGatherLod:
3855 if (i == 3)
3856 lvalue = true;
3857 break;
3858 case glslang::EOpSparseTextureGatherLodOffset:
3859 case glslang::EOpSparseTextureGatherLodOffsets:
3860 if (i == 4)
3861 lvalue = true;
3862 break;
Rex Xu129799a2017-07-05 17:23:28 +08003863 case glslang::EOpSparseImageLoadLod:
3864 if (i == 3)
3865 lvalue = true;
3866 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003867#endif
Chao Chen3a137962018-09-19 11:41:27 -07003868#ifdef NV_EXTENSIONS
3869 case glslang::EOpImageSampleFootprintNV:
3870 if (i == 4)
3871 lvalue = true;
3872 break;
3873 case glslang::EOpImageSampleFootprintClampNV:
3874 case glslang::EOpImageSampleFootprintLodNV:
3875 if (i == 5)
3876 lvalue = true;
3877 break;
3878 case glslang::EOpImageSampleFootprintGradNV:
3879 if (i == 6)
3880 lvalue = true;
3881 break;
3882 case glslang::EOpImageSampleFootprintGradClampNV:
3883 if (i == 7)
3884 lvalue = true;
3885 break;
3886#endif
Rex Xufc618912015-09-09 16:42:49 +08003887 default:
3888 break;
3889 }
3890
Rex Xu6b86d492015-09-16 17:48:22 +08003891 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003892 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003893 else
John Kessenich32cfd492016-02-02 12:37:46 -07003894 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003895 }
3896}
3897
John Kessenichfc51d282015-08-19 13:34:18 -06003898void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003899{
John Kessenichfc51d282015-08-19 13:34:18 -06003900 builder.clearAccessChain();
3901 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003902 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003903}
John Kessenich140f3df2015-06-26 16:58:36 -06003904
John Kessenichfc51d282015-08-19 13:34:18 -06003905spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3906{
John Kesseniche485c7a2017-05-31 18:50:53 -06003907 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003908 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003909
3910 builder.setLine(node->getLoc().line);
3911
John Kessenichfc51d282015-08-19 13:34:18 -06003912 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05003913
3914 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
3915 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
3916 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003917#ifdef AMD_EXTENSIONS
3918 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3919 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3920 : false;
3921#endif
3922
John Kessenichfc51d282015-08-19 13:34:18 -06003923 std::vector<spv::Id> arguments;
3924 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003925 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003926 else
3927 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003928 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003929
3930 spv::Builder::TextureParameters params = { };
3931 params.sampler = arguments[0];
3932
Rex Xu04db3f52015-09-16 11:44:02 +08003933 glslang::TCrackedTextureOp cracked;
3934 node->crackTexture(sampler, cracked);
3935
amhagan05506bb2017-06-13 16:53:02 -04003936 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003937
John Kessenichfc51d282015-08-19 13:34:18 -06003938 // Check for queries
3939 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003940 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3941 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003942 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003943
John Kessenichfc51d282015-08-19 13:34:18 -06003944 switch (node->getOp()) {
3945 case glslang::EOpImageQuerySize:
3946 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003947 if (arguments.size() > 1) {
3948 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003949 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003950 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003951 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003952 case glslang::EOpImageQuerySamples:
3953 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003954 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003955 case glslang::EOpTextureQueryLod:
3956 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003957 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003958 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003959 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003960 case glslang::EOpSparseTexelsResident:
3961 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003962 default:
3963 assert(0);
3964 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003965 }
John Kessenich140f3df2015-06-26 16:58:36 -06003966 }
3967
LoopDawg4425f242018-02-18 11:40:01 -07003968 int components = node->getType().getVectorSize();
3969
3970 if (node->getOp() == glslang::EOpTextureFetch) {
3971 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3972 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3973 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3974 // here around e.g. which ones return scalars or other types.
3975 components = 4;
3976 }
3977
3978 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3979
3980 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3981
Rex Xufc618912015-09-09 16:42:49 +08003982 // Check for image functions other than queries
3983 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06003984 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06003985 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06003986 spv::IdImmediate image = { true, *(opIt++) };
3987 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07003988
3989 // Handle subpass operations
3990 // TODO: GLSL should change to have the "MS" only on the type rather than the
3991 // built-in function.
3992 if (cracked.subpass) {
3993 // add on the (0,0) coordinate
3994 spv::Id zero = builder.makeIntConstant(0);
3995 std::vector<spv::Id> comps;
3996 comps.push_back(zero);
3997 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06003998 spv::IdImmediate coord = { true,
3999 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
4000 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07004001 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06004002 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
4003 operands.push_back(imageOperands);
4004 spv::IdImmediate imageOperand = { true, *(opIt++) };
4005 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07004006 }
John Kessenichfe4e5722017-10-19 02:07:30 -06004007 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
4008 builder.setPrecision(result, precision);
4009 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07004010 }
4011
John Kessenich149afc32018-08-14 13:31:43 -06004012 spv::IdImmediate coord = { true, *(opIt++) };
4013 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08004014#ifdef AMD_EXTENSIONS
4015 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
4016#else
John Kessenich56bab042015-09-16 10:54:31 -06004017 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004018#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004019 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07004020 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004021 mask = mask | spv::ImageOperandsSampleMask;
4022 }
Rex Xu129799a2017-07-05 17:23:28 +08004023#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004024 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004025 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4026 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05004027 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07004028 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004029#endif
4030 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4031 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4032 if (mask) {
4033 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4034 operands.push_back(imageOperands);
4035 }
4036 if (mask & spv::ImageOperandsSampleMask) {
4037 spv::IdImmediate imageOperand = { true, *opIt++ };
4038 operands.push_back(imageOperand);
4039 }
4040#ifdef AMD_EXTENSIONS
4041 if (mask & spv::ImageOperandsLodMask) {
4042 spv::IdImmediate imageOperand = { true, *opIt++ };
4043 operands.push_back(imageOperand);
4044 }
4045#endif
4046 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4047 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4048 operands.push_back(imageOperand);
4049 }
4050
John Kessenich149afc32018-08-14 13:31:43 -06004051 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004052 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06004053
John Kessenich149afc32018-08-14 13:31:43 -06004054 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07004055 builder.setPrecision(result[0], precision);
4056
4057 // If needed, add a conversion constructor to the proper size.
4058 if (components != node->getType().getVectorSize())
4059 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4060
4061 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08004062#ifdef AMD_EXTENSIONS
4063 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
4064#else
John Kessenich56bab042015-09-16 10:54:31 -06004065 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08004066#endif
Rex Xu129799a2017-07-05 17:23:28 +08004067
Jeff Bolz36831c92018-09-05 10:11:41 -05004068 // Push the texel value before the operands
4069#ifdef AMD_EXTENSIONS
4070 if (sampler.ms || cracked.lod) {
4071#else
4072 if (sampler.ms) {
4073#endif
John Kessenich149afc32018-08-14 13:31:43 -06004074 spv::IdImmediate texel = { true, *(opIt + 1) };
4075 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06004076 } else {
4077 spv::IdImmediate texel = { true, *opIt };
4078 operands.push_back(texel);
4079 }
Jeff Bolz36831c92018-09-05 10:11:41 -05004080
4081 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
4082 if (sampler.ms) {
4083 mask = mask | spv::ImageOperandsSampleMask;
4084 }
4085#ifdef AMD_EXTENSIONS
4086 if (cracked.lod) {
4087 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4088 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4089 mask = mask | spv::ImageOperandsLodMask;
4090 }
4091#endif
4092 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4093 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
4094 if (mask) {
4095 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
4096 operands.push_back(imageOperands);
4097 }
4098 if (mask & spv::ImageOperandsSampleMask) {
4099 spv::IdImmediate imageOperand = { true, *opIt++ };
4100 operands.push_back(imageOperand);
4101 }
4102#ifdef AMD_EXTENSIONS
4103 if (mask & spv::ImageOperandsLodMask) {
4104 spv::IdImmediate imageOperand = { true, *opIt++ };
4105 operands.push_back(imageOperand);
4106 }
4107#endif
4108 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
4109 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4110 operands.push_back(imageOperand);
4111 }
4112
John Kessenich56bab042015-09-16 10:54:31 -06004113 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06004114 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07004115 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06004116 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08004117#ifdef AMD_EXTENSIONS
4118 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
4119#else
Rex Xu5eafa472016-02-19 22:24:03 +08004120 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08004121#endif
Rex Xu5eafa472016-02-19 22:24:03 +08004122 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06004123 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08004124 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
4125
Jeff Bolz36831c92018-09-05 10:11:41 -05004126 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08004127 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05004128 mask = mask | spv::ImageOperandsSampleMask;
4129 }
Rex Xu129799a2017-07-05 17:23:28 +08004130#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05004131 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08004132 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
4133 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
4134
Jeff Bolz36831c92018-09-05 10:11:41 -05004135 mask = mask | spv::ImageOperandsLodMask;
4136 }
4137#endif
4138 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
4139 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
4140 if (mask) {
4141 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06004142 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05004143 }
4144 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06004145 spv::IdImmediate imageOperand = { true, *opIt++ };
4146 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05004147 }
4148#ifdef AMD_EXTENSIONS
4149 if (mask & spv::ImageOperandsLodMask) {
4150 spv::IdImmediate imageOperand = { true, *opIt++ };
4151 operands.push_back(imageOperand);
4152 }
Rex Xu129799a2017-07-05 17:23:28 +08004153#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05004154 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
4155 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
4156 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08004157 }
4158
4159 // Create the return type that was a special structure
4160 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06004161 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08004162 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
4163 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
4164
4165 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
4166
4167 // Decode the return type
4168 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
4169 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07004170 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08004171 // Process image atomic operations
4172
4173 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
4174 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06004175 // For non-MS, the sample value should be 0
4176 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
4177 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06004178
Jeff Bolz36831c92018-09-05 10:11:41 -05004179 spv::Id resultTypeId;
4180 // imageAtomicStore has a void return type so base the pointer type on
4181 // the type of the value operand.
4182 if (node->getOp() == glslang::EOpImageAtomicStore) {
4183 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
4184 } else {
4185 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
4186 }
John Kessenich56bab042015-09-16 10:54:31 -06004187 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08004188
4189 std::vector<spv::Id> operands;
4190 operands.push_back(pointer);
4191 for (; opIt != arguments.end(); ++opIt)
4192 operands.push_back(*opIt);
4193
John Kessenich8c8505c2016-07-26 12:50:38 -06004194 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08004195 }
4196 }
4197
amhagan05506bb2017-06-13 16:53:02 -04004198#ifdef AMD_EXTENSIONS
4199 // Check for fragment mask functions other than queries
4200 if (cracked.fragMask) {
4201 assert(sampler.ms);
4202
4203 auto opIt = arguments.begin();
4204 std::vector<spv::Id> operands;
4205
4206 // Extract the image if necessary
4207 if (builder.isSampledImage(params.sampler))
4208 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4209
4210 operands.push_back(params.sampler);
4211 ++opIt;
4212
4213 if (sampler.isSubpass()) {
4214 // add on the (0,0) coordinate
4215 spv::Id zero = builder.makeIntConstant(0);
4216 std::vector<spv::Id> comps;
4217 comps.push_back(zero);
4218 comps.push_back(zero);
4219 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4220 }
4221
4222 for (; opIt != arguments.end(); ++opIt)
4223 operands.push_back(*opIt);
4224
4225 spv::Op fragMaskOp = spv::OpNop;
4226 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4227 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4228 else if (node->getOp() == glslang::EOpFragmentFetch)
4229 fragMaskOp = spv::OpFragmentFetchAMD;
4230
4231 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4232 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4233 return builder.createOp(fragMaskOp, resultType(), operands);
4234 }
4235#endif
4236
Rex Xufc618912015-09-09 16:42:49 +08004237 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004238 bool sparse = node->isSparseTexture();
Chao Chen3a137962018-09-19 11:41:27 -07004239#ifdef NV_EXTENSIONS
4240 bool imageFootprint = node->isImageFootprint();
4241#endif
4242
Rex Xu71519fe2015-11-11 15:35:47 +08004243 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4244
John Kessenichfc51d282015-08-19 13:34:18 -06004245 // check for bias argument
4246 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004247#ifdef AMD_EXTENSIONS
4248 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4249#else
Rex Xu71519fe2015-11-11 15:35:47 +08004250 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004251#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004252 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004253#ifdef AMD_EXTENSIONS
4254 if (cracked.gather)
4255 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004256
4257 if (f16ShadowCompare)
4258 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004259#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004260 if (cracked.offset)
4261 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004262#ifdef AMD_EXTENSIONS
4263 else if (cracked.offsets)
4264 ++nonBiasArgCount;
4265#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004266 if (cracked.grad)
4267 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004268 if (cracked.lodClamp)
4269 ++nonBiasArgCount;
4270 if (sparse)
4271 ++nonBiasArgCount;
Chao Chen3a137962018-09-19 11:41:27 -07004272#ifdef NV_EXTENSIONS
4273 if (imageFootprint)
4274 //Following three extra arguments
4275 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4276 nonBiasArgCount += 3;
4277#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004278 if ((int)arguments.size() > nonBiasArgCount)
4279 bias = true;
4280 }
4281
John Kessenicha5c33d62016-06-02 23:45:21 -06004282 // See if the sampler param should really be just the SPV image part
4283 if (cracked.fetch) {
4284 // a fetch needs to have the image extracted first
4285 if (builder.isSampledImage(params.sampler))
4286 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4287 }
4288
Rex Xu225e0fc2016-11-17 17:47:59 +08004289#ifdef AMD_EXTENSIONS
4290 if (cracked.gather) {
4291 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4292 if (bias || cracked.lod ||
4293 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4294 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004295 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004296 }
4297 }
4298#endif
4299
John Kessenichfc51d282015-08-19 13:34:18 -06004300 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004301
John Kessenichfc51d282015-08-19 13:34:18 -06004302 params.coords = arguments[1];
4303 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004304 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004305
4306 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004307#ifdef AMD_EXTENSIONS
4308 if (cubeCompare || f16ShadowCompare) {
4309#else
Rex Xu48edadf2015-12-31 16:11:41 +08004310 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004311#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004312 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004313 ++extraArgs;
4314 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004315 params.Dref = arguments[2];
4316 ++extraArgs;
4317 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004318 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004319 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004320 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004321 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004322 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004323 dRefComp = builder.getNumComponents(params.coords) - 1;
4324 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004325 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4326 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004327
4328 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004329 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004330 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004331 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004332 } else if (glslangIntermediate->getStage() != EShLangFragment
4333#ifdef NV_EXTENSIONS
4334 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4335 && !(glslangIntermediate->getStage() == EShLangCompute &&
4336 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4337#endif
4338 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004339 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4340 noImplicitLod = true;
4341 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004342
4343 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004344 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004345 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004346 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004347 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004348
4349 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004350 if (cracked.grad) {
4351 params.gradX = arguments[2 + extraArgs];
4352 params.gradY = arguments[3 + extraArgs];
4353 extraArgs += 2;
4354 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004355
4356 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004357 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004358 params.offset = arguments[2 + extraArgs];
4359 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004360 } else if (cracked.offsets) {
4361 params.offsets = arguments[2 + extraArgs];
4362 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004363 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004364
4365 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004366 if (cracked.lodClamp) {
4367 params.lodClamp = arguments[2 + extraArgs];
4368 ++extraArgs;
4369 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004370 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004371 if (sparse) {
4372 params.texelOut = arguments[2 + extraArgs];
4373 ++extraArgs;
4374 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004375
John Kessenich76d4dfc2016-06-16 12:43:23 -06004376 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004377 if (cracked.gather && ! sampler.shadow) {
4378 // default component is 0, if missing, otherwise an argument
4379 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004380 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004381 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004382 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004383 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004384 }
Chao Chen3a137962018-09-19 11:41:27 -07004385#ifdef NV_EXTENSIONS
4386 spv::Id resultStruct = spv::NoResult;
4387 if (imageFootprint) {
4388 //Following three extra arguments
4389 // int granularity, bool coarse, out gl_TextureFootprint2DNV footprint
4390 params.granularity = arguments[2 + extraArgs];
4391 params.coarse = arguments[3 + extraArgs];
4392 resultStruct = arguments[4 + extraArgs];
4393 extraArgs += 3;
4394 }
4395#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08004396 // bias
4397 if (bias) {
4398 params.bias = arguments[2 + extraArgs];
4399 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004400 }
John Kessenichfc51d282015-08-19 13:34:18 -06004401
Chao Chen3a137962018-09-19 11:41:27 -07004402#ifdef NV_EXTENSIONS
4403 if (imageFootprint) {
4404 builder.addExtension(spv::E_SPV_NV_shader_image_footprint);
4405 builder.addCapability(spv::CapabilityImageFootprintNV);
4406
4407
4408 //resultStructType(OpenGL type) contains 5 elements:
4409 //struct gl_TextureFootprint2DNV {
4410 // uvec2 anchor;
4411 // uvec2 offset;
4412 // uvec2 mask;
4413 // uint lod;
4414 // uint granularity;
4415 //};
4416 //or
4417 //struct gl_TextureFootprint3DNV {
4418 // uvec3 anchor;
4419 // uvec3 offset;
4420 // uvec2 mask;
4421 // uint lod;
4422 // uint granularity;
4423 //};
4424 spv::Id resultStructType = builder.getContainedTypeId(builder.getTypeId(resultStruct));
4425 assert(builder.isStructType(resultStructType));
4426
4427 //resType (SPIR-V type) contains 6 elements:
4428 //Member 0 must be a Boolean type scalar(LOD),
4429 //Member 1 must be a vector of integer type, whose Signedness operand is 0(anchor),
4430 //Member 2 must be a vector of integer type, whose Signedness operand is 0(offset),
4431 //Member 3 must be a vector of integer type, whose Signedness operand is 0(mask),
4432 //Member 4 must be a scalar of integer type, whose Signedness operand is 0(lod),
4433 //Member 5 must be a scalar of integer type, whose Signedness operand is 0(granularity).
4434 std::vector<spv::Id> members;
4435 members.push_back(resultType());
4436 for (int i = 0; i < 5; i++) {
4437 members.push_back(builder.getContainedTypeId(resultStructType, i));
4438 }
4439 spv::Id resType = builder.makeStructType(members, "ResType");
4440
4441 //call ImageFootprintNV
4442 spv::Id res = builder.createTextureCall(precision, resType, sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
4443
4444 //copy resType (SPIR-V type) to resultStructType(OpenGL type)
4445 for (int i = 0; i < 5; i++) {
4446 builder.clearAccessChain();
4447 builder.setAccessChainLValue(resultStruct);
4448
4449 //Accessing to a struct we created, no coherent flag is set
4450 spv::Builder::AccessChain::CoherentFlags flags;
4451 flags.clear();
4452
4453 builder.accessChainPush(builder.makeIntConstant(i), flags);
4454 builder.accessChainStore(builder.createCompositeExtract(res, builder.getContainedTypeId(resType, i+1), i+1));
4455 }
4456 return builder.createCompositeExtract(res, resultType(), 0);
4457 }
4458#endif
4459
John Kessenich65336482016-06-16 14:06:26 -06004460 // projective component (might not to move)
4461 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4462 // are divided by the last component of P."
4463 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4464 // unused components will appear after all used components."
4465 if (cracked.proj) {
4466 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4467 int projTargetComp;
4468 switch (sampler.dim) {
4469 case glslang::Esd1D: projTargetComp = 1; break;
4470 case glslang::Esd2D: projTargetComp = 2; break;
4471 case glslang::EsdRect: projTargetComp = 2; break;
4472 default: projTargetComp = projSourceComp; break;
4473 }
4474 // copy the projective coordinate if we have to
4475 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004476 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004477 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4478 projSourceComp);
4479 params.coords = builder.createCompositeInsert(projComp, params.coords,
4480 builder.getTypeId(params.coords), projTargetComp);
4481 }
4482 }
4483
Jeff Bolz36831c92018-09-05 10:11:41 -05004484 // nonprivate
4485 if (imageType.getQualifier().nonprivate) {
4486 params.nonprivate = true;
4487 }
4488
4489 // volatile
4490 if (imageType.getQualifier().volatil) {
4491 params.volatil = true;
4492 }
4493
St0fFa1184dd2018-04-09 21:08:14 +02004494 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004495 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004496 );
LoopDawg4425f242018-02-18 11:40:01 -07004497
4498 if (components != node->getType().getVectorSize())
4499 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4500
4501 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004502}
4503
4504spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4505{
4506 // Grab the function's pointer from the previously created function
4507 spv::Function* function = functionMap[node->getName().c_str()];
4508 if (! function)
4509 return 0;
4510
4511 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4512 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4513
4514 // See comments in makeFunctions() for details about the semantics for parameter passing.
4515 //
4516 // These imply we need a four step process:
4517 // 1. Evaluate the arguments
4518 // 2. Allocate and make copies of in, out, and inout arguments
4519 // 3. Make the call
4520 // 4. Copy back the results
4521
John Kessenichd3ed90b2018-05-04 11:43:03 -06004522 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004523 std::vector<spv::Builder::AccessChain> lValues;
4524 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004525 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004526 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004527 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004528 // build l-value
4529 builder.clearAccessChain();
4530 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004531 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004532 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004533 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004534 // save l-value
4535 lValues.push_back(builder.getAccessChain());
4536 } else {
4537 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004538 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004539 }
4540 }
4541
4542 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4543 // copy the original into that space.
4544 //
4545 // Also, build up the list of actual arguments to pass in for the call
4546 int lValueCount = 0;
4547 int rValueCount = 0;
4548 std::vector<spv::Id> spvArgs;
4549 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4550 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004551 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004552 builder.setAccessChain(lValues[lValueCount]);
4553 arg = builder.accessChainGetLValue();
4554 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004555 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004556 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004557 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004558 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4559 // need to copy the input into output space
4560 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004561 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004562 builder.clearAccessChain();
4563 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004564 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004565 }
4566 ++lValueCount;
4567 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004568 // process r-value, which involves a copy for a type mismatch
4569 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4570 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4571 builder.clearAccessChain();
4572 builder.setAccessChainLValue(argCopy);
4573 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4574 arg = builder.createLoad(argCopy);
4575 } else
4576 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004577 ++rValueCount;
4578 }
4579 spvArgs.push_back(arg);
4580 }
4581
4582 // 3. Make the call.
4583 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004584 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004585
4586 // 4. Copy back out an "out" arguments.
4587 lValueCount = 0;
4588 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004589 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004590 ++lValueCount;
4591 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004592 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4593 spv::Id copy = builder.createLoad(spvArgs[a]);
4594 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004595 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004596 }
4597 ++lValueCount;
4598 }
4599 }
4600
4601 return result;
4602}
4603
4604// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004605spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004606 spv::Id typeId, spv::Id left, spv::Id right,
4607 glslang::TBasicType typeProxy, bool reduceComparison)
4608{
John Kessenich66011cb2018-03-06 16:12:04 -07004609 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4610 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004611 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004612
4613 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004614 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004615 bool comparison = false;
4616
4617 switch (op) {
4618 case glslang::EOpAdd:
4619 case glslang::EOpAddAssign:
4620 if (isFloat)
4621 binOp = spv::OpFAdd;
4622 else
4623 binOp = spv::OpIAdd;
4624 break;
4625 case glslang::EOpSub:
4626 case glslang::EOpSubAssign:
4627 if (isFloat)
4628 binOp = spv::OpFSub;
4629 else
4630 binOp = spv::OpISub;
4631 break;
4632 case glslang::EOpMul:
4633 case glslang::EOpMulAssign:
4634 if (isFloat)
4635 binOp = spv::OpFMul;
4636 else
4637 binOp = spv::OpIMul;
4638 break;
4639 case glslang::EOpVectorTimesScalar:
4640 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004641 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004642 if (builder.isVector(right))
4643 std::swap(left, right);
4644 assert(builder.isScalar(right));
4645 needMatchingVectors = false;
4646 binOp = spv::OpVectorTimesScalar;
t.jung697fdf02018-11-14 13:04:39 +01004647 } else if (isFloat)
4648 binOp = spv::OpFMul;
4649 else
John Kessenichec43d0a2015-07-04 17:17:31 -06004650 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004651 break;
4652 case glslang::EOpVectorTimesMatrix:
4653 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004654 binOp = spv::OpVectorTimesMatrix;
4655 break;
4656 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004657 binOp = spv::OpMatrixTimesVector;
4658 break;
4659 case glslang::EOpMatrixTimesScalar:
4660 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004661 binOp = spv::OpMatrixTimesScalar;
4662 break;
4663 case glslang::EOpMatrixTimesMatrix:
4664 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004665 binOp = spv::OpMatrixTimesMatrix;
4666 break;
4667 case glslang::EOpOuterProduct:
4668 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004669 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004670 break;
4671
4672 case glslang::EOpDiv:
4673 case glslang::EOpDivAssign:
4674 if (isFloat)
4675 binOp = spv::OpFDiv;
4676 else if (isUnsigned)
4677 binOp = spv::OpUDiv;
4678 else
4679 binOp = spv::OpSDiv;
4680 break;
4681 case glslang::EOpMod:
4682 case glslang::EOpModAssign:
4683 if (isFloat)
4684 binOp = spv::OpFMod;
4685 else if (isUnsigned)
4686 binOp = spv::OpUMod;
4687 else
4688 binOp = spv::OpSMod;
4689 break;
4690 case glslang::EOpRightShift:
4691 case glslang::EOpRightShiftAssign:
4692 if (isUnsigned)
4693 binOp = spv::OpShiftRightLogical;
4694 else
4695 binOp = spv::OpShiftRightArithmetic;
4696 break;
4697 case glslang::EOpLeftShift:
4698 case glslang::EOpLeftShiftAssign:
4699 binOp = spv::OpShiftLeftLogical;
4700 break;
4701 case glslang::EOpAnd:
4702 case glslang::EOpAndAssign:
4703 binOp = spv::OpBitwiseAnd;
4704 break;
4705 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004706 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004707 binOp = spv::OpLogicalAnd;
4708 break;
4709 case glslang::EOpInclusiveOr:
4710 case glslang::EOpInclusiveOrAssign:
4711 binOp = spv::OpBitwiseOr;
4712 break;
4713 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004714 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004715 binOp = spv::OpLogicalOr;
4716 break;
4717 case glslang::EOpExclusiveOr:
4718 case glslang::EOpExclusiveOrAssign:
4719 binOp = spv::OpBitwiseXor;
4720 break;
4721 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004722 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004723 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004724 break;
4725
4726 case glslang::EOpLessThan:
4727 case glslang::EOpGreaterThan:
4728 case glslang::EOpLessThanEqual:
4729 case glslang::EOpGreaterThanEqual:
4730 case glslang::EOpEqual:
4731 case glslang::EOpNotEqual:
4732 case glslang::EOpVectorEqual:
4733 case glslang::EOpVectorNotEqual:
4734 comparison = true;
4735 break;
4736 default:
4737 break;
4738 }
4739
John Kessenich7c1aa102015-10-15 13:29:11 -06004740 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004741 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004742 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004743 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004744 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004745
4746 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004747 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004748 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004749
qining25262b32016-05-06 17:25:16 -04004750 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004751 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004752 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004753 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004754 }
4755
4756 if (! comparison)
4757 return 0;
4758
John Kessenich7c1aa102015-10-15 13:29:11 -06004759 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004760
John Kessenich4583b612016-08-07 19:14:22 -06004761 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004762 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4763 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004764 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004765 return result;
4766 }
John Kessenich140f3df2015-06-26 16:58:36 -06004767
4768 switch (op) {
4769 case glslang::EOpLessThan:
4770 if (isFloat)
4771 binOp = spv::OpFOrdLessThan;
4772 else if (isUnsigned)
4773 binOp = spv::OpULessThan;
4774 else
4775 binOp = spv::OpSLessThan;
4776 break;
4777 case glslang::EOpGreaterThan:
4778 if (isFloat)
4779 binOp = spv::OpFOrdGreaterThan;
4780 else if (isUnsigned)
4781 binOp = spv::OpUGreaterThan;
4782 else
4783 binOp = spv::OpSGreaterThan;
4784 break;
4785 case glslang::EOpLessThanEqual:
4786 if (isFloat)
4787 binOp = spv::OpFOrdLessThanEqual;
4788 else if (isUnsigned)
4789 binOp = spv::OpULessThanEqual;
4790 else
4791 binOp = spv::OpSLessThanEqual;
4792 break;
4793 case glslang::EOpGreaterThanEqual:
4794 if (isFloat)
4795 binOp = spv::OpFOrdGreaterThanEqual;
4796 else if (isUnsigned)
4797 binOp = spv::OpUGreaterThanEqual;
4798 else
4799 binOp = spv::OpSGreaterThanEqual;
4800 break;
4801 case glslang::EOpEqual:
4802 case glslang::EOpVectorEqual:
4803 if (isFloat)
4804 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004805 else if (isBool)
4806 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004807 else
4808 binOp = spv::OpIEqual;
4809 break;
4810 case glslang::EOpNotEqual:
4811 case glslang::EOpVectorNotEqual:
4812 if (isFloat)
4813 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004814 else if (isBool)
4815 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004816 else
4817 binOp = spv::OpINotEqual;
4818 break;
4819 default:
4820 break;
4821 }
4822
qining25262b32016-05-06 17:25:16 -04004823 if (binOp != spv::OpNop) {
4824 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004825 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004826 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004827 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004828 }
John Kessenich140f3df2015-06-26 16:58:36 -06004829
4830 return 0;
4831}
4832
John Kessenich04bb8a02015-12-12 12:28:14 -07004833//
4834// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4835// These can be any of:
4836//
4837// matrix * scalar
4838// scalar * matrix
4839// matrix * matrix linear algebraic
4840// matrix * vector
4841// vector * matrix
4842// matrix * matrix componentwise
4843// matrix op matrix op in {+, -, /}
4844// matrix op scalar op in {+, -, /}
4845// scalar op matrix op in {+, -, /}
4846//
John Kessenichead86222018-03-28 18:01:20 -06004847spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4848 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004849{
4850 bool firstClass = true;
4851
4852 // First, handle first-class matrix operations (* and matrix/scalar)
4853 switch (op) {
4854 case spv::OpFDiv:
4855 if (builder.isMatrix(left) && builder.isScalar(right)) {
4856 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004857 spv::Id resultType = builder.getTypeId(right);
4858 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004859 op = spv::OpMatrixTimesScalar;
4860 } else
4861 firstClass = false;
4862 break;
4863 case spv::OpMatrixTimesScalar:
4864 if (builder.isMatrix(right))
4865 std::swap(left, right);
4866 assert(builder.isScalar(right));
4867 break;
4868 case spv::OpVectorTimesMatrix:
4869 assert(builder.isVector(left));
4870 assert(builder.isMatrix(right));
4871 break;
4872 case spv::OpMatrixTimesVector:
4873 assert(builder.isMatrix(left));
4874 assert(builder.isVector(right));
4875 break;
4876 case spv::OpMatrixTimesMatrix:
4877 assert(builder.isMatrix(left));
4878 assert(builder.isMatrix(right));
4879 break;
4880 default:
4881 firstClass = false;
4882 break;
4883 }
4884
qining25262b32016-05-06 17:25:16 -04004885 if (firstClass) {
4886 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004887 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004888 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004889 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004890 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004891
LoopDawg592860c2016-06-09 08:57:35 -06004892 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004893 // The result type of all of them is the same type as the (a) matrix operand.
4894 // The algorithm is to:
4895 // - break the matrix(es) into vectors
4896 // - smear any scalar to a vector
4897 // - do vector operations
4898 // - make a matrix out the vector results
4899 switch (op) {
4900 case spv::OpFAdd:
4901 case spv::OpFSub:
4902 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004903 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004904 case spv::OpFMul:
4905 {
4906 // one time set up...
4907 bool leftMat = builder.isMatrix(left);
4908 bool rightMat = builder.isMatrix(right);
4909 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4910 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4911 spv::Id scalarType = builder.getScalarTypeId(typeId);
4912 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4913 std::vector<spv::Id> results;
4914 spv::Id smearVec = spv::NoResult;
4915 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004916 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004917 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004918 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004919
4920 // do each vector op
4921 for (unsigned int c = 0; c < numCols; ++c) {
4922 std::vector<unsigned int> indexes;
4923 indexes.push_back(c);
4924 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4925 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004926 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004927 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004928 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004929 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004930 }
4931
4932 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004933 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004934 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004935 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004936 }
4937 default:
4938 assert(0);
4939 return spv::NoResult;
4940 }
4941}
4942
John Kessenichead86222018-03-28 18:01:20 -06004943spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4944 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004945{
4946 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004947 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004948 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004949 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4950 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004951
4952 switch (op) {
4953 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004954 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004955 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004956 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004957 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004958 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004959 unaryOp = spv::OpSNegate;
4960 break;
4961
4962 case glslang::EOpLogicalNot:
4963 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004964 unaryOp = spv::OpLogicalNot;
4965 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004966 case glslang::EOpBitwiseNot:
4967 unaryOp = spv::OpNot;
4968 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004969
John Kessenich140f3df2015-06-26 16:58:36 -06004970 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004971 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004972 break;
4973 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004974 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004975 break;
4976 case glslang::EOpTranspose:
4977 unaryOp = spv::OpTranspose;
4978 break;
4979
4980 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004981 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004982 break;
4983 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004984 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004985 break;
4986 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004987 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004988 break;
4989 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004990 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004991 break;
4992 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004993 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004994 break;
4995 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004996 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004997 break;
4998 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004999 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06005000 break;
5001 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005002 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06005003 break;
5004
5005 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005006 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005007 break;
5008 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005009 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005010 break;
5011 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005012 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005013 break;
5014 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005015 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06005016 break;
5017 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005018 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06005019 break;
5020 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06005021 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06005022 break;
5023
5024 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06005025 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06005026 break;
5027 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06005028 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06005029 break;
5030
5031 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005032 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06005033 break;
5034 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06005035 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06005036 break;
5037 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005038 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06005039 break;
5040 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06005041 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06005042 break;
5043 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005044 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005045 break;
5046 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06005047 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06005048 break;
5049
5050 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06005051 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06005052 break;
5053 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06005054 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06005055 break;
5056 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06005057 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06005058 break;
5059 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06005060 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06005061 break;
5062 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06005063 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06005064 break;
5065 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005066 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06005067 break;
5068
5069 case glslang::EOpIsNan:
5070 unaryOp = spv::OpIsNan;
5071 break;
5072 case glslang::EOpIsInf:
5073 unaryOp = spv::OpIsInf;
5074 break;
LoopDawg592860c2016-06-09 08:57:35 -06005075 case glslang::EOpIsFinite:
5076 unaryOp = spv::OpIsFinite;
5077 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005078
Rex Xucbc426e2015-12-15 16:03:10 +08005079 case glslang::EOpFloatBitsToInt:
5080 case glslang::EOpFloatBitsToUint:
5081 case glslang::EOpIntBitsToFloat:
5082 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08005083 case glslang::EOpDoubleBitsToInt64:
5084 case glslang::EOpDoubleBitsToUint64:
5085 case glslang::EOpInt64BitsToDouble:
5086 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08005087 case glslang::EOpFloat16BitsToInt16:
5088 case glslang::EOpFloat16BitsToUint16:
5089 case glslang::EOpInt16BitsToFloat16:
5090 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08005091 unaryOp = spv::OpBitcast;
5092 break;
5093
John Kessenich140f3df2015-06-26 16:58:36 -06005094 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005095 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005096 break;
5097 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005098 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005099 break;
5100 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005101 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005102 break;
5103 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005104 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005105 break;
5106 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005107 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005108 break;
5109 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06005110 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06005111 break;
John Kessenichfc51d282015-08-19 13:34:18 -06005112 case glslang::EOpPackSnorm4x8:
5113 libCall = spv::GLSLstd450PackSnorm4x8;
5114 break;
5115 case glslang::EOpUnpackSnorm4x8:
5116 libCall = spv::GLSLstd450UnpackSnorm4x8;
5117 break;
5118 case glslang::EOpPackUnorm4x8:
5119 libCall = spv::GLSLstd450PackUnorm4x8;
5120 break;
5121 case glslang::EOpUnpackUnorm4x8:
5122 libCall = spv::GLSLstd450UnpackUnorm4x8;
5123 break;
5124 case glslang::EOpPackDouble2x32:
5125 libCall = spv::GLSLstd450PackDouble2x32;
5126 break;
5127 case glslang::EOpUnpackDouble2x32:
5128 libCall = spv::GLSLstd450UnpackDouble2x32;
5129 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005130
Rex Xu8ff43de2016-04-22 16:51:45 +08005131 case glslang::EOpPackInt2x32:
5132 case glslang::EOpUnpackInt2x32:
5133 case glslang::EOpPackUint2x32:
5134 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07005135 case glslang::EOpPack16:
5136 case glslang::EOpPack32:
5137 case glslang::EOpPack64:
5138 case glslang::EOpUnpack32:
5139 case glslang::EOpUnpack16:
5140 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08005141 case glslang::EOpPackInt2x16:
5142 case glslang::EOpUnpackInt2x16:
5143 case glslang::EOpPackUint2x16:
5144 case glslang::EOpUnpackUint2x16:
5145 case glslang::EOpPackInt4x16:
5146 case glslang::EOpUnpackInt4x16:
5147 case glslang::EOpPackUint4x16:
5148 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005149 case glslang::EOpPackFloat2x16:
5150 case glslang::EOpUnpackFloat2x16:
5151 unaryOp = spv::OpBitcast;
5152 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005153
John Kessenich140f3df2015-06-26 16:58:36 -06005154 case glslang::EOpDPdx:
5155 unaryOp = spv::OpDPdx;
5156 break;
5157 case glslang::EOpDPdy:
5158 unaryOp = spv::OpDPdy;
5159 break;
5160 case glslang::EOpFwidth:
5161 unaryOp = spv::OpFwidth;
5162 break;
5163 case glslang::EOpDPdxFine:
5164 unaryOp = spv::OpDPdxFine;
5165 break;
5166 case glslang::EOpDPdyFine:
5167 unaryOp = spv::OpDPdyFine;
5168 break;
5169 case glslang::EOpFwidthFine:
5170 unaryOp = spv::OpFwidthFine;
5171 break;
5172 case glslang::EOpDPdxCoarse:
5173 unaryOp = spv::OpDPdxCoarse;
5174 break;
5175 case glslang::EOpDPdyCoarse:
5176 unaryOp = spv::OpDPdyCoarse;
5177 break;
5178 case glslang::EOpFwidthCoarse:
5179 unaryOp = spv::OpFwidthCoarse;
5180 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005181 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08005182#ifdef AMD_EXTENSIONS
5183 if (typeProxy == glslang::EbtFloat16)
5184 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
5185#endif
Rex Xu7a26c172015-12-08 17:12:09 +08005186 libCall = spv::GLSLstd450InterpolateAtCentroid;
5187 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005188 case glslang::EOpAny:
5189 unaryOp = spv::OpAny;
5190 break;
5191 case glslang::EOpAll:
5192 unaryOp = spv::OpAll;
5193 break;
5194
5195 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06005196 if (isFloat)
5197 libCall = spv::GLSLstd450FAbs;
5198 else
5199 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06005200 break;
5201 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06005202 if (isFloat)
5203 libCall = spv::GLSLstd450FSign;
5204 else
5205 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06005206 break;
5207
John Kessenichfc51d282015-08-19 13:34:18 -06005208 case glslang::EOpAtomicCounterIncrement:
5209 case glslang::EOpAtomicCounterDecrement:
5210 case glslang::EOpAtomicCounter:
5211 {
5212 // Handle all of the atomics in one place, in createAtomicOperation()
5213 std::vector<spv::Id> operands;
5214 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06005215 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06005216 }
5217
John Kessenichfc51d282015-08-19 13:34:18 -06005218 case glslang::EOpBitFieldReverse:
5219 unaryOp = spv::OpBitReverse;
5220 break;
5221 case glslang::EOpBitCount:
5222 unaryOp = spv::OpBitCount;
5223 break;
5224 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005225 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005226 break;
5227 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07005228 if (isUnsigned)
5229 libCall = spv::GLSLstd450FindUMsb;
5230 else
5231 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06005232 break;
5233
Rex Xu574ab042016-04-14 16:53:07 +08005234 case glslang::EOpBallot:
5235 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005236 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08005237 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08005238 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08005239#ifdef AMD_EXTENSIONS
5240 case glslang::EOpMinInvocations:
5241 case glslang::EOpMaxInvocations:
5242 case glslang::EOpAddInvocations:
5243 case glslang::EOpMinInvocationsNonUniform:
5244 case glslang::EOpMaxInvocationsNonUniform:
5245 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005246 case glslang::EOpMinInvocationsInclusiveScan:
5247 case glslang::EOpMaxInvocationsInclusiveScan:
5248 case glslang::EOpAddInvocationsInclusiveScan:
5249 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5250 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5251 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5252 case glslang::EOpMinInvocationsExclusiveScan:
5253 case glslang::EOpMaxInvocationsExclusiveScan:
5254 case glslang::EOpAddInvocationsExclusiveScan:
5255 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5256 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5257 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08005258#endif
Rex Xu51596642016-09-21 18:56:12 +08005259 {
5260 std::vector<spv::Id> operands;
5261 operands.push_back(operand);
5262 return createInvocationsOperation(op, typeId, operands, typeProxy);
5263 }
John Kessenich66011cb2018-03-06 16:12:04 -07005264 case glslang::EOpSubgroupAll:
5265 case glslang::EOpSubgroupAny:
5266 case glslang::EOpSubgroupAllEqual:
5267 case glslang::EOpSubgroupBroadcastFirst:
5268 case glslang::EOpSubgroupBallot:
5269 case glslang::EOpSubgroupInverseBallot:
5270 case glslang::EOpSubgroupBallotBitCount:
5271 case glslang::EOpSubgroupBallotInclusiveBitCount:
5272 case glslang::EOpSubgroupBallotExclusiveBitCount:
5273 case glslang::EOpSubgroupBallotFindLSB:
5274 case glslang::EOpSubgroupBallotFindMSB:
5275 case glslang::EOpSubgroupAdd:
5276 case glslang::EOpSubgroupMul:
5277 case glslang::EOpSubgroupMin:
5278 case glslang::EOpSubgroupMax:
5279 case glslang::EOpSubgroupAnd:
5280 case glslang::EOpSubgroupOr:
5281 case glslang::EOpSubgroupXor:
5282 case glslang::EOpSubgroupInclusiveAdd:
5283 case glslang::EOpSubgroupInclusiveMul:
5284 case glslang::EOpSubgroupInclusiveMin:
5285 case glslang::EOpSubgroupInclusiveMax:
5286 case glslang::EOpSubgroupInclusiveAnd:
5287 case glslang::EOpSubgroupInclusiveOr:
5288 case glslang::EOpSubgroupInclusiveXor:
5289 case glslang::EOpSubgroupExclusiveAdd:
5290 case glslang::EOpSubgroupExclusiveMul:
5291 case glslang::EOpSubgroupExclusiveMin:
5292 case glslang::EOpSubgroupExclusiveMax:
5293 case glslang::EOpSubgroupExclusiveAnd:
5294 case glslang::EOpSubgroupExclusiveOr:
5295 case glslang::EOpSubgroupExclusiveXor:
5296 case glslang::EOpSubgroupQuadSwapHorizontal:
5297 case glslang::EOpSubgroupQuadSwapVertical:
5298 case glslang::EOpSubgroupQuadSwapDiagonal: {
5299 std::vector<spv::Id> operands;
5300 operands.push_back(operand);
5301 return createSubgroupOperation(op, typeId, operands, typeProxy);
5302 }
Rex Xu9d93a232016-05-05 12:30:44 +08005303#ifdef AMD_EXTENSIONS
5304 case glslang::EOpMbcnt:
5305 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5306 libCall = spv::MbcntAMD;
5307 break;
5308
5309 case glslang::EOpCubeFaceIndex:
5310 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5311 libCall = spv::CubeFaceIndexAMD;
5312 break;
5313
5314 case glslang::EOpCubeFaceCoord:
5315 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5316 libCall = spv::CubeFaceCoordAMD;
5317 break;
5318#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005319#ifdef NV_EXTENSIONS
5320 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005321 unaryOp = spv::OpGroupNonUniformPartitionNV;
5322 break;
5323#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005324 default:
5325 return 0;
5326 }
5327
5328 spv::Id id;
5329 if (libCall >= 0) {
5330 std::vector<spv::Id> args;
5331 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005332 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005333 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005334 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005335 }
John Kessenich140f3df2015-06-26 16:58:36 -06005336
John Kessenichead86222018-03-28 18:01:20 -06005337 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005338 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005339 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005340}
5341
John Kessenich7a53f762016-01-20 11:19:27 -07005342// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005343spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5344 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005345{
5346 // Handle unary operations vector by vector.
5347 // The result type is the same type as the original type.
5348 // The algorithm is to:
5349 // - break the matrix into vectors
5350 // - apply the operation to each vector
5351 // - make a matrix out the vector results
5352
5353 // get the types sorted out
5354 int numCols = builder.getNumColumns(operand);
5355 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005356 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5357 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005358 std::vector<spv::Id> results;
5359
5360 // do each vector op
5361 for (int c = 0; c < numCols; ++c) {
5362 std::vector<unsigned int> indexes;
5363 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005364 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5365 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005366 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005367 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005368 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005369 }
5370
5371 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005372 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005373 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005374 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005375}
5376
John Kessenichad7645f2018-06-04 19:11:25 -06005377// For converting integers where both the bitwidth and the signedness could
5378// change, but only do the width change here. The caller is still responsible
5379// for the signedness conversion.
5380spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005381{
John Kessenichad7645f2018-06-04 19:11:25 -06005382 // Get the result type width, based on the type to convert to.
5383 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005384 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005385 case glslang::EOpConvInt16ToUint8:
5386 case glslang::EOpConvIntToUint8:
5387 case glslang::EOpConvInt64ToUint8:
5388 case glslang::EOpConvUint16ToInt8:
5389 case glslang::EOpConvUintToInt8:
5390 case glslang::EOpConvUint64ToInt8:
5391 width = 8;
5392 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005393 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005394 case glslang::EOpConvIntToUint16:
5395 case glslang::EOpConvInt64ToUint16:
5396 case glslang::EOpConvUint8ToInt16:
5397 case glslang::EOpConvUintToInt16:
5398 case glslang::EOpConvUint64ToInt16:
5399 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005400 break;
5401 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005402 case glslang::EOpConvInt16ToUint:
5403 case glslang::EOpConvInt64ToUint:
5404 case glslang::EOpConvUint8ToInt:
5405 case glslang::EOpConvUint16ToInt:
5406 case glslang::EOpConvUint64ToInt:
5407 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005408 break;
5409 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005410 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005411 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005412 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005413 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005414 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005415 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005416 break;
5417
5418 default:
5419 assert(false && "Default missing");
5420 break;
5421 }
5422
John Kessenichad7645f2018-06-04 19:11:25 -06005423 // Get the conversion operation and result type,
5424 // based on the target width, but the source type.
5425 spv::Id type = spv::NoType;
5426 spv::Op convOp = spv::OpNop;
5427 switch(op) {
5428 case glslang::EOpConvInt8ToUint16:
5429 case glslang::EOpConvInt8ToUint:
5430 case glslang::EOpConvInt8ToUint64:
5431 case glslang::EOpConvInt16ToUint8:
5432 case glslang::EOpConvInt16ToUint:
5433 case glslang::EOpConvInt16ToUint64:
5434 case glslang::EOpConvIntToUint8:
5435 case glslang::EOpConvIntToUint16:
5436 case glslang::EOpConvIntToUint64:
5437 case glslang::EOpConvInt64ToUint8:
5438 case glslang::EOpConvInt64ToUint16:
5439 case glslang::EOpConvInt64ToUint:
5440 convOp = spv::OpSConvert;
5441 type = builder.makeIntType(width);
5442 break;
5443 default:
5444 convOp = spv::OpUConvert;
5445 type = builder.makeUintType(width);
5446 break;
5447 }
5448
John Kessenich66011cb2018-03-06 16:12:04 -07005449 if (vectorSize > 0)
5450 type = builder.makeVectorType(type, vectorSize);
5451
John Kessenichad7645f2018-06-04 19:11:25 -06005452 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005453}
5454
John Kessenichead86222018-03-28 18:01:20 -06005455spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5456 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005457{
5458 spv::Op convOp = spv::OpNop;
5459 spv::Id zero = 0;
5460 spv::Id one = 0;
5461
5462 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5463
5464 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005465 case glslang::EOpConvInt8ToBool:
5466 case glslang::EOpConvUint8ToBool:
5467 zero = builder.makeUint8Constant(0);
5468 zero = makeSmearedConstant(zero, vectorSize);
5469 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005470 case glslang::EOpConvInt16ToBool:
5471 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005472 zero = builder.makeUint16Constant(0);
5473 zero = makeSmearedConstant(zero, vectorSize);
5474 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5475 case glslang::EOpConvIntToBool:
5476 case glslang::EOpConvUintToBool:
5477 zero = builder.makeUintConstant(0);
5478 zero = makeSmearedConstant(zero, vectorSize);
5479 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5480 case glslang::EOpConvInt64ToBool:
5481 case glslang::EOpConvUint64ToBool:
5482 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005483 zero = makeSmearedConstant(zero, vectorSize);
5484 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5485
5486 case glslang::EOpConvFloatToBool:
5487 zero = builder.makeFloatConstant(0.0F);
5488 zero = makeSmearedConstant(zero, vectorSize);
5489 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5490
5491 case glslang::EOpConvDoubleToBool:
5492 zero = builder.makeDoubleConstant(0.0);
5493 zero = makeSmearedConstant(zero, vectorSize);
5494 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5495
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005496 case glslang::EOpConvFloat16ToBool:
5497 zero = builder.makeFloat16Constant(0.0F);
5498 zero = makeSmearedConstant(zero, vectorSize);
5499 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005500
John Kessenich140f3df2015-06-26 16:58:36 -06005501 case glslang::EOpConvBoolToFloat:
5502 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005503 zero = builder.makeFloatConstant(0.0F);
5504 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005505 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005506
John Kessenich140f3df2015-06-26 16:58:36 -06005507 case glslang::EOpConvBoolToDouble:
5508 convOp = spv::OpSelect;
5509 zero = builder.makeDoubleConstant(0.0);
5510 one = builder.makeDoubleConstant(1.0);
5511 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005512
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005513 case glslang::EOpConvBoolToFloat16:
5514 convOp = spv::OpSelect;
5515 zero = builder.makeFloat16Constant(0.0F);
5516 one = builder.makeFloat16Constant(1.0F);
5517 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005518
5519 case glslang::EOpConvBoolToInt8:
5520 zero = builder.makeInt8Constant(0);
5521 one = builder.makeInt8Constant(1);
5522 convOp = spv::OpSelect;
5523 break;
5524
5525 case glslang::EOpConvBoolToUint8:
5526 zero = builder.makeUint8Constant(0);
5527 one = builder.makeUint8Constant(1);
5528 convOp = spv::OpSelect;
5529 break;
5530
5531 case glslang::EOpConvBoolToInt16:
5532 zero = builder.makeInt16Constant(0);
5533 one = builder.makeInt16Constant(1);
5534 convOp = spv::OpSelect;
5535 break;
5536
5537 case glslang::EOpConvBoolToUint16:
5538 zero = builder.makeUint16Constant(0);
5539 one = builder.makeUint16Constant(1);
5540 convOp = spv::OpSelect;
5541 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005542
John Kessenich140f3df2015-06-26 16:58:36 -06005543 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005544 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005545 if (op == glslang::EOpConvBoolToInt64)
5546 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005547 else
5548 zero = builder.makeIntConstant(0);
5549
5550 if (op == glslang::EOpConvBoolToInt64)
5551 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005552 else
5553 one = builder.makeIntConstant(1);
5554
John Kessenich140f3df2015-06-26 16:58:36 -06005555 convOp = spv::OpSelect;
5556 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005557
John Kessenich140f3df2015-06-26 16:58:36 -06005558 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005559 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005560 if (op == glslang::EOpConvBoolToUint64)
5561 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005562 else
5563 zero = builder.makeUintConstant(0);
5564
5565 if (op == glslang::EOpConvBoolToUint64)
5566 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005567 else
5568 one = builder.makeUintConstant(1);
5569
John Kessenich140f3df2015-06-26 16:58:36 -06005570 convOp = spv::OpSelect;
5571 break;
5572
John Kessenich66011cb2018-03-06 16:12:04 -07005573 case glslang::EOpConvInt8ToFloat16:
5574 case glslang::EOpConvInt8ToFloat:
5575 case glslang::EOpConvInt8ToDouble:
5576 case glslang::EOpConvInt16ToFloat16:
5577 case glslang::EOpConvInt16ToFloat:
5578 case glslang::EOpConvInt16ToDouble:
5579 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005580 case glslang::EOpConvIntToFloat:
5581 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005582 case glslang::EOpConvInt64ToFloat:
5583 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005584 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005585 convOp = spv::OpConvertSToF;
5586 break;
5587
John Kessenich66011cb2018-03-06 16:12:04 -07005588 case glslang::EOpConvUint8ToFloat16:
5589 case glslang::EOpConvUint8ToFloat:
5590 case glslang::EOpConvUint8ToDouble:
5591 case glslang::EOpConvUint16ToFloat16:
5592 case glslang::EOpConvUint16ToFloat:
5593 case glslang::EOpConvUint16ToDouble:
5594 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005595 case glslang::EOpConvUintToFloat:
5596 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005597 case glslang::EOpConvUint64ToFloat:
5598 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005599 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005600 convOp = spv::OpConvertUToF;
5601 break;
5602
5603 case glslang::EOpConvDoubleToFloat:
5604 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005605 case glslang::EOpConvDoubleToFloat16:
5606 case glslang::EOpConvFloat16ToDouble:
5607 case glslang::EOpConvFloatToFloat16:
5608 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005609 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005610 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005611 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005612 break;
5613
John Kessenich66011cb2018-03-06 16:12:04 -07005614 case glslang::EOpConvFloat16ToInt8:
5615 case glslang::EOpConvFloatToInt8:
5616 case glslang::EOpConvDoubleToInt8:
5617 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005618 case glslang::EOpConvFloatToInt16:
5619 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005620 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005621 case glslang::EOpConvFloatToInt:
5622 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005623 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005624 case glslang::EOpConvFloatToInt64:
5625 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005626 convOp = spv::OpConvertFToS;
5627 break;
5628
John Kessenich66011cb2018-03-06 16:12:04 -07005629 case glslang::EOpConvUint8ToInt8:
5630 case glslang::EOpConvInt8ToUint8:
5631 case glslang::EOpConvUint16ToInt16:
5632 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005633 case glslang::EOpConvUintToInt:
5634 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005635 case glslang::EOpConvUint64ToInt64:
5636 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005637 if (builder.isInSpecConstCodeGenMode()) {
5638 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005639 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5640 zero = builder.makeUint8Constant(0);
5641 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005642 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005643 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5644 zero = builder.makeUint64Constant(0);
5645 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005646 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005647 }
qining189b2032016-04-12 23:16:20 -04005648 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005649 // Use OpIAdd, instead of OpBitcast to do the conversion when
5650 // generating for OpSpecConstantOp instruction.
5651 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5652 }
5653 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005654 convOp = spv::OpBitcast;
5655 break;
5656
John Kessenich66011cb2018-03-06 16:12:04 -07005657 case glslang::EOpConvFloat16ToUint8:
5658 case glslang::EOpConvFloatToUint8:
5659 case glslang::EOpConvDoubleToUint8:
5660 case glslang::EOpConvFloat16ToUint16:
5661 case glslang::EOpConvFloatToUint16:
5662 case glslang::EOpConvDoubleToUint16:
5663 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005664 case glslang::EOpConvFloatToUint:
5665 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005666 case glslang::EOpConvFloatToUint64:
5667 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005668 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005669 convOp = spv::OpConvertFToU;
5670 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005671
John Kessenich66011cb2018-03-06 16:12:04 -07005672 case glslang::EOpConvInt8ToInt16:
5673 case glslang::EOpConvInt8ToInt:
5674 case glslang::EOpConvInt8ToInt64:
5675 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005676 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005677 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005678 case glslang::EOpConvIntToInt8:
5679 case glslang::EOpConvIntToInt16:
5680 case glslang::EOpConvIntToInt64:
5681 case glslang::EOpConvInt64ToInt8:
5682 case glslang::EOpConvInt64ToInt16:
5683 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005684 convOp = spv::OpSConvert;
5685 break;
5686
John Kessenich66011cb2018-03-06 16:12:04 -07005687 case glslang::EOpConvUint8ToUint16:
5688 case glslang::EOpConvUint8ToUint:
5689 case glslang::EOpConvUint8ToUint64:
5690 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005691 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005692 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005693 case glslang::EOpConvUintToUint8:
5694 case glslang::EOpConvUintToUint16:
5695 case glslang::EOpConvUintToUint64:
5696 case glslang::EOpConvUint64ToUint8:
5697 case glslang::EOpConvUint64ToUint16:
5698 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005699 convOp = spv::OpUConvert;
5700 break;
5701
John Kessenich66011cb2018-03-06 16:12:04 -07005702 case glslang::EOpConvInt8ToUint16:
5703 case glslang::EOpConvInt8ToUint:
5704 case glslang::EOpConvInt8ToUint64:
5705 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005706 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005707 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005708 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005709 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005710 case glslang::EOpConvIntToUint64:
5711 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005712 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005713 case glslang::EOpConvInt64ToUint:
5714 case glslang::EOpConvUint8ToInt16:
5715 case glslang::EOpConvUint8ToInt:
5716 case glslang::EOpConvUint8ToInt64:
5717 case glslang::EOpConvUint16ToInt8:
5718 case glslang::EOpConvUint16ToInt:
5719 case glslang::EOpConvUint16ToInt64:
5720 case glslang::EOpConvUintToInt8:
5721 case glslang::EOpConvUintToInt16:
5722 case glslang::EOpConvUintToInt64:
5723 case glslang::EOpConvUint64ToInt8:
5724 case glslang::EOpConvUint64ToInt16:
5725 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005726 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005727 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005728
5729 if (builder.isInSpecConstCodeGenMode()) {
5730 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005731 switch(op) {
5732 case glslang::EOpConvInt16ToUint8:
5733 case glslang::EOpConvIntToUint8:
5734 case glslang::EOpConvInt64ToUint8:
5735 case glslang::EOpConvUint16ToInt8:
5736 case glslang::EOpConvUintToInt8:
5737 case glslang::EOpConvUint64ToInt8:
5738 zero = builder.makeUint8Constant(0);
5739 break;
5740 case glslang::EOpConvInt8ToUint16:
5741 case glslang::EOpConvIntToUint16:
5742 case glslang::EOpConvInt64ToUint16:
5743 case glslang::EOpConvUint8ToInt16:
5744 case glslang::EOpConvUintToInt16:
5745 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005746 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005747 break;
5748 case glslang::EOpConvInt8ToUint:
5749 case glslang::EOpConvInt16ToUint:
5750 case glslang::EOpConvInt64ToUint:
5751 case glslang::EOpConvUint8ToInt:
5752 case glslang::EOpConvUint16ToInt:
5753 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005754 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005755 break;
5756 case glslang::EOpConvInt8ToUint64:
5757 case glslang::EOpConvInt16ToUint64:
5758 case glslang::EOpConvIntToUint64:
5759 case glslang::EOpConvUint8ToInt64:
5760 case glslang::EOpConvUint16ToInt64:
5761 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005762 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005763 break;
5764 default:
5765 assert(false && "Default missing");
5766 break;
5767 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005768 zero = makeSmearedConstant(zero, vectorSize);
5769 // Use OpIAdd, instead of OpBitcast to do the conversion when
5770 // generating for OpSpecConstantOp instruction.
5771 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5772 }
5773 // For normal run-time conversion instruction, use OpBitcast.
5774 convOp = spv::OpBitcast;
5775 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005776 default:
5777 break;
5778 }
5779
5780 spv::Id result = 0;
5781 if (convOp == spv::OpNop)
5782 return result;
5783
5784 if (convOp == spv::OpSelect) {
5785 zero = makeSmearedConstant(zero, vectorSize);
5786 one = makeSmearedConstant(one, vectorSize);
5787 result = builder.createTriOp(convOp, destType, operand, one, zero);
5788 } else
5789 result = builder.createUnaryOp(convOp, destType, operand);
5790
John Kessenichead86222018-03-28 18:01:20 -06005791 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005792 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005793 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005794}
5795
5796spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5797{
5798 if (vectorSize == 0)
5799 return constant;
5800
5801 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5802 std::vector<spv::Id> components;
5803 for (int c = 0; c < vectorSize; ++c)
5804 components.push_back(constant);
5805 return builder.makeCompositeConstant(vectorTypeId, components);
5806}
5807
John Kessenich426394d2015-07-23 10:22:48 -06005808// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005809spv::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 -06005810{
5811 spv::Op opCode = spv::OpNop;
5812
5813 switch (op) {
5814 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005815 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005816 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005817 opCode = spv::OpAtomicIAdd;
5818 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005819 case glslang::EOpAtomicCounterSubtract:
5820 opCode = spv::OpAtomicISub;
5821 break;
John Kessenich426394d2015-07-23 10:22:48 -06005822 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005823 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005824 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005825 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005826 break;
5827 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005828 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005829 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005830 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005831 break;
5832 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005833 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005834 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005835 opCode = spv::OpAtomicAnd;
5836 break;
5837 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005838 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005839 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005840 opCode = spv::OpAtomicOr;
5841 break;
5842 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005843 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005844 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005845 opCode = spv::OpAtomicXor;
5846 break;
5847 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005848 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005849 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005850 opCode = spv::OpAtomicExchange;
5851 break;
5852 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005853 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005854 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005855 opCode = spv::OpAtomicCompareExchange;
5856 break;
5857 case glslang::EOpAtomicCounterIncrement:
5858 opCode = spv::OpAtomicIIncrement;
5859 break;
5860 case glslang::EOpAtomicCounterDecrement:
5861 opCode = spv::OpAtomicIDecrement;
5862 break;
5863 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05005864 case glslang::EOpImageAtomicLoad:
5865 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06005866 opCode = spv::OpAtomicLoad;
5867 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05005868 case glslang::EOpAtomicStore:
5869 case glslang::EOpImageAtomicStore:
5870 opCode = spv::OpAtomicStore;
5871 break;
John Kessenich426394d2015-07-23 10:22:48 -06005872 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005873 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005874 break;
5875 }
5876
Rex Xue8fe8b02017-09-26 15:42:56 +08005877 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5878 builder.addCapability(spv::CapabilityInt64Atomics);
5879
John Kessenich426394d2015-07-23 10:22:48 -06005880 // Sort out the operands
5881 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05005882 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06005883 // - compare-exchange swaps the value and comparator
5884 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005885 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05005886 spv::Id pointerId = 0, compareId = 0, valueId = 0;
5887 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
5888 spv::Id scopeId;
5889 if (glslangIntermediate->usingVulkanMemoryModel()) {
5890 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
5891 } else {
5892 scopeId = builder.makeUintConstant(spv::ScopeDevice);
5893 }
5894 // semantics default to relaxed
5895 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
5896 spv::Id semanticsId2 = semanticsId;
5897
5898 pointerId = operands[0];
5899 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
5900 // no additional operands
5901 } else if (opCode == spv::OpAtomicCompareExchange) {
5902 compareId = operands[1];
5903 valueId = operands[2];
5904 if (operands.size() > 3) {
5905 scopeId = operands[3];
5906 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
5907 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
5908 }
5909 } else if (opCode == spv::OpAtomicLoad) {
5910 if (operands.size() > 1) {
5911 scopeId = operands[1];
5912 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
5913 }
5914 } else {
5915 // atomic store or RMW
5916 valueId = operands[1];
5917 if (operands.size() > 2) {
5918 scopeId = operands[2];
5919 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
5920 }
Rex Xu04db3f52015-09-16 11:44:02 +08005921 }
John Kessenich426394d2015-07-23 10:22:48 -06005922
Jeff Bolz36831c92018-09-05 10:11:41 -05005923 // Check for capabilities
5924 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
5925 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
5926 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
5927 }
John Kessenich426394d2015-07-23 10:22:48 -06005928
Jeff Bolz36831c92018-09-05 10:11:41 -05005929 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
5930 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
5931 }
John Kessenich48d6e792017-10-06 21:21:48 -06005932
Jeff Bolz36831c92018-09-05 10:11:41 -05005933 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5934 spvAtomicOperands.push_back(pointerId);
5935 spvAtomicOperands.push_back(scopeId);
5936 spvAtomicOperands.push_back(semanticsId);
5937 if (opCode == spv::OpAtomicCompareExchange) {
5938 spvAtomicOperands.push_back(semanticsId2);
5939 spvAtomicOperands.push_back(valueId);
5940 spvAtomicOperands.push_back(compareId);
5941 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
5942 spvAtomicOperands.push_back(valueId);
5943 }
John Kessenich48d6e792017-10-06 21:21:48 -06005944
Jeff Bolz36831c92018-09-05 10:11:41 -05005945 if (opCode == spv::OpAtomicStore) {
5946 builder.createNoResultOp(opCode, spvAtomicOperands);
5947 return 0;
5948 } else {
5949 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5950
5951 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5952 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5953 if (op == glslang::EOpAtomicCounterDecrement)
5954 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5955
5956 return resultId;
5957 }
John Kessenich426394d2015-07-23 10:22:48 -06005958}
5959
John Kessenich91cef522016-05-05 16:45:40 -06005960// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005961spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005962{
Corentin Walleze7061422018-08-08 15:20:15 +02005963#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07005964 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5965 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02005966#endif
Rex Xu9d93a232016-05-05 12:30:44 +08005967
Rex Xu51596642016-09-21 18:56:12 +08005968 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06005969 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005970 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5971
chaocf200da82016-12-20 12:44:35 -08005972 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5973 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005974 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5975 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005976 } else if (op == glslang::EOpAnyInvocation ||
5977 op == glslang::EOpAllInvocations ||
5978 op == glslang::EOpAllInvocationsEqual) {
5979 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5980 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005981 } else {
5982 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005983#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005984 if (op == glslang::EOpMinInvocationsNonUniform ||
5985 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005986 op == glslang::EOpAddInvocationsNonUniform ||
5987 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5988 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5989 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5990 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5991 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5992 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005993 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005994#endif
Rex Xu51596642016-09-21 18:56:12 +08005995
Rex Xu9d93a232016-05-05 12:30:44 +08005996#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005997 switch (op) {
5998 case glslang::EOpMinInvocations:
5999 case glslang::EOpMaxInvocations:
6000 case glslang::EOpAddInvocations:
6001 case glslang::EOpMinInvocationsNonUniform:
6002 case glslang::EOpMaxInvocationsNonUniform:
6003 case glslang::EOpAddInvocationsNonUniform:
6004 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08006005 break;
6006 case glslang::EOpMinInvocationsInclusiveScan:
6007 case glslang::EOpMaxInvocationsInclusiveScan:
6008 case glslang::EOpAddInvocationsInclusiveScan:
6009 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6010 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6011 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6012 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006013 break;
6014 case glslang::EOpMinInvocationsExclusiveScan:
6015 case glslang::EOpMaxInvocationsExclusiveScan:
6016 case glslang::EOpAddInvocationsExclusiveScan:
6017 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6018 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6019 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6020 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08006021 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07006022 default:
6023 break;
Rex Xu430ef402016-10-14 17:22:23 +08006024 }
John Kessenich149afc32018-08-14 13:31:43 -06006025 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6026 spvGroupOperands.push_back(scope);
6027 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006028 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006029 spvGroupOperands.push_back(groupOp);
6030 }
Rex Xu9d93a232016-05-05 12:30:44 +08006031#endif
Rex Xu51596642016-09-21 18:56:12 +08006032 }
6033
John Kessenich149afc32018-08-14 13:31:43 -06006034 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
6035 spv::IdImmediate op = { true, *opIt };
6036 spvGroupOperands.push_back(op);
6037 }
John Kessenich91cef522016-05-05 16:45:40 -06006038
6039 switch (op) {
6040 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006041 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08006042 break;
John Kessenich91cef522016-05-05 16:45:40 -06006043 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006044 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08006045 break;
John Kessenich91cef522016-05-05 16:45:40 -06006046 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08006047 opCode = spv::OpSubgroupAllEqualKHR;
6048 break;
Rex Xu51596642016-09-21 18:56:12 +08006049 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08006050 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08006051 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006052 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006053 break;
6054 case glslang::EOpReadFirstInvocation:
6055 opCode = spv::OpSubgroupFirstInvocationKHR;
6056 break;
6057 case glslang::EOpBallot:
6058 {
6059 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
6060 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
6061 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
6062 //
6063 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
6064 //
6065 spv::Id uintType = builder.makeUintType(32);
6066 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
6067 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
6068
6069 std::vector<spv::Id> components;
6070 components.push_back(builder.createCompositeExtract(result, uintType, 0));
6071 components.push_back(builder.createCompositeExtract(result, uintType, 1));
6072
6073 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
6074 return builder.createUnaryOp(spv::OpBitcast, typeId,
6075 builder.createCompositeConstruct(uvec2Type, components));
6076 }
6077
Rex Xu9d93a232016-05-05 12:30:44 +08006078#ifdef AMD_EXTENSIONS
6079 case glslang::EOpMinInvocations:
6080 case glslang::EOpMaxInvocations:
6081 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08006082 case glslang::EOpMinInvocationsInclusiveScan:
6083 case glslang::EOpMaxInvocationsInclusiveScan:
6084 case glslang::EOpAddInvocationsInclusiveScan:
6085 case glslang::EOpMinInvocationsExclusiveScan:
6086 case glslang::EOpMaxInvocationsExclusiveScan:
6087 case glslang::EOpAddInvocationsExclusiveScan:
6088 if (op == glslang::EOpMinInvocations ||
6089 op == glslang::EOpMinInvocationsInclusiveScan ||
6090 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006091 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006092 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006093 else {
6094 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006095 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006096 else
Rex Xu51596642016-09-21 18:56:12 +08006097 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08006098 }
Rex Xu430ef402016-10-14 17:22:23 +08006099 } else if (op == glslang::EOpMaxInvocations ||
6100 op == glslang::EOpMaxInvocationsInclusiveScan ||
6101 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08006102 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006103 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006104 else {
6105 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006106 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006107 else
Rex Xu51596642016-09-21 18:56:12 +08006108 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08006109 }
6110 } else {
6111 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006112 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006113 else
Rex Xu51596642016-09-21 18:56:12 +08006114 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08006115 }
6116
Rex Xu2bbbe062016-08-23 15:41:05 +08006117 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006118 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006119
6120 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006121 case glslang::EOpMinInvocationsNonUniform:
6122 case glslang::EOpMaxInvocationsNonUniform:
6123 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08006124 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
6125 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
6126 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
6127 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
6128 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
6129 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
6130 if (op == glslang::EOpMinInvocationsNonUniform ||
6131 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
6132 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006133 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006134 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006135 else {
6136 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006137 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006138 else
Rex Xu51596642016-09-21 18:56:12 +08006139 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006140 }
6141 }
Rex Xu430ef402016-10-14 17:22:23 +08006142 else if (op == glslang::EOpMaxInvocationsNonUniform ||
6143 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
6144 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08006145 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006146 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006147 else {
6148 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08006149 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006150 else
Rex Xu51596642016-09-21 18:56:12 +08006151 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006152 }
6153 }
6154 else {
6155 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08006156 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006157 else
Rex Xu51596642016-09-21 18:56:12 +08006158 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08006159 }
6160
Rex Xu2bbbe062016-08-23 15:41:05 +08006161 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08006162 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08006163
6164 break;
Rex Xu9d93a232016-05-05 12:30:44 +08006165#endif
John Kessenich91cef522016-05-05 16:45:40 -06006166 default:
6167 logger->missingFunctionality("invocation operation");
6168 return spv::NoResult;
6169 }
Rex Xu51596642016-09-21 18:56:12 +08006170
6171 assert(opCode != spv::OpNop);
6172 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06006173}
6174
Rex Xu2bbbe062016-08-23 15:41:05 +08006175// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06006176spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
6177 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08006178{
Rex Xub7072052016-09-26 15:53:40 +08006179#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08006180 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6181 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08006182 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08006183 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08006184 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
6185 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
6186 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08006187#else
6188 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
6189 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08006190 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
6191 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08006192#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08006193
6194 // Handle group invocation operations scalar by scalar.
6195 // The result type is the same type as the original type.
6196 // The algorithm is to:
6197 // - break the vector into scalars
6198 // - apply the operation to each scalar
6199 // - make a vector out the scalar results
6200
6201 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08006202 int numComponents = builder.getNumComponents(operands[0]);
6203 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08006204 std::vector<spv::Id> results;
6205
6206 // do each scalar op
6207 for (int comp = 0; comp < numComponents; ++comp) {
6208 std::vector<unsigned int> indexes;
6209 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06006210 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
6211 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08006212 if (op == spv::OpSubgroupReadInvocationKHR) {
6213 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006214 spv::IdImmediate operand = { true, operands[1] };
6215 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08006216 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06006217 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6218 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08006219 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06006220 spv::IdImmediate operand = { true, operands[1] };
6221 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08006222 } else {
John Kessenich149afc32018-08-14 13:31:43 -06006223 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6224 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06006225 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006226 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08006227 spvGroupOperands.push_back(scalar);
6228 }
Rex Xu2bbbe062016-08-23 15:41:05 +08006229
Rex Xub7072052016-09-26 15:53:40 +08006230 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08006231 }
6232
6233 // put the pieces together
6234 return builder.createCompositeConstruct(typeId, results);
6235}
Rex Xu2bbbe062016-08-23 15:41:05 +08006236
John Kessenich66011cb2018-03-06 16:12:04 -07006237// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06006238spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
6239 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07006240{
6241 // Add the required capabilities.
6242 switch (op) {
6243 case glslang::EOpSubgroupElect:
6244 builder.addCapability(spv::CapabilityGroupNonUniform);
6245 break;
6246 case glslang::EOpSubgroupAll:
6247 case glslang::EOpSubgroupAny:
6248 case glslang::EOpSubgroupAllEqual:
6249 builder.addCapability(spv::CapabilityGroupNonUniform);
6250 builder.addCapability(spv::CapabilityGroupNonUniformVote);
6251 break;
6252 case glslang::EOpSubgroupBroadcast:
6253 case glslang::EOpSubgroupBroadcastFirst:
6254 case glslang::EOpSubgroupBallot:
6255 case glslang::EOpSubgroupInverseBallot:
6256 case glslang::EOpSubgroupBallotBitExtract:
6257 case glslang::EOpSubgroupBallotBitCount:
6258 case glslang::EOpSubgroupBallotInclusiveBitCount:
6259 case glslang::EOpSubgroupBallotExclusiveBitCount:
6260 case glslang::EOpSubgroupBallotFindLSB:
6261 case glslang::EOpSubgroupBallotFindMSB:
6262 builder.addCapability(spv::CapabilityGroupNonUniform);
6263 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
6264 break;
6265 case glslang::EOpSubgroupShuffle:
6266 case glslang::EOpSubgroupShuffleXor:
6267 builder.addCapability(spv::CapabilityGroupNonUniform);
6268 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
6269 break;
6270 case glslang::EOpSubgroupShuffleUp:
6271 case glslang::EOpSubgroupShuffleDown:
6272 builder.addCapability(spv::CapabilityGroupNonUniform);
6273 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
6274 break;
6275 case glslang::EOpSubgroupAdd:
6276 case glslang::EOpSubgroupMul:
6277 case glslang::EOpSubgroupMin:
6278 case glslang::EOpSubgroupMax:
6279 case glslang::EOpSubgroupAnd:
6280 case glslang::EOpSubgroupOr:
6281 case glslang::EOpSubgroupXor:
6282 case glslang::EOpSubgroupInclusiveAdd:
6283 case glslang::EOpSubgroupInclusiveMul:
6284 case glslang::EOpSubgroupInclusiveMin:
6285 case glslang::EOpSubgroupInclusiveMax:
6286 case glslang::EOpSubgroupInclusiveAnd:
6287 case glslang::EOpSubgroupInclusiveOr:
6288 case glslang::EOpSubgroupInclusiveXor:
6289 case glslang::EOpSubgroupExclusiveAdd:
6290 case glslang::EOpSubgroupExclusiveMul:
6291 case glslang::EOpSubgroupExclusiveMin:
6292 case glslang::EOpSubgroupExclusiveMax:
6293 case glslang::EOpSubgroupExclusiveAnd:
6294 case glslang::EOpSubgroupExclusiveOr:
6295 case glslang::EOpSubgroupExclusiveXor:
6296 builder.addCapability(spv::CapabilityGroupNonUniform);
6297 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6298 break;
6299 case glslang::EOpSubgroupClusteredAdd:
6300 case glslang::EOpSubgroupClusteredMul:
6301 case glslang::EOpSubgroupClusteredMin:
6302 case glslang::EOpSubgroupClusteredMax:
6303 case glslang::EOpSubgroupClusteredAnd:
6304 case glslang::EOpSubgroupClusteredOr:
6305 case glslang::EOpSubgroupClusteredXor:
6306 builder.addCapability(spv::CapabilityGroupNonUniform);
6307 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6308 break;
6309 case glslang::EOpSubgroupQuadBroadcast:
6310 case glslang::EOpSubgroupQuadSwapHorizontal:
6311 case glslang::EOpSubgroupQuadSwapVertical:
6312 case glslang::EOpSubgroupQuadSwapDiagonal:
6313 builder.addCapability(spv::CapabilityGroupNonUniform);
6314 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6315 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006316#ifdef NV_EXTENSIONS
6317 case glslang::EOpSubgroupPartitionedAdd:
6318 case glslang::EOpSubgroupPartitionedMul:
6319 case glslang::EOpSubgroupPartitionedMin:
6320 case glslang::EOpSubgroupPartitionedMax:
6321 case glslang::EOpSubgroupPartitionedAnd:
6322 case glslang::EOpSubgroupPartitionedOr:
6323 case glslang::EOpSubgroupPartitionedXor:
6324 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6325 case glslang::EOpSubgroupPartitionedInclusiveMul:
6326 case glslang::EOpSubgroupPartitionedInclusiveMin:
6327 case glslang::EOpSubgroupPartitionedInclusiveMax:
6328 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6329 case glslang::EOpSubgroupPartitionedInclusiveOr:
6330 case glslang::EOpSubgroupPartitionedInclusiveXor:
6331 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6332 case glslang::EOpSubgroupPartitionedExclusiveMul:
6333 case glslang::EOpSubgroupPartitionedExclusiveMin:
6334 case glslang::EOpSubgroupPartitionedExclusiveMax:
6335 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6336 case glslang::EOpSubgroupPartitionedExclusiveOr:
6337 case glslang::EOpSubgroupPartitionedExclusiveXor:
6338 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6339 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6340 break;
6341#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006342 default: assert(0 && "Unhandled subgroup operation!");
6343 }
6344
6345 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6346 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6347 const bool isBool = typeProxy == glslang::EbtBool;
6348
6349 spv::Op opCode = spv::OpNop;
6350
6351 // Figure out which opcode to use.
6352 switch (op) {
6353 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6354 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6355 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6356 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6357 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6358 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6359 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6360 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6361 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6362 case glslang::EOpSubgroupBallotBitCount:
6363 case glslang::EOpSubgroupBallotInclusiveBitCount:
6364 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6365 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6366 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6367 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6368 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6369 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6370 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6371 case glslang::EOpSubgroupAdd:
6372 case glslang::EOpSubgroupInclusiveAdd:
6373 case glslang::EOpSubgroupExclusiveAdd:
6374 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006375#ifdef NV_EXTENSIONS
6376 case glslang::EOpSubgroupPartitionedAdd:
6377 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6378 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6379#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006380 if (isFloat) {
6381 opCode = spv::OpGroupNonUniformFAdd;
6382 } else {
6383 opCode = spv::OpGroupNonUniformIAdd;
6384 }
6385 break;
6386 case glslang::EOpSubgroupMul:
6387 case glslang::EOpSubgroupInclusiveMul:
6388 case glslang::EOpSubgroupExclusiveMul:
6389 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006390#ifdef NV_EXTENSIONS
6391 case glslang::EOpSubgroupPartitionedMul:
6392 case glslang::EOpSubgroupPartitionedInclusiveMul:
6393 case glslang::EOpSubgroupPartitionedExclusiveMul:
6394#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006395 if (isFloat) {
6396 opCode = spv::OpGroupNonUniformFMul;
6397 } else {
6398 opCode = spv::OpGroupNonUniformIMul;
6399 }
6400 break;
6401 case glslang::EOpSubgroupMin:
6402 case glslang::EOpSubgroupInclusiveMin:
6403 case glslang::EOpSubgroupExclusiveMin:
6404 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006405#ifdef NV_EXTENSIONS
6406 case glslang::EOpSubgroupPartitionedMin:
6407 case glslang::EOpSubgroupPartitionedInclusiveMin:
6408 case glslang::EOpSubgroupPartitionedExclusiveMin:
6409#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006410 if (isFloat) {
6411 opCode = spv::OpGroupNonUniformFMin;
6412 } else if (isUnsigned) {
6413 opCode = spv::OpGroupNonUniformUMin;
6414 } else {
6415 opCode = spv::OpGroupNonUniformSMin;
6416 }
6417 break;
6418 case glslang::EOpSubgroupMax:
6419 case glslang::EOpSubgroupInclusiveMax:
6420 case glslang::EOpSubgroupExclusiveMax:
6421 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006422#ifdef NV_EXTENSIONS
6423 case glslang::EOpSubgroupPartitionedMax:
6424 case glslang::EOpSubgroupPartitionedInclusiveMax:
6425 case glslang::EOpSubgroupPartitionedExclusiveMax:
6426#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006427 if (isFloat) {
6428 opCode = spv::OpGroupNonUniformFMax;
6429 } else if (isUnsigned) {
6430 opCode = spv::OpGroupNonUniformUMax;
6431 } else {
6432 opCode = spv::OpGroupNonUniformSMax;
6433 }
6434 break;
6435 case glslang::EOpSubgroupAnd:
6436 case glslang::EOpSubgroupInclusiveAnd:
6437 case glslang::EOpSubgroupExclusiveAnd:
6438 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006439#ifdef NV_EXTENSIONS
6440 case glslang::EOpSubgroupPartitionedAnd:
6441 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6442 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6443#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006444 if (isBool) {
6445 opCode = spv::OpGroupNonUniformLogicalAnd;
6446 } else {
6447 opCode = spv::OpGroupNonUniformBitwiseAnd;
6448 }
6449 break;
6450 case glslang::EOpSubgroupOr:
6451 case glslang::EOpSubgroupInclusiveOr:
6452 case glslang::EOpSubgroupExclusiveOr:
6453 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006454#ifdef NV_EXTENSIONS
6455 case glslang::EOpSubgroupPartitionedOr:
6456 case glslang::EOpSubgroupPartitionedInclusiveOr:
6457 case glslang::EOpSubgroupPartitionedExclusiveOr:
6458#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006459 if (isBool) {
6460 opCode = spv::OpGroupNonUniformLogicalOr;
6461 } else {
6462 opCode = spv::OpGroupNonUniformBitwiseOr;
6463 }
6464 break;
6465 case glslang::EOpSubgroupXor:
6466 case glslang::EOpSubgroupInclusiveXor:
6467 case glslang::EOpSubgroupExclusiveXor:
6468 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006469#ifdef NV_EXTENSIONS
6470 case glslang::EOpSubgroupPartitionedXor:
6471 case glslang::EOpSubgroupPartitionedInclusiveXor:
6472 case glslang::EOpSubgroupPartitionedExclusiveXor:
6473#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006474 if (isBool) {
6475 opCode = spv::OpGroupNonUniformLogicalXor;
6476 } else {
6477 opCode = spv::OpGroupNonUniformBitwiseXor;
6478 }
6479 break;
6480 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6481 case glslang::EOpSubgroupQuadSwapHorizontal:
6482 case glslang::EOpSubgroupQuadSwapVertical:
6483 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6484 default: assert(0 && "Unhandled subgroup operation!");
6485 }
6486
John Kessenich149afc32018-08-14 13:31:43 -06006487 // get the right Group Operation
6488 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006489 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006490 default:
6491 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006492 case glslang::EOpSubgroupBallotBitCount:
6493 case glslang::EOpSubgroupAdd:
6494 case glslang::EOpSubgroupMul:
6495 case glslang::EOpSubgroupMin:
6496 case glslang::EOpSubgroupMax:
6497 case glslang::EOpSubgroupAnd:
6498 case glslang::EOpSubgroupOr:
6499 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006500 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006501 break;
6502 case glslang::EOpSubgroupBallotInclusiveBitCount:
6503 case glslang::EOpSubgroupInclusiveAdd:
6504 case glslang::EOpSubgroupInclusiveMul:
6505 case glslang::EOpSubgroupInclusiveMin:
6506 case glslang::EOpSubgroupInclusiveMax:
6507 case glslang::EOpSubgroupInclusiveAnd:
6508 case glslang::EOpSubgroupInclusiveOr:
6509 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006510 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006511 break;
6512 case glslang::EOpSubgroupBallotExclusiveBitCount:
6513 case glslang::EOpSubgroupExclusiveAdd:
6514 case glslang::EOpSubgroupExclusiveMul:
6515 case glslang::EOpSubgroupExclusiveMin:
6516 case glslang::EOpSubgroupExclusiveMax:
6517 case glslang::EOpSubgroupExclusiveAnd:
6518 case glslang::EOpSubgroupExclusiveOr:
6519 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006520 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006521 break;
6522 case glslang::EOpSubgroupClusteredAdd:
6523 case glslang::EOpSubgroupClusteredMul:
6524 case glslang::EOpSubgroupClusteredMin:
6525 case glslang::EOpSubgroupClusteredMax:
6526 case glslang::EOpSubgroupClusteredAnd:
6527 case glslang::EOpSubgroupClusteredOr:
6528 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006529 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006530 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006531#ifdef NV_EXTENSIONS
6532 case glslang::EOpSubgroupPartitionedAdd:
6533 case glslang::EOpSubgroupPartitionedMul:
6534 case glslang::EOpSubgroupPartitionedMin:
6535 case glslang::EOpSubgroupPartitionedMax:
6536 case glslang::EOpSubgroupPartitionedAnd:
6537 case glslang::EOpSubgroupPartitionedOr:
6538 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006539 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006540 break;
6541 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6542 case glslang::EOpSubgroupPartitionedInclusiveMul:
6543 case glslang::EOpSubgroupPartitionedInclusiveMin:
6544 case glslang::EOpSubgroupPartitionedInclusiveMax:
6545 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6546 case glslang::EOpSubgroupPartitionedInclusiveOr:
6547 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006548 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006549 break;
6550 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6551 case glslang::EOpSubgroupPartitionedExclusiveMul:
6552 case glslang::EOpSubgroupPartitionedExclusiveMin:
6553 case glslang::EOpSubgroupPartitionedExclusiveMax:
6554 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6555 case glslang::EOpSubgroupPartitionedExclusiveOr:
6556 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006557 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006558 break;
6559#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006560 }
6561
John Kessenich149afc32018-08-14 13:31:43 -06006562 // build the instruction
6563 std::vector<spv::IdImmediate> spvGroupOperands;
6564
6565 // Every operation begins with the Execution Scope operand.
6566 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6567 spvGroupOperands.push_back(executionScope);
6568
6569 // Next, for all operations that use a Group Operation, push that as an operand.
6570 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006571 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006572 spvGroupOperands.push_back(groupOperand);
6573 }
6574
John Kessenich66011cb2018-03-06 16:12:04 -07006575 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006576 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6577 spv::IdImmediate operand = { true, *opIt };
6578 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006579 }
6580
6581 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006582 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006583 switch (op) {
6584 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006585 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6586 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6587 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6588 }
6589 if (directionId != spv::NoResult) {
6590 spv::IdImmediate direction = { true, directionId };
6591 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006592 }
6593
6594 return builder.createOp(opCode, typeId, spvGroupOperands);
6595}
6596
John Kessenich5e4b1242015-08-06 22:53:06 -06006597spv::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 -06006598{
John Kessenich66011cb2018-03-06 16:12:04 -07006599 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6600 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006601
John Kessenich140f3df2015-06-26 16:58:36 -06006602 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006603 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006604 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006605 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006606 spv::Id typeId0 = 0;
6607 if (consumedOperands > 0)
6608 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006609 spv::Id typeId1 = 0;
6610 if (consumedOperands > 1)
6611 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006612 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006613
6614 switch (op) {
6615 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006616 if (isFloat)
6617 libCall = spv::GLSLstd450FMin;
6618 else if (isUnsigned)
6619 libCall = spv::GLSLstd450UMin;
6620 else
6621 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006622 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006623 break;
6624 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006625 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006626 break;
6627 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006628 if (isFloat)
6629 libCall = spv::GLSLstd450FMax;
6630 else if (isUnsigned)
6631 libCall = spv::GLSLstd450UMax;
6632 else
6633 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006634 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006635 break;
6636 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006637 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006638 break;
6639 case glslang::EOpDot:
6640 opCode = spv::OpDot;
6641 break;
6642 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006643 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006644 break;
6645
6646 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006647 if (isFloat)
6648 libCall = spv::GLSLstd450FClamp;
6649 else if (isUnsigned)
6650 libCall = spv::GLSLstd450UClamp;
6651 else
6652 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006653 builder.promoteScalar(precision, operands.front(), operands[1]);
6654 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006655 break;
6656 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006657 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6658 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006659 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006660 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006661 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006662 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006663 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006664 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006665 break;
6666 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006667 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006668 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006669 break;
6670 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006671 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006672 builder.promoteScalar(precision, operands[0], operands[2]);
6673 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006674 break;
6675
6676 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006677 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006678 break;
6679 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006680 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006681 break;
6682 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006683 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006684 break;
6685 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006686 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006687 break;
6688 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006689 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006690 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006691 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006692#ifdef AMD_EXTENSIONS
6693 if (typeProxy == glslang::EbtFloat16)
6694 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6695#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006696 libCall = spv::GLSLstd450InterpolateAtSample;
6697 break;
6698 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006699#ifdef AMD_EXTENSIONS
6700 if (typeProxy == glslang::EbtFloat16)
6701 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6702#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006703 libCall = spv::GLSLstd450InterpolateAtOffset;
6704 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006705 case glslang::EOpAddCarry:
6706 opCode = spv::OpIAddCarry;
6707 typeId = builder.makeStructResultType(typeId0, typeId0);
6708 consumedOperands = 2;
6709 break;
6710 case glslang::EOpSubBorrow:
6711 opCode = spv::OpISubBorrow;
6712 typeId = builder.makeStructResultType(typeId0, typeId0);
6713 consumedOperands = 2;
6714 break;
6715 case glslang::EOpUMulExtended:
6716 opCode = spv::OpUMulExtended;
6717 typeId = builder.makeStructResultType(typeId0, typeId0);
6718 consumedOperands = 2;
6719 break;
6720 case glslang::EOpIMulExtended:
6721 opCode = spv::OpSMulExtended;
6722 typeId = builder.makeStructResultType(typeId0, typeId0);
6723 consumedOperands = 2;
6724 break;
6725 case glslang::EOpBitfieldExtract:
6726 if (isUnsigned)
6727 opCode = spv::OpBitFieldUExtract;
6728 else
6729 opCode = spv::OpBitFieldSExtract;
6730 break;
6731 case glslang::EOpBitfieldInsert:
6732 opCode = spv::OpBitFieldInsert;
6733 break;
6734
6735 case glslang::EOpFma:
6736 libCall = spv::GLSLstd450Fma;
6737 break;
6738 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006739 {
6740 libCall = spv::GLSLstd450FrexpStruct;
6741 assert(builder.isPointerType(typeId1));
6742 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006743 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006744#ifdef AMD_EXTENSIONS
6745 if (width == 16)
6746 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6747 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6748#endif
Rex Xu470026f2017-03-29 17:12:40 +08006749 if (builder.getNumComponents(operands[0]) == 1)
6750 frexpIntType = builder.makeIntegerType(width, true);
6751 else
6752 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6753 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6754 consumedOperands = 1;
6755 }
John Kessenich55e7d112015-11-15 21:33:39 -07006756 break;
6757 case glslang::EOpLdexp:
6758 libCall = spv::GLSLstd450Ldexp;
6759 break;
6760
Rex Xu574ab042016-04-14 16:53:07 +08006761 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006762 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006763
John Kessenich66011cb2018-03-06 16:12:04 -07006764 case glslang::EOpSubgroupBroadcast:
6765 case glslang::EOpSubgroupBallotBitExtract:
6766 case glslang::EOpSubgroupShuffle:
6767 case glslang::EOpSubgroupShuffleXor:
6768 case glslang::EOpSubgroupShuffleUp:
6769 case glslang::EOpSubgroupShuffleDown:
6770 case glslang::EOpSubgroupClusteredAdd:
6771 case glslang::EOpSubgroupClusteredMul:
6772 case glslang::EOpSubgroupClusteredMin:
6773 case glslang::EOpSubgroupClusteredMax:
6774 case glslang::EOpSubgroupClusteredAnd:
6775 case glslang::EOpSubgroupClusteredOr:
6776 case glslang::EOpSubgroupClusteredXor:
6777 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006778#ifdef NV_EXTENSIONS
6779 case glslang::EOpSubgroupPartitionedAdd:
6780 case glslang::EOpSubgroupPartitionedMul:
6781 case glslang::EOpSubgroupPartitionedMin:
6782 case glslang::EOpSubgroupPartitionedMax:
6783 case glslang::EOpSubgroupPartitionedAnd:
6784 case glslang::EOpSubgroupPartitionedOr:
6785 case glslang::EOpSubgroupPartitionedXor:
6786 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6787 case glslang::EOpSubgroupPartitionedInclusiveMul:
6788 case glslang::EOpSubgroupPartitionedInclusiveMin:
6789 case glslang::EOpSubgroupPartitionedInclusiveMax:
6790 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6791 case glslang::EOpSubgroupPartitionedInclusiveOr:
6792 case glslang::EOpSubgroupPartitionedInclusiveXor:
6793 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6794 case glslang::EOpSubgroupPartitionedExclusiveMul:
6795 case glslang::EOpSubgroupPartitionedExclusiveMin:
6796 case glslang::EOpSubgroupPartitionedExclusiveMax:
6797 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6798 case glslang::EOpSubgroupPartitionedExclusiveOr:
6799 case glslang::EOpSubgroupPartitionedExclusiveXor:
6800#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006801 return createSubgroupOperation(op, typeId, operands, typeProxy);
6802
Rex Xu9d93a232016-05-05 12:30:44 +08006803#ifdef AMD_EXTENSIONS
6804 case glslang::EOpSwizzleInvocations:
6805 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6806 libCall = spv::SwizzleInvocationsAMD;
6807 break;
6808 case glslang::EOpSwizzleInvocationsMasked:
6809 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6810 libCall = spv::SwizzleInvocationsMaskedAMD;
6811 break;
6812 case glslang::EOpWriteInvocation:
6813 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6814 libCall = spv::WriteInvocationAMD;
6815 break;
6816
6817 case glslang::EOpMin3:
6818 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6819 if (isFloat)
6820 libCall = spv::FMin3AMD;
6821 else {
6822 if (isUnsigned)
6823 libCall = spv::UMin3AMD;
6824 else
6825 libCall = spv::SMin3AMD;
6826 }
6827 break;
6828 case glslang::EOpMax3:
6829 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6830 if (isFloat)
6831 libCall = spv::FMax3AMD;
6832 else {
6833 if (isUnsigned)
6834 libCall = spv::UMax3AMD;
6835 else
6836 libCall = spv::SMax3AMD;
6837 }
6838 break;
6839 case glslang::EOpMid3:
6840 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6841 if (isFloat)
6842 libCall = spv::FMid3AMD;
6843 else {
6844 if (isUnsigned)
6845 libCall = spv::UMid3AMD;
6846 else
6847 libCall = spv::SMid3AMD;
6848 }
6849 break;
6850
6851 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006852 if (typeProxy == glslang::EbtFloat16)
6853 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08006854 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6855 libCall = spv::InterpolateAtVertexAMD;
6856 break;
6857#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05006858 case glslang::EOpBarrier:
6859 {
6860 // This is for the extended controlBarrier function, with four operands.
6861 // The unextended barrier() goes through createNoArgOperation.
6862 assert(operands.size() == 4);
6863 unsigned int executionScope = builder.getConstantScalar(operands[0]);
6864 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
6865 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
6866 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6867 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6868 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6869 }
6870 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
6871 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6872 }
6873 return 0;
6874 }
6875 break;
6876 case glslang::EOpMemoryBarrier:
6877 {
6878 // This is for the extended memoryBarrier function, with three operands.
6879 // The unextended memoryBarrier() goes through createNoArgOperation.
6880 assert(operands.size() == 3);
6881 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
6882 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
6883 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6884 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6885 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6886 }
6887 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
6888 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6889 }
6890 return 0;
6891 }
6892 break;
Chao Chen3c366992018-09-19 11:41:59 -07006893
6894#ifdef NV_EXTENSIONS
Chao Chenb50c02e2018-09-19 11:42:24 -07006895 case glslang::EOpReportIntersectionNV:
6896 {
6897 typeId = builder.makeBoolType();
Ashwin Leleff1783d2018-10-22 16:41:44 -07006898 opCode = spv::OpReportIntersectionNV;
Chao Chenb50c02e2018-09-19 11:42:24 -07006899 }
6900 break;
6901 case glslang::EOpTraceNV:
6902 {
Ashwin Leleff1783d2018-10-22 16:41:44 -07006903 builder.createNoResultOp(spv::OpTraceNV, operands);
6904 return 0;
6905 }
6906 break;
6907 case glslang::EOpExecuteCallableNV:
6908 {
6909 builder.createNoResultOp(spv::OpExecuteCallableNV, operands);
Chao Chenb50c02e2018-09-19 11:42:24 -07006910 return 0;
6911 }
6912 break;
Chao Chen3c366992018-09-19 11:41:59 -07006913 case glslang::EOpWritePackedPrimitiveIndices4x8NV:
6914 builder.createNoResultOp(spv::OpWritePackedPrimitiveIndices4x8NV, operands);
6915 return 0;
6916#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006917 default:
6918 return 0;
6919 }
6920
6921 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006922 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006923 // Use an extended instruction from the standard library.
6924 // Construct the call arguments, without modifying the original operands vector.
6925 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6926 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006927 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
t.jungb16bea82018-11-15 10:21:36 +01006928 } else if (opCode == spv::OpDot && !isFloat) {
6929 // int dot(int, int)
6930 // NOTE: never called for scalar/vector1, this is turned into simple mul before this can be reached
6931 const int componentCount = builder.getNumComponents(operands[0]);
6932 spv::Id mulOp = builder.createBinOp(spv::OpIMul, builder.getTypeId(operands[0]), operands[0], operands[1]);
6933 builder.setPrecision(mulOp, precision);
6934 id = builder.createCompositeExtract(mulOp, typeId, 0);
6935 for (int i = 1; i < componentCount; ++i) {
6936 builder.setPrecision(id, precision);
6937 id = builder.createBinOp(spv::OpIAdd, typeId, id, builder.createCompositeExtract(operands[0], typeId, i));
6938 }
John Kessenich2359bd02015-12-06 19:29:11 -07006939 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006940 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006941 case 0:
6942 // should all be handled by visitAggregate and createNoArgOperation
6943 assert(0);
6944 return 0;
6945 case 1:
6946 // should all be handled by createUnaryOperation
6947 assert(0);
6948 return 0;
6949 case 2:
6950 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6951 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006952 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006953 // anything 3 or over doesn't have l-value operands, so all should be consumed
6954 assert(consumedOperands == operands.size());
6955 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006956 break;
6957 }
6958 }
6959
John Kessenich55e7d112015-11-15 21:33:39 -07006960 // Decode the return types that were structures
6961 switch (op) {
6962 case glslang::EOpAddCarry:
6963 case glslang::EOpSubBorrow:
6964 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6965 id = builder.createCompositeExtract(id, typeId0, 0);
6966 break;
6967 case glslang::EOpUMulExtended:
6968 case glslang::EOpIMulExtended:
6969 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6970 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6971 break;
6972 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006973 {
6974 assert(operands.size() == 2);
6975 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6976 // "exp" is floating-point type (from HLSL intrinsic)
6977 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6978 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6979 builder.createStore(member1, operands[1]);
6980 } else
6981 // "exp" is integer type (from GLSL built-in function)
6982 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6983 id = builder.createCompositeExtract(id, typeId0, 0);
6984 }
John Kessenich55e7d112015-11-15 21:33:39 -07006985 break;
6986 default:
6987 break;
6988 }
6989
John Kessenich32cfd492016-02-02 12:37:46 -07006990 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006991}
6992
Rex Xu9d93a232016-05-05 12:30:44 +08006993// Intrinsics with no arguments (or no return value, and no precision).
6994spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006995{
Jeff Bolz36831c92018-09-05 10:11:41 -05006996 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
6997 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06006998
6999 switch (op) {
7000 case glslang::EOpEmitVertex:
7001 builder.createNoResultOp(spv::OpEmitVertex);
7002 return 0;
7003 case glslang::EOpEndPrimitive:
7004 builder.createNoResultOp(spv::OpEndPrimitive);
7005 return 0;
7006 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007007 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05007008 if (glslangIntermediate->usingVulkanMemoryModel()) {
7009 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7010 spv::MemorySemanticsOutputMemoryKHRMask |
7011 spv::MemorySemanticsAcquireReleaseMask);
7012 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
7013 } else {
7014 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
7015 }
John Kessenich82979362017-12-11 04:02:24 -07007016 } else {
7017 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7018 spv::MemorySemanticsWorkgroupMemoryMask |
7019 spv::MemorySemanticsAcquireReleaseMask);
7020 }
John Kessenich140f3df2015-06-26 16:58:36 -06007021 return 0;
7022 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05007023 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
7024 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007025 return 0;
7026 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05007027 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
7028 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007029 return 0;
7030 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05007031 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
7032 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007033 return 0;
7034 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05007035 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
7036 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007037 return 0;
7038 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05007039 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
7040 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007041 return 0;
7042 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07007043 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
7044 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06007045 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06007046 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007047 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07007048 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07007049 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007050 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07007051 case glslang::EOpDeviceMemoryBarrier:
7052 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7053 spv::MemorySemanticsImageMemoryMask |
7054 spv::MemorySemanticsAcquireReleaseMask);
7055 return 0;
7056 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
7057 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
7058 spv::MemorySemanticsImageMemoryMask |
7059 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007060 return 0;
7061 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07007062 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7063 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007064 return 0;
7065 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07007066 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
7067 spv::MemorySemanticsWorkgroupMemoryMask |
7068 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06007069 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07007070 case glslang::EOpSubgroupBarrier:
7071 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7072 spv::MemorySemanticsAcquireReleaseMask);
7073 return spv::NoResult;
7074 case glslang::EOpSubgroupMemoryBarrier:
7075 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
7076 spv::MemorySemanticsAcquireReleaseMask);
7077 return spv::NoResult;
7078 case glslang::EOpSubgroupMemoryBarrierBuffer:
7079 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
7080 spv::MemorySemanticsAcquireReleaseMask);
7081 return spv::NoResult;
7082 case glslang::EOpSubgroupMemoryBarrierImage:
7083 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
7084 spv::MemorySemanticsAcquireReleaseMask);
7085 return spv::NoResult;
7086 case glslang::EOpSubgroupMemoryBarrierShared:
7087 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
7088 spv::MemorySemanticsAcquireReleaseMask);
7089 return spv::NoResult;
7090 case glslang::EOpSubgroupElect: {
7091 std::vector<spv::Id> operands;
7092 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
7093 }
Rex Xu9d93a232016-05-05 12:30:44 +08007094#ifdef AMD_EXTENSIONS
7095 case glslang::EOpTime:
7096 {
7097 std::vector<spv::Id> args; // Dummy arguments
7098 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
7099 return builder.setPrecision(id, precision);
7100 }
7101#endif
Chao Chenb50c02e2018-09-19 11:42:24 -07007102#ifdef NV_EXTENSIONS
7103 case glslang::EOpIgnoreIntersectionNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007104 builder.createNoResultOp(spv::OpIgnoreIntersectionNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007105 return 0;
7106 case glslang::EOpTerminateRayNV:
Ashwin Leleff1783d2018-10-22 16:41:44 -07007107 builder.createNoResultOp(spv::OpTerminateRayNV);
Chao Chenb50c02e2018-09-19 11:42:24 -07007108 return 0;
7109#endif
John Kessenich140f3df2015-06-26 16:58:36 -06007110 default:
Lei Zhang17535f72016-05-04 15:55:59 -04007111 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06007112 return 0;
7113 }
7114}
7115
7116spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
7117{
John Kessenich2f273362015-07-18 22:34:27 -06007118 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06007119 spv::Id id;
7120 if (symbolValues.end() != iter) {
7121 id = iter->second;
7122 return id;
7123 }
7124
7125 // it was not found, create it
7126 id = createSpvVariable(symbol);
7127 symbolValues[symbol->getId()] = id;
7128
Rex Xuc884b4a2016-06-29 15:03:44 +08007129 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007130 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
7131 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
7132 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
Chao Chen3c366992018-09-19 11:41:59 -07007133#ifdef NV_EXTENSIONS
7134 addMeshNVDecoration(id, /*member*/ -1, symbol->getType().getQualifier());
7135#endif
John Kessenich6c292d32016-02-15 20:58:50 -07007136 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07007137 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06007138 if (symbol->getQualifier().hasIndex())
7139 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
7140 if (symbol->getQualifier().hasComponent())
7141 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06007142 // atomic counters use this:
7143 if (symbol->getQualifier().hasOffset())
7144 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007145 }
7146
scygan2c864272016-05-18 18:09:17 +02007147 if (symbol->getQualifier().hasLocation())
7148 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07007149 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07007150 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07007151 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06007152 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07007153 }
John Kessenich140f3df2015-06-26 16:58:36 -06007154 if (symbol->getQualifier().hasSet())
7155 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07007156 else if (IsDescriptorResource(symbol->getType())) {
7157 // default to 0
7158 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
7159 }
John Kessenich140f3df2015-06-26 16:58:36 -06007160 if (symbol->getQualifier().hasBinding())
7161 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07007162 if (symbol->getQualifier().hasAttachment())
7163 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06007164 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07007165 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06007166 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06007167 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07007168 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06007169 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07007170 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
7171 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
7172 builder.addDecoration(id, spv::DecorationXfbStride, stride);
7173 }
7174 if (symbol->getQualifier().hasXfbOffset())
7175 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06007176 }
7177
Rex Xu1da878f2016-02-21 20:59:01 +08007178 if (symbol->getType().isImage()) {
7179 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05007180 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08007181 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07007182 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08007183 }
7184
John Kessenich140f3df2015-06-26 16:58:36 -06007185 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06007186 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06007187 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07007188 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06007189
John Kessenich5611c6d2018-04-05 11:25:02 -06007190 // nonuniform
7191 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
7192
John Kessenichecba76f2017-01-06 00:34:48 -07007193#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08007194 if (builtIn == spv::BuiltInSampleMask) {
7195 spv::Decoration decoration;
7196 // GL_NV_sample_mask_override_coverage extension
7197 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08007198 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08007199 else
7200 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07007201 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08007202 if (decoration != spv::DecorationMax) {
7203 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
7204 }
7205 }
chaoc771d89f2017-01-13 01:10:53 -08007206 else if (builtIn == spv::BuiltInLayer) {
7207 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06007208 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007209 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08007210 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
7211 builder.addExtension(spv::E_SPV_NV_viewport_array2);
7212 }
John Kessenichb41bff62017-08-11 13:07:17 -06007213 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007214 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
7215 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08007216 builder.addCapability(spv::CapabilityShaderStereoViewNV);
7217 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
7218 }
7219 }
7220
chaoc6e5acae2016-12-20 13:28:52 -08007221 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07007222 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08007223 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08007224 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
7225 }
Chao Chen9eada4b2018-09-19 11:39:56 -07007226 if (symbol->getQualifier().pervertexNV) {
7227 builder.addDecoration(id, spv::DecorationPerVertexNV);
7228 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
7229 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
7230 }
chaoc0ad6a4e2016-12-19 16:29:34 -08007231#endif
7232
John Kessenich5d610ee2018-03-07 18:05:55 -07007233 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
7234 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
7235 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
7236 symbol->getType().getQualifier().semanticName);
7237 }
7238
John Kessenich140f3df2015-06-26 16:58:36 -06007239 return id;
7240}
7241
Chao Chen3c366992018-09-19 11:41:59 -07007242#ifdef NV_EXTENSIONS
7243// add per-primitive, per-view. per-task decorations to a struct member (member >= 0) or an object
7244void TGlslangToSpvTraverser::addMeshNVDecoration(spv::Id id, int member, const glslang::TQualifier& qualifier)
7245{
7246 if (member >= 0) {
Sahil Parmar38772c02018-10-25 23:50:59 -07007247 if (qualifier.perPrimitiveNV) {
7248 // Need to add capability/extension for fragment shader.
7249 // Mesh shader already adds this by default.
7250 if (glslangIntermediate->getStage() == EShLangFragment) {
7251 builder.addCapability(spv::CapabilityMeshShadingNV);
7252 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7253 }
Chao Chen3c366992018-09-19 11:41:59 -07007254 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007255 }
Chao Chen3c366992018-09-19 11:41:59 -07007256 if (qualifier.perViewNV)
7257 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerViewNV);
7258 if (qualifier.perTaskNV)
7259 builder.addMemberDecoration(id, (unsigned)member, spv::DecorationPerTaskNV);
7260 } else {
Sahil Parmar38772c02018-10-25 23:50:59 -07007261 if (qualifier.perPrimitiveNV) {
7262 // Need to add capability/extension for fragment shader.
7263 // Mesh shader already adds this by default.
7264 if (glslangIntermediate->getStage() == EShLangFragment) {
7265 builder.addCapability(spv::CapabilityMeshShadingNV);
7266 builder.addExtension(spv::E_SPV_NV_mesh_shader);
7267 }
Chao Chen3c366992018-09-19 11:41:59 -07007268 builder.addDecoration(id, spv::DecorationPerPrimitiveNV);
Sahil Parmar38772c02018-10-25 23:50:59 -07007269 }
Chao Chen3c366992018-09-19 11:41:59 -07007270 if (qualifier.perViewNV)
7271 builder.addDecoration(id, spv::DecorationPerViewNV);
7272 if (qualifier.perTaskNV)
7273 builder.addDecoration(id, spv::DecorationPerTaskNV);
7274 }
7275}
7276#endif
7277
John Kessenich55e7d112015-11-15 21:33:39 -07007278// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07007279// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07007280//
7281// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
7282//
7283// Recursively walk the nodes. The nodes form a tree whose leaves are
7284// regular constants, which themselves are trees that createSpvConstant()
7285// recursively walks. So, this function walks the "top" of the tree:
7286// - emit specialization constant-building instructions for specConstant
7287// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04007288spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07007289{
John Kessenich7cc0e282016-03-20 00:46:02 -06007290 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07007291
qining4f4bb812016-04-03 23:55:17 -04007292 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07007293 if (! node.getQualifier().specConstant) {
7294 // hand off to the non-spec-constant path
7295 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
7296 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04007297 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07007298 nextConst, false);
7299 }
7300
7301 // We now know we have a specialization constant to build
7302
John Kessenichd94c0032016-05-30 19:29:40 -06007303 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04007304 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
7305 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
7306 std::vector<spv::Id> dimConstId;
7307 for (int dim = 0; dim < 3; ++dim) {
7308 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
7309 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07007310 if (specConst) {
7311 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
7312 glslangIntermediate->getLocalSizeSpecId(dim));
7313 }
qining4f4bb812016-04-03 23:55:17 -04007314 }
7315 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
7316 }
7317
7318 // An AST node labelled as specialization constant should be a symbol node.
7319 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
7320 if (auto* sn = node.getAsSymbolNode()) {
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007321 spv::Id result;
qining4f4bb812016-04-03 23:55:17 -04007322 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04007323 // Traverse the constant constructor sub tree like generating normal run-time instructions.
7324 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
7325 // will set the builder into spec constant op instruction generating mode.
7326 sub_tree->traverse(this);
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007327 result = accessChainLoad(sub_tree->getType());
7328 } else if (auto* const_union_array = &sn->getConstArray()) {
qining4f4bb812016-04-03 23:55:17 -04007329 int nextConst = 0;
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007330 result = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
Dan Sinclair70661b92018-11-12 13:56:52 -05007331 } else {
7332 logger->missingFunctionality("Invalid initializer for spec onstant.");
Dan Sinclair70661b92018-11-12 13:56:52 -05007333 return spv::NoResult;
John Kessenich6c292d32016-02-15 20:58:50 -07007334 }
Grigory Dzhavadyan4c9876b2018-10-29 22:56:44 -07007335 builder.addName(result, sn->getName().c_str());
7336 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07007337 }
qining4f4bb812016-04-03 23:55:17 -04007338
7339 // Neither a front-end constant node, nor a specialization constant node with constant union array or
7340 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04007341 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04007342 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07007343}
7344
John Kessenich140f3df2015-06-26 16:58:36 -06007345// Use 'consts' as the flattened glslang source of scalar constants to recursively
7346// build the aggregate SPIR-V constant.
7347//
7348// If there are not enough elements present in 'consts', 0 will be substituted;
7349// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
7350//
qining08408382016-03-21 09:51:37 -04007351spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06007352{
7353 // vector of constants for SPIR-V
7354 std::vector<spv::Id> spvConsts;
7355
7356 // Type is used for struct and array constants
7357 spv::Id typeId = convertGlslangToSpvType(glslangType);
7358
7359 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007360 glslang::TType elementType(glslangType, 0);
7361 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04007362 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007363 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06007364 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06007365 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04007366 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06007367 } else if (glslangType.getStruct()) {
7368 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
7369 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04007370 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06007371 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06007372 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
7373 bool zero = nextConst >= consts.size();
7374 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007375 case glslang::EbtInt8:
7376 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
7377 break;
7378 case glslang::EbtUint8:
7379 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7380 break;
7381 case glslang::EbtInt16:
7382 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7383 break;
7384 case glslang::EbtUint16:
7385 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7386 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007387 case glslang::EbtInt:
7388 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7389 break;
7390 case glslang::EbtUint:
7391 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7392 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007393 case glslang::EbtInt64:
7394 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7395 break;
7396 case glslang::EbtUint64:
7397 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7398 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007399 case glslang::EbtFloat:
7400 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7401 break;
7402 case glslang::EbtDouble:
7403 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7404 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007405 case glslang::EbtFloat16:
7406 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7407 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007408 case glslang::EbtBool:
7409 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7410 break;
7411 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007412 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007413 break;
7414 }
7415 ++nextConst;
7416 }
7417 } else {
7418 // we have a non-aggregate (scalar) constant
7419 bool zero = nextConst >= consts.size();
7420 spv::Id scalar = 0;
7421 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007422 case glslang::EbtInt8:
7423 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7424 break;
7425 case glslang::EbtUint8:
7426 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7427 break;
7428 case glslang::EbtInt16:
7429 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7430 break;
7431 case glslang::EbtUint16:
7432 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7433 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007434 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007435 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007436 break;
7437 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007438 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007439 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007440 case glslang::EbtInt64:
7441 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7442 break;
7443 case glslang::EbtUint64:
7444 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7445 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007446 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007447 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007448 break;
7449 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007450 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007451 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007452 case glslang::EbtFloat16:
7453 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7454 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007455 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007456 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007457 break;
7458 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007459 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007460 break;
7461 }
7462 ++nextConst;
7463 return scalar;
7464 }
7465
7466 return builder.makeCompositeConstant(typeId, spvConsts);
7467}
7468
John Kessenich7c1aa102015-10-15 13:29:11 -06007469// Return true if the node is a constant or symbol whose reading has no
7470// non-trivial observable cost or effect.
7471bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7472{
7473 // don't know what this is
7474 if (node == nullptr)
7475 return false;
7476
7477 // a constant is safe
7478 if (node->getAsConstantUnion() != nullptr)
7479 return true;
7480
7481 // not a symbol means non-trivial
7482 if (node->getAsSymbolNode() == nullptr)
7483 return false;
7484
7485 // a symbol, depends on what's being read
7486 switch (node->getType().getQualifier().storage) {
7487 case glslang::EvqTemporary:
7488 case glslang::EvqGlobal:
7489 case glslang::EvqIn:
7490 case glslang::EvqInOut:
7491 case glslang::EvqConst:
7492 case glslang::EvqConstReadOnly:
7493 case glslang::EvqUniform:
7494 return true;
7495 default:
7496 return false;
7497 }
qining25262b32016-05-06 17:25:16 -04007498}
John Kessenich7c1aa102015-10-15 13:29:11 -06007499
7500// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007501// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007502// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007503// Return true if trivial.
7504bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7505{
7506 if (node == nullptr)
7507 return false;
7508
John Kessenich84cc15f2017-05-24 16:44:47 -06007509 // count non scalars as trivial, as well as anything coming from HLSL
7510 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007511 return true;
7512
John Kessenich7c1aa102015-10-15 13:29:11 -06007513 // symbols and constants are trivial
7514 if (isTrivialLeaf(node))
7515 return true;
7516
7517 // otherwise, it needs to be a simple operation or one or two leaf nodes
7518
7519 // not a simple operation
7520 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7521 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7522 if (binaryNode == nullptr && unaryNode == nullptr)
7523 return false;
7524
7525 // not on leaf nodes
7526 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7527 return false;
7528
7529 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7530 return false;
7531 }
7532
7533 switch (node->getAsOperator()->getOp()) {
7534 case glslang::EOpLogicalNot:
7535 case glslang::EOpConvIntToBool:
7536 case glslang::EOpConvUintToBool:
7537 case glslang::EOpConvFloatToBool:
7538 case glslang::EOpConvDoubleToBool:
7539 case glslang::EOpEqual:
7540 case glslang::EOpNotEqual:
7541 case glslang::EOpLessThan:
7542 case glslang::EOpGreaterThan:
7543 case glslang::EOpLessThanEqual:
7544 case glslang::EOpGreaterThanEqual:
7545 case glslang::EOpIndexDirect:
7546 case glslang::EOpIndexDirectStruct:
7547 case glslang::EOpLogicalXor:
7548 case glslang::EOpAny:
7549 case glslang::EOpAll:
7550 return true;
7551 default:
7552 return false;
7553 }
7554}
7555
7556// Emit short-circuiting code, where 'right' is never evaluated unless
7557// the left side is true (for &&) or false (for ||).
7558spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7559{
7560 spv::Id boolTypeId = builder.makeBoolType();
7561
7562 // emit left operand
7563 builder.clearAccessChain();
7564 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007565 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007566
7567 // Operands to accumulate OpPhi operands
7568 std::vector<spv::Id> phiOperands;
7569 // accumulate left operand's phi information
7570 phiOperands.push_back(leftId);
7571 phiOperands.push_back(builder.getBuildPoint()->getId());
7572
7573 // Make the two kinds of operation symmetric with a "!"
7574 // || => emit "if (! left) result = right"
7575 // && => emit "if ( left) result = right"
7576 //
7577 // TODO: this runtime "not" for || could be avoided by adding functionality
7578 // to 'builder' to have an "else" without an "then"
7579 if (op == glslang::EOpLogicalOr)
7580 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7581
7582 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007583 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007584
7585 // emit right operand as the "then" part of the "if"
7586 builder.clearAccessChain();
7587 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007588 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007589
7590 // accumulate left operand's phi information
7591 phiOperands.push_back(rightId);
7592 phiOperands.push_back(builder.getBuildPoint()->getId());
7593
7594 // finish the "if"
7595 ifBuilder.makeEndIf();
7596
7597 // phi together the two results
7598 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7599}
7600
Frank Henigman541f7bb2018-01-16 00:18:26 -05007601#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007602// Return type Id of the imported set of extended instructions corresponds to the name.
7603// Import this set if it has not been imported yet.
7604spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7605{
7606 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7607 return extBuiltinMap[name];
7608 else {
Rex Xu51596642016-09-21 18:56:12 +08007609 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007610 spv::Id extBuiltins = builder.import(name);
7611 extBuiltinMap[name] = extBuiltins;
7612 return extBuiltins;
7613 }
7614}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007615#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007616
John Kessenich140f3df2015-06-26 16:58:36 -06007617}; // end anonymous namespace
7618
7619namespace glslang {
7620
John Kessenich68d78fd2015-07-12 19:28:10 -06007621void GetSpirvVersion(std::string& version)
7622{
John Kessenich9e55f632015-07-15 10:03:39 -06007623 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007624 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007625 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007626 version = buf;
7627}
7628
John Kessenicha372a3e2017-11-02 22:32:14 -06007629// For low-order part of the generator's magic number. Bump up
7630// when there is a change in the style (e.g., if SSA form changes,
7631// or a different instruction sequence to do something gets used).
7632int GetSpirvGeneratorVersion()
7633{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007634 // return 1; // start
7635 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007636 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007637 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007638 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007639 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7640 // versions 4 and 6 each generate OpArrayLength as it has long been done
7641 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007642}
7643
John Kessenich140f3df2015-06-26 16:58:36 -06007644// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007645void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007646{
7647 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007648 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007649 if (out.fail())
7650 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007651 for (int i = 0; i < (int)spirv.size(); ++i) {
7652 unsigned int word = spirv[i];
7653 out.write((const char*)&word, 4);
7654 }
7655 out.close();
7656}
7657
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007658// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007659void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007660{
7661 std::ofstream out;
7662 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007663 if (out.fail())
7664 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007665 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007666 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007667 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007668 if (varName != nullptr) {
7669 out << "\t #pragma once" << std::endl;
7670 out << "const uint32_t " << varName << "[] = {" << std::endl;
7671 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007672 const int WORDS_PER_LINE = 8;
7673 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7674 out << "\t";
7675 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7676 const unsigned int word = spirv[i + j];
7677 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7678 if (i + j + 1 < (int)spirv.size()) {
7679 out << ",";
7680 }
7681 }
7682 out << std::endl;
7683 }
Flavio15017db2017-02-15 14:29:33 -08007684 if (varName != nullptr) {
7685 out << "};";
7686 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007687 out.close();
7688}
7689
John Kessenich140f3df2015-06-26 16:58:36 -06007690//
7691// Set up the glslang traversal
7692//
John Kessenich4e11b612018-08-30 16:56:59 -06007693void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007694{
Lei Zhang17535f72016-05-04 15:55:59 -04007695 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007696 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007697}
7698
John Kessenich4e11b612018-08-30 16:56:59 -06007699void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007700 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007701{
John Kessenich140f3df2015-06-26 16:58:36 -06007702 TIntermNode* root = intermediate.getTreeRoot();
7703
7704 if (root == 0)
7705 return;
7706
John Kessenich4e11b612018-08-30 16:56:59 -06007707 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007708 if (options == nullptr)
7709 options = &defaultOptions;
7710
John Kessenich4e11b612018-08-30 16:56:59 -06007711 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007712
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007713 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007714 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007715 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007716 it.dumpSpv(spirv);
7717
GregFfb03a552018-03-29 11:49:14 -06007718#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007719 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7720 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007721 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007722 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007723
John Kessenich4e11b612018-08-30 16:56:59 -06007724 if (options->validate)
7725 SpirvToolsValidate(intermediate, spirv, logger);
7726
John Kessenich717c80a2018-08-23 15:17:10 -06007727 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007728 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007729
GregFcd1f1692017-09-21 18:40:22 -06007730#endif
7731
John Kessenich4e11b612018-08-30 16:56:59 -06007732 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06007733}
7734
7735}; // end namespace glslang