blob: 4911920da05236ba94667867beb106a5fec234d2 [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);
qining08408382016-03-21 09:51:37 -0400197 spv::Id createSpvConstant(const glslang::TIntermTyped&);
198 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600199 bool isTrivialLeaf(const glslang::TIntermTyped* node);
200 bool isTrivial(const glslang::TIntermTyped* node);
201 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500202#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800203 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500204#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700205 void addPre13Extension(const char* ext)
206 {
207 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
208 builder.addExtension(ext);
209 }
John Kessenich140f3df2015-06-26 16:58:36 -0600210
John Kessenich121853f2017-05-31 17:11:16 -0600211 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600212 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600213 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700214 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600215 int sequenceDepth;
216
Lei Zhang17535f72016-05-04 15:55:59 -0400217 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400218
John Kessenich140f3df2015-06-26 16:58:36 -0600219 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
220 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700221 bool inEntryPoint;
222 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700223 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 -0700224 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600225 const glslang::TIntermediate* glslangIntermediate;
226 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800227 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600228
John Kessenich2f273362015-07-18 22:34:27 -0600229 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600230 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600231 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700232 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700233 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
234 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600235 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700236 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
John Kessenich140f3df2015-06-26 16:58:36 -0600237};
238
239//
240// Helper functions for translating glslang representations to SPIR-V enumerants.
241//
242
243// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700244spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600245{
John Kessenich66e2faf2016-03-12 18:34:36 -0700246 switch (source) {
247 case glslang::EShSourceGlsl:
248 switch (profile) {
249 case ENoProfile:
250 case ECoreProfile:
251 case ECompatibilityProfile:
252 return spv::SourceLanguageGLSL;
253 case EEsProfile:
254 return spv::SourceLanguageESSL;
255 default:
256 return spv::SourceLanguageUnknown;
257 }
258 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600259 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600260 default:
261 return spv::SourceLanguageUnknown;
262 }
263}
264
265// Translate glslang language (stage) to SPIR-V execution model.
266spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
267{
268 switch (stage) {
269 case EShLangVertex: return spv::ExecutionModelVertex;
270 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
271 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
272 case EShLangGeometry: return spv::ExecutionModelGeometry;
273 case EShLangFragment: return spv::ExecutionModelFragment;
274 case EShLangCompute: return spv::ExecutionModelGLCompute;
275 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700276 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600277 return spv::ExecutionModelFragment;
278 }
279}
280
John Kessenich140f3df2015-06-26 16:58:36 -0600281// Translate glslang sampler type to SPIR-V dimensionality.
282spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
283{
284 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700285 case glslang::Esd1D: return spv::Dim1D;
286 case glslang::Esd2D: return spv::Dim2D;
287 case glslang::Esd3D: return spv::Dim3D;
288 case glslang::EsdCube: return spv::DimCube;
289 case glslang::EsdRect: return spv::DimRect;
290 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700291 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600292 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700293 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600294 return spv::Dim2D;
295 }
296}
297
John Kessenichf6640762016-08-01 19:44:00 -0600298// Translate glslang precision to SPIR-V precision decorations.
299spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600300{
John Kessenichf6640762016-08-01 19:44:00 -0600301 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700302 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600303 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600304 default:
305 return spv::NoPrecision;
306 }
307}
308
John Kessenichf6640762016-08-01 19:44:00 -0600309// Translate glslang type to SPIR-V precision decorations.
310spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
311{
312 return TranslatePrecisionDecoration(type.getQualifier().precision);
313}
314
John Kessenich140f3df2015-06-26 16:58:36 -0600315// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600316spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600317{
318 if (type.getBasicType() == glslang::EbtBlock) {
319 switch (type.getQualifier().storage) {
320 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600321 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600322 case glslang::EvqVaryingIn: return spv::DecorationBlock;
323 case glslang::EvqVaryingOut: return spv::DecorationBlock;
324 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700325 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600326 break;
327 }
328 }
329
John Kessenich4016e382016-07-15 11:53:56 -0600330 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600331}
332
Rex Xu1da878f2016-02-21 20:59:01 +0800333// Translate glslang type to SPIR-V memory decorations.
Jeff Bolz36831c92018-09-05 10:11:41 -0500334void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory, bool useVulkanMemoryModel)
Rex Xu1da878f2016-02-21 20:59:01 +0800335{
Jeff Bolz36831c92018-09-05 10:11:41 -0500336 if (!useVulkanMemoryModel) {
337 if (qualifier.coherent)
338 memory.push_back(spv::DecorationCoherent);
339 if (qualifier.volatil) {
340 memory.push_back(spv::DecorationVolatile);
341 memory.push_back(spv::DecorationCoherent);
342 }
John Kessenich14b85d32018-06-04 15:36:03 -0600343 }
Rex Xu1da878f2016-02-21 20:59:01 +0800344 if (qualifier.restrict)
345 memory.push_back(spv::DecorationRestrict);
346 if (qualifier.readonly)
347 memory.push_back(spv::DecorationNonWritable);
348 if (qualifier.writeonly)
349 memory.push_back(spv::DecorationNonReadable);
350}
351
John Kessenich140f3df2015-06-26 16:58:36 -0600352// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700353spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600354{
355 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700356 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600357 case glslang::ElmRowMajor:
358 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700359 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600360 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700361 default:
362 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600363 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600364 }
365 } else {
366 switch (type.getBasicType()) {
367 default:
John Kessenich4016e382016-07-15 11:53:56 -0600368 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600369 break;
370 case glslang::EbtBlock:
371 switch (type.getQualifier().storage) {
372 case glslang::EvqUniform:
373 case glslang::EvqBuffer:
374 switch (type.getQualifier().layoutPacking) {
375 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600376 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
377 default:
John Kessenich4016e382016-07-15 11:53:56 -0600378 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600379 }
380 case glslang::EvqVaryingIn:
381 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700382 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600383 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600384 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700385 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600386 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600387 }
388 }
389 }
390}
391
392// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600393// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700394// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800395spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600396{
Rex Xubbceed72016-05-21 09:40:44 +0800397 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700398 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600399 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800400 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700401 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700402 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600403 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800404#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800405 else if (qualifier.explicitInterp) {
406 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800407 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800408 }
Rex Xu9d93a232016-05-05 12:30:44 +0800409#endif
Rex Xubbceed72016-05-21 09:40:44 +0800410 else
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800412}
413
414// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600415// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800416// should be applied.
417spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
418{
419 if (qualifier.patch)
420 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700421 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600422 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700423 else if (qualifier.sample) {
424 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600425 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700426 } else
John Kessenich4016e382016-07-15 11:53:56 -0600427 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600428}
429
John Kessenich92187592016-02-01 13:45:25 -0700430// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700431spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600432{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700433 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600434 return spv::DecorationInvariant;
435 else
John Kessenich4016e382016-07-15 11:53:56 -0600436 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600437}
438
qining9220dbb2016-05-04 17:34:38 -0400439// If glslang type is noContraction, return SPIR-V NoContraction decoration.
440spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
441{
442 if (qualifier.noContraction)
443 return spv::DecorationNoContraction;
444 else
John Kessenich4016e382016-07-15 11:53:56 -0600445 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400446}
447
John Kessenich5611c6d2018-04-05 11:25:02 -0600448// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
449spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
450{
451 if (qualifier.isNonUniform()) {
452 builder.addExtension("SPV_EXT_descriptor_indexing");
453 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
454 return spv::DecorationNonUniformEXT;
455 } else
456 return spv::DecorationMax;
457}
458
Jeff Bolz36831c92018-09-05 10:11:41 -0500459spv::MemoryAccessMask TGlslangToSpvTraverser::TranslateMemoryAccess(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
460{
461 if (!glslangIntermediate->usingVulkanMemoryModel() || coherentFlags.isImage) {
462 return spv::MemoryAccessMaskNone;
463 }
464 spv::MemoryAccessMask mask = spv::MemoryAccessMaskNone;
465 if (coherentFlags.volatil ||
466 coherentFlags.coherent ||
467 coherentFlags.devicecoherent ||
468 coherentFlags.queuefamilycoherent ||
469 coherentFlags.workgroupcoherent ||
470 coherentFlags.subgroupcoherent) {
471 mask = mask | spv::MemoryAccessMakePointerAvailableKHRMask |
472 spv::MemoryAccessMakePointerVisibleKHRMask;
473 }
474 if (coherentFlags.nonprivate) {
475 mask = mask | spv::MemoryAccessNonPrivatePointerKHRMask;
476 }
477 if (coherentFlags.volatil) {
478 mask = mask | spv::MemoryAccessVolatileMask;
479 }
480 if (mask != spv::MemoryAccessMaskNone) {
481 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
482 }
483 return mask;
484}
485
486spv::ImageOperandsMask TGlslangToSpvTraverser::TranslateImageOperands(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
487{
488 if (!glslangIntermediate->usingVulkanMemoryModel()) {
489 return spv::ImageOperandsMaskNone;
490 }
491 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
492 if (coherentFlags.volatil ||
493 coherentFlags.coherent ||
494 coherentFlags.devicecoherent ||
495 coherentFlags.queuefamilycoherent ||
496 coherentFlags.workgroupcoherent ||
497 coherentFlags.subgroupcoherent) {
498 mask = mask | spv::ImageOperandsMakeTexelAvailableKHRMask |
499 spv::ImageOperandsMakeTexelVisibleKHRMask;
500 }
501 if (coherentFlags.nonprivate) {
502 mask = mask | spv::ImageOperandsNonPrivateTexelKHRMask;
503 }
504 if (coherentFlags.volatil) {
505 mask = mask | spv::ImageOperandsVolatileTexelKHRMask;
506 }
507 if (mask != spv::ImageOperandsMaskNone) {
508 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
509 }
510 return mask;
511}
512
513spv::Builder::AccessChain::CoherentFlags TGlslangToSpvTraverser::TranslateCoherent(const glslang::TType& type)
514{
515 spv::Builder::AccessChain::CoherentFlags flags;
516 flags.coherent = type.getQualifier().coherent;
517 flags.devicecoherent = type.getQualifier().devicecoherent;
518 flags.queuefamilycoherent = type.getQualifier().queuefamilycoherent;
519 // shared variables are implicitly workgroupcoherent in GLSL.
520 flags.workgroupcoherent = type.getQualifier().workgroupcoherent ||
521 type.getQualifier().storage == glslang::EvqShared;
522 flags.subgroupcoherent = type.getQualifier().subgroupcoherent;
523 // *coherent variables are implicitly nonprivate in GLSL
524 flags.nonprivate = type.getQualifier().nonprivate ||
525 type.getQualifier().subgroupcoherent ||
526 type.getQualifier().workgroupcoherent ||
527 type.getQualifier().queuefamilycoherent ||
528 type.getQualifier().devicecoherent ||
529 type.getQualifier().coherent;
530 flags.volatil = type.getQualifier().volatil;
531 flags.isImage = type.getBasicType() == glslang::EbtSampler;
532 return flags;
533}
534
535spv::Scope TGlslangToSpvTraverser::TranslateMemoryScope(const spv::Builder::AccessChain::CoherentFlags &coherentFlags)
536{
537 spv::Scope scope;
538 if (coherentFlags.coherent) {
539 // coherent defaults to Device scope in the old model, QueueFamilyKHR scope in the new model
540 scope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
541 } else if (coherentFlags.devicecoherent) {
542 scope = spv::ScopeDevice;
543 } else if (coherentFlags.queuefamilycoherent) {
544 scope = spv::ScopeQueueFamilyKHR;
545 } else if (coherentFlags.workgroupcoherent) {
546 scope = spv::ScopeWorkgroup;
547 } else if (coherentFlags.subgroupcoherent) {
548 scope = spv::ScopeSubgroup;
549 } else {
550 scope = spv::ScopeMax;
551 }
552 if (glslangIntermediate->usingVulkanMemoryModel() && scope == spv::ScopeDevice) {
553 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
554 }
555 return scope;
556}
557
David Netoa901ffe2016-06-08 14:11:40 +0100558// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
559// associated capabilities when required. For some built-in variables, a capability
560// is generated only when using the variable in an executable instruction, but not when
561// just declaring a struct member variable with it. This is true for PointSize,
562// ClipDistance, and CullDistance.
563spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600564{
565 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700566 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600567 // Defer adding the capability until the built-in is actually used.
568 if (! memberDeclaration) {
569 switch (glslangIntermediate->getStage()) {
570 case EShLangGeometry:
571 builder.addCapability(spv::CapabilityGeometryPointSize);
572 break;
573 case EShLangTessControl:
574 case EShLangTessEvaluation:
575 builder.addCapability(spv::CapabilityTessellationPointSize);
576 break;
577 default:
578 break;
579 }
John Kessenich92187592016-02-01 13:45:25 -0700580 }
581 return spv::BuiltInPointSize;
582
John Kessenichebb50532016-05-16 19:22:05 -0600583 // These *Distance capabilities logically belong here, but if the member is declared and
584 // then never used, consumers of SPIR-V prefer the capability not be declared.
585 // They are now generated when used, rather than here when declared.
586 // Potentially, the specification should be more clear what the minimum
587 // use needed is to trigger the capability.
588 //
John Kessenich92187592016-02-01 13:45:25 -0700589 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100590 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800591 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700592 return spv::BuiltInClipDistance;
593
594 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100595 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800596 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700597 return spv::BuiltInCullDistance;
598
599 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600600 builder.addCapability(spv::CapabilityMultiViewport);
601 if (glslangIntermediate->getStage() == EShLangVertex ||
602 glslangIntermediate->getStage() == EShLangTessControl ||
603 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800604
John Kessenichba6a3c22017-09-13 13:22:50 -0600605 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
606 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800607 }
John Kessenich92187592016-02-01 13:45:25 -0700608 return spv::BuiltInViewportIndex;
609
John Kessenich5e801132016-02-15 11:09:46 -0700610 case glslang::EbvSampleId:
611 builder.addCapability(spv::CapabilitySampleRateShading);
612 return spv::BuiltInSampleId;
613
614 case glslang::EbvSamplePosition:
615 builder.addCapability(spv::CapabilitySampleRateShading);
616 return spv::BuiltInSamplePosition;
617
618 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700619 return spv::BuiltInSampleMask;
620
John Kessenich78a45572016-07-08 14:05:15 -0600621 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600622 builder.addCapability(spv::CapabilityGeometry);
623 if (glslangIntermediate->getStage() == EShLangVertex ||
624 glslangIntermediate->getStage() == EShLangTessControl ||
625 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800626
John Kessenichba6a3c22017-09-13 13:22:50 -0600627 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
628 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800629 }
John Kessenich78a45572016-07-08 14:05:15 -0600630 return spv::BuiltInLayer;
631
John Kessenich140f3df2015-06-26 16:58:36 -0600632 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600633 case glslang::EbvVertexId: return spv::BuiltInVertexId;
634 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700635 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
636 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800637
John Kessenichda581a22015-10-14 14:10:30 -0600638 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700639 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800640 builder.addCapability(spv::CapabilityDrawParameters);
641 return spv::BuiltInBaseVertex;
642
John Kessenichda581a22015-10-14 14:10:30 -0600643 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700644 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800645 builder.addCapability(spv::CapabilityDrawParameters);
646 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200647
John Kessenichda581a22015-10-14 14:10:30 -0600648 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700649 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800650 builder.addCapability(spv::CapabilityDrawParameters);
651 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200652
653 case glslang::EbvPrimitiveId:
654 if (glslangIntermediate->getStage() == EShLangFragment)
655 builder.addCapability(spv::CapabilityGeometry);
656 return spv::BuiltInPrimitiveId;
657
Rex Xu37cdcee2017-06-29 17:46:34 +0800658 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800659 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
660 builder.addCapability(spv::CapabilityStencilExportEXT);
661 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800662
John Kessenich140f3df2015-06-26 16:58:36 -0600663 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600664 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
665 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
666 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
667 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
668 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
669 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
670 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600671 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
672 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
673 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
674 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
675 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
676 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
677 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
678 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800679
Rex Xu574ab042016-04-14 16:53:07 +0800680 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800681 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800682 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
683 return spv::BuiltInSubgroupSize;
684
Rex Xu574ab042016-04-14 16:53:07 +0800685 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800686 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800687 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
688 return spv::BuiltInSubgroupLocalInvocationId;
689
Rex Xu574ab042016-04-14 16:53:07 +0800690 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800691 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
692 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
693 return spv::BuiltInSubgroupEqMaskKHR;
694
Rex Xu574ab042016-04-14 16:53:07 +0800695 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800696 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
697 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
698 return spv::BuiltInSubgroupGeMaskKHR;
699
Rex Xu574ab042016-04-14 16:53:07 +0800700 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800701 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
702 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
703 return spv::BuiltInSubgroupGtMaskKHR;
704
Rex Xu574ab042016-04-14 16:53:07 +0800705 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800706 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
707 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
708 return spv::BuiltInSubgroupLeMaskKHR;
709
Rex Xu574ab042016-04-14 16:53:07 +0800710 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800711 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
712 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
713 return spv::BuiltInSubgroupLtMaskKHR;
714
John Kessenich66011cb2018-03-06 16:12:04 -0700715 case glslang::EbvNumSubgroups:
716 builder.addCapability(spv::CapabilityGroupNonUniform);
717 return spv::BuiltInNumSubgroups;
718
719 case glslang::EbvSubgroupID:
720 builder.addCapability(spv::CapabilityGroupNonUniform);
721 return spv::BuiltInSubgroupId;
722
723 case glslang::EbvSubgroupSize2:
724 builder.addCapability(spv::CapabilityGroupNonUniform);
725 return spv::BuiltInSubgroupSize;
726
727 case glslang::EbvSubgroupInvocation2:
728 builder.addCapability(spv::CapabilityGroupNonUniform);
729 return spv::BuiltInSubgroupLocalInvocationId;
730
731 case glslang::EbvSubgroupEqMask2:
732 builder.addCapability(spv::CapabilityGroupNonUniform);
733 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
734 return spv::BuiltInSubgroupEqMask;
735
736 case glslang::EbvSubgroupGeMask2:
737 builder.addCapability(spv::CapabilityGroupNonUniform);
738 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
739 return spv::BuiltInSubgroupGeMask;
740
741 case glslang::EbvSubgroupGtMask2:
742 builder.addCapability(spv::CapabilityGroupNonUniform);
743 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
744 return spv::BuiltInSubgroupGtMask;
745
746 case glslang::EbvSubgroupLeMask2:
747 builder.addCapability(spv::CapabilityGroupNonUniform);
748 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
749 return spv::BuiltInSubgroupLeMask;
750
751 case glslang::EbvSubgroupLtMask2:
752 builder.addCapability(spv::CapabilityGroupNonUniform);
753 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
754 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800755#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800756 case glslang::EbvBaryCoordNoPersp:
757 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
758 return spv::BuiltInBaryCoordNoPerspAMD;
759
760 case glslang::EbvBaryCoordNoPerspCentroid:
761 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
762 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
763
764 case glslang::EbvBaryCoordNoPerspSample:
765 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
766 return spv::BuiltInBaryCoordNoPerspSampleAMD;
767
768 case glslang::EbvBaryCoordSmooth:
769 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
770 return spv::BuiltInBaryCoordSmoothAMD;
771
772 case glslang::EbvBaryCoordSmoothCentroid:
773 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
774 return spv::BuiltInBaryCoordSmoothCentroidAMD;
775
776 case glslang::EbvBaryCoordSmoothSample:
777 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
778 return spv::BuiltInBaryCoordSmoothSampleAMD;
779
780 case glslang::EbvBaryCoordPullModel:
781 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
782 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800783#endif
chaoc771d89f2017-01-13 01:10:53 -0800784
John Kessenich6c8aaac2017-02-27 01:20:51 -0700785 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700786 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700787 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700788 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700789
790 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700791 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700792 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700793 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700794
chaoc771d89f2017-01-13 01:10:53 -0800795#ifdef NV_EXTENSIONS
796 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800797 if (!memberDeclaration) {
798 builder.addExtension(spv::E_SPV_NV_viewport_array2);
799 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
800 }
chaoc771d89f2017-01-13 01:10:53 -0800801 return spv::BuiltInViewportMaskNV;
802 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800803 if (!memberDeclaration) {
804 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
805 builder.addCapability(spv::CapabilityShaderStereoViewNV);
806 }
chaoc771d89f2017-01-13 01:10:53 -0800807 return spv::BuiltInSecondaryPositionNV;
808 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800809 if (!memberDeclaration) {
810 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
811 builder.addCapability(spv::CapabilityShaderStereoViewNV);
812 }
chaoc771d89f2017-01-13 01:10:53 -0800813 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800814 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800815 if (!memberDeclaration) {
816 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
817 builder.addCapability(spv::CapabilityPerViewAttributesNV);
818 }
chaocdf3956c2017-02-14 14:52:34 -0800819 return spv::BuiltInPositionPerViewNV;
820 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800821 if (!memberDeclaration) {
822 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
823 builder.addCapability(spv::CapabilityPerViewAttributesNV);
824 }
chaocdf3956c2017-02-14 14:52:34 -0800825 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700826 case glslang::EbvFragFullyCoveredNV:
827 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
828 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
829 return spv::BuiltInFullyCoveredEXT;
Chao Chen9eada4b2018-09-19 11:39:56 -0700830 case glslang::EbvBaryCoordNV:
831 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
832 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
833 return spv::BuiltInBaryCoordNV;
834 case glslang::EbvBaryCoordNoPerspNV:
835 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
836 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
837 return spv::BuiltInBaryCoordNoPerspNV;
chaoc771d89f2017-01-13 01:10:53 -0800838#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800839 default:
840 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600841 }
842}
843
Rex Xufc618912015-09-09 16:42:49 +0800844// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700845spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800846{
847 assert(type.getBasicType() == glslang::EbtSampler);
848
John Kessenich5d0fa972016-02-15 11:57:00 -0700849 // Check for capabilities
850 switch (type.getQualifier().layoutFormat) {
851 case glslang::ElfRg32f:
852 case glslang::ElfRg16f:
853 case glslang::ElfR11fG11fB10f:
854 case glslang::ElfR16f:
855 case glslang::ElfRgba16:
856 case glslang::ElfRgb10A2:
857 case glslang::ElfRg16:
858 case glslang::ElfRg8:
859 case glslang::ElfR16:
860 case glslang::ElfR8:
861 case glslang::ElfRgba16Snorm:
862 case glslang::ElfRg16Snorm:
863 case glslang::ElfRg8Snorm:
864 case glslang::ElfR16Snorm:
865 case glslang::ElfR8Snorm:
866
867 case glslang::ElfRg32i:
868 case glslang::ElfRg16i:
869 case glslang::ElfRg8i:
870 case glslang::ElfR16i:
871 case glslang::ElfR8i:
872
873 case glslang::ElfRgb10a2ui:
874 case glslang::ElfRg32ui:
875 case glslang::ElfRg16ui:
876 case glslang::ElfRg8ui:
877 case glslang::ElfR16ui:
878 case glslang::ElfR8ui:
879 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
880 break;
881
882 default:
883 break;
884 }
885
886 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800887 switch (type.getQualifier().layoutFormat) {
888 case glslang::ElfNone: return spv::ImageFormatUnknown;
889 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
890 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
891 case glslang::ElfR32f: return spv::ImageFormatR32f;
892 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
893 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
894 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
895 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
896 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
897 case glslang::ElfR16f: return spv::ImageFormatR16f;
898 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
899 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
900 case glslang::ElfRg16: return spv::ImageFormatRg16;
901 case glslang::ElfRg8: return spv::ImageFormatRg8;
902 case glslang::ElfR16: return spv::ImageFormatR16;
903 case glslang::ElfR8: return spv::ImageFormatR8;
904 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
905 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
906 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
907 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
908 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
909 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
910 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
911 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
912 case glslang::ElfR32i: return spv::ImageFormatR32i;
913 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
914 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
915 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
916 case glslang::ElfR16i: return spv::ImageFormatR16i;
917 case glslang::ElfR8i: return spv::ImageFormatR8i;
918 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
919 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
920 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
921 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
922 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
923 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
924 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
925 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
926 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
927 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600928 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800929 }
930}
931
John Kesseniche18fd202018-01-30 11:01:39 -0700932spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +0800933{
John Kesseniche18fd202018-01-30 11:01:39 -0700934 if (selectionNode.getFlatten())
935 return spv::SelectionControlFlattenMask;
936 if (selectionNode.getDontFlatten())
937 return spv::SelectionControlDontFlattenMask;
938 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +0800939}
940
John Kesseniche18fd202018-01-30 11:01:39 -0700941spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -0600942{
John Kesseniche18fd202018-01-30 11:01:39 -0700943 if (switchNode.getFlatten())
944 return spv::SelectionControlFlattenMask;
945 if (switchNode.getDontFlatten())
946 return spv::SelectionControlDontFlattenMask;
947 return spv::SelectionControlMaskNone;
948}
949
John Kessenicha2858d92018-01-31 08:11:18 -0700950// return a non-0 dependency if the dependency argument must be set
951spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
952 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -0700953{
954 spv::LoopControlMask control = spv::LoopControlMaskNone;
955
956 if (loopNode.getDontUnroll())
957 control = control | spv::LoopControlDontUnrollMask;
958 if (loopNode.getUnroll())
959 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -0700960 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -0700961 control = control | spv::LoopControlDependencyInfiniteMask;
962 else if (loopNode.getLoopDependency() > 0) {
963 control = control | spv::LoopControlDependencyLengthMask;
964 dependencyLength = loopNode.getLoopDependency();
965 }
John Kesseniche18fd202018-01-30 11:01:39 -0700966
967 return control;
steve-lunargf1709e72017-05-02 20:14:50 -0600968}
969
John Kessenicha5c5fb62017-05-05 05:09:58 -0600970// Translate glslang type to SPIR-V storage class.
971spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
972{
973 if (type.getQualifier().isPipeInput())
974 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600975 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600976 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600977
978 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
979 type.getQualifier().storage == glslang::EvqUniform) {
980 if (type.getBasicType() == glslang::EbtAtomicUint)
981 return spv::StorageClassAtomicCounter;
982 if (type.containsOpaque())
983 return spv::StorageClassUniformConstant;
984 }
985
986 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -0700987 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -0600988 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600989 }
990
991 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600992 if (type.getQualifier().layoutPushConstant)
993 return spv::StorageClassPushConstant;
994 if (type.getBasicType() == glslang::EbtBlock)
995 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600996 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600997 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600998
999 switch (type.getQualifier().storage) {
1000 case glslang::EvqShared: return spv::StorageClassWorkgroup;
1001 case glslang::EvqGlobal: return spv::StorageClassPrivate;
1002 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
1003 case glslang::EvqTemporary: return spv::StorageClassFunction;
1004 default:
1005 assert(0);
1006 break;
1007 }
1008
1009 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001010}
1011
John Kessenich5611c6d2018-04-05 11:25:02 -06001012// Add capabilities pertaining to how an array is indexed.
1013void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1014 const glslang::TType& indexType)
1015{
1016 if (indexType.getQualifier().isNonUniform()) {
1017 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001018 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001019 if (baseType.getBasicType() == glslang::EbtSampler) {
1020 if (baseType.getQualifier().hasAttachment())
1021 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1022 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1023 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1024 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1025 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1026 else if (baseType.isImage())
1027 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1028 else if (baseType.isTexture())
1029 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1030 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1031 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1032 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1033 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1034 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1035 }
1036 } else {
1037 // assume a dynamically uniform index
1038 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001039 if (baseType.getQualifier().hasAttachment()) {
1040 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001041 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001042 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1043 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001044 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001045 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1046 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001047 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001048 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001049 }
1050 }
1051}
1052
qining25262b32016-05-06 17:25:16 -04001053// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001054// descriptor set.
1055bool IsDescriptorResource(const glslang::TType& type)
1056{
John Kessenichf7497e22016-03-08 21:36:22 -07001057 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001058 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -07001059 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001060
1061 // non block...
1062 // basically samplerXXX/subpass/sampler/texture are all included
1063 // if they are the global-scope-class, not the function parameter
1064 // (or local, if they ever exist) class.
1065 if (type.getBasicType() == glslang::EbtSampler)
1066 return type.getQualifier().isUniformOrBuffer();
1067
1068 // None of the above.
1069 return false;
1070}
1071
John Kesseniche0b6cad2015-12-24 10:30:13 -07001072void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1073{
1074 if (child.layoutMatrix == glslang::ElmNone)
1075 child.layoutMatrix = parent.layoutMatrix;
1076
1077 if (parent.invariant)
1078 child.invariant = true;
1079 if (parent.nopersp)
1080 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001081#ifdef AMD_EXTENSIONS
1082 if (parent.explicitInterp)
1083 child.explicitInterp = true;
1084#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001085 if (parent.flat)
1086 child.flat = true;
1087 if (parent.centroid)
1088 child.centroid = true;
1089 if (parent.patch)
1090 child.patch = true;
1091 if (parent.sample)
1092 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001093 if (parent.coherent)
1094 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001095 if (parent.devicecoherent)
1096 child.devicecoherent = true;
1097 if (parent.queuefamilycoherent)
1098 child.queuefamilycoherent = true;
1099 if (parent.workgroupcoherent)
1100 child.workgroupcoherent = true;
1101 if (parent.subgroupcoherent)
1102 child.subgroupcoherent = true;
1103 if (parent.nonprivate)
1104 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001105 if (parent.volatil)
1106 child.volatil = true;
1107 if (parent.restrict)
1108 child.restrict = true;
1109 if (parent.readonly)
1110 child.readonly = true;
1111 if (parent.writeonly)
1112 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001113}
1114
John Kessenichf2b7f332016-09-01 17:05:23 -06001115bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001116{
John Kessenich7b9fa252016-01-21 18:56:57 -07001117 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001118 // - struct members might inherit from a struct declaration
1119 // (note that non-block structs don't explicitly inherit,
1120 // only implicitly, meaning no decoration involved)
1121 // - affect decorations on the struct members
1122 // (note smooth does not, and expecting something like volatile
1123 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001124 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001125 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001126}
1127
John Kessenich140f3df2015-06-26 16:58:36 -06001128//
1129// Implement the TGlslangToSpvTraverser class.
1130//
1131
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001132TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001133 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1134 : TIntermTraverser(true, false, true),
1135 options(options),
1136 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001137 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001138 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001139 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001140 glslangIntermediate(glslangIntermediate)
1141{
1142 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1143
1144 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001145 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1146 glslangIntermediate->getVersion());
1147
John Kessenich121853f2017-05-31 17:11:16 -06001148 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001149 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001150 builder.setSourceFile(glslangIntermediate->getSourceFile());
1151
1152 // Set the source shader's text. If for SPV version 1.0, include
1153 // a preamble in comments stating the OpModuleProcessed instructions.
1154 // Otherwise, emit those as actual instructions.
1155 std::string text;
1156 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1157 for (int p = 0; p < (int)processes.size(); ++p) {
1158 if (glslangIntermediate->getSpv().spv < 0x00010100) {
1159 text.append("// OpModuleProcessed ");
1160 text.append(processes[p]);
1161 text.append("\n");
1162 } else
1163 builder.addModuleProcessed(processes[p]);
1164 }
1165 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
1166 text.append("#line 1\n");
1167 text.append(glslangIntermediate->getSourceText());
1168 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -06001169 }
John Kessenich140f3df2015-06-26 16:58:36 -06001170 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz36831c92018-09-05 10:11:41 -05001171 if (glslangIntermediate->usingVulkanMemoryModel()) {
1172 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelVulkanKHR);
1173 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
1174 } else {
1175 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
1176 }
John Kessenicheee9d532016-09-19 18:09:30 -06001177 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1178 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001179
1180 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001181 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1182 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001183 builder.addSourceExtension(it->c_str());
1184
1185 // Add the top-level modes for this shader.
1186
John Kessenich92187592016-02-01 13:45:25 -07001187 if (glslangIntermediate->getXfbMode()) {
1188 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001189 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001190 }
John Kessenich140f3df2015-06-26 16:58:36 -06001191
1192 unsigned int mode;
1193 switch (glslangIntermediate->getStage()) {
1194 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001195 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001196 break;
1197
steve-lunarge7412492017-03-23 11:56:07 -06001198 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001199 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001200 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001201
steve-lunarge7412492017-03-23 11:56:07 -06001202 glslang::TLayoutGeometry primitive;
1203
1204 if (glslangIntermediate->getStage() == EShLangTessControl) {
1205 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1206 primitive = glslangIntermediate->getOutputPrimitive();
1207 } else {
1208 primitive = glslangIntermediate->getInputPrimitive();
1209 }
1210
1211 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001212 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1213 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1214 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001215 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001216 }
John Kessenich4016e382016-07-15 11:53:56 -06001217 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001218 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1219
John Kesseniche6903322015-10-13 16:29:02 -06001220 switch (glslangIntermediate->getVertexSpacing()) {
1221 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1222 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1223 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001224 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001225 }
John Kessenich4016e382016-07-15 11:53:56 -06001226 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001227 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1228
1229 switch (glslangIntermediate->getVertexOrder()) {
1230 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1231 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001232 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001233 }
John Kessenich4016e382016-07-15 11:53:56 -06001234 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001235 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1236
1237 if (glslangIntermediate->getPointMode())
1238 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001239 break;
1240
1241 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001242 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001243 switch (glslangIntermediate->getInputPrimitive()) {
1244 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1245 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1246 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001247 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001248 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001249 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001250 }
John Kessenich4016e382016-07-15 11:53:56 -06001251 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001252 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001253
John Kessenich140f3df2015-06-26 16:58:36 -06001254 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1255
1256 switch (glslangIntermediate->getOutputPrimitive()) {
1257 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1258 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1259 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001260 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001261 }
John Kessenich4016e382016-07-15 11:53:56 -06001262 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001263 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1264 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1265 break;
1266
1267 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001268 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001269 if (glslangIntermediate->getPixelCenterInteger())
1270 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001271
John Kessenich140f3df2015-06-26 16:58:36 -06001272 if (glslangIntermediate->getOriginUpperLeft())
1273 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001274 else
1275 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001276
1277 if (glslangIntermediate->getEarlyFragmentTests())
1278 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1279
chaocc1204522017-06-30 17:14:30 -07001280 if (glslangIntermediate->getPostDepthCoverage()) {
1281 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1282 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1283 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1284 }
1285
John Kesseniche6903322015-10-13 16:29:02 -06001286 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001287 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1288 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001289 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001290 }
John Kessenich4016e382016-07-15 11:53:56 -06001291 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001292 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1293
1294 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1295 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001296 break;
1297
1298 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001299 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001300 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1301 glslangIntermediate->getLocalSize(1),
1302 glslangIntermediate->getLocalSize(2));
Chao Chenbeae2252018-09-19 11:40:45 -07001303#ifdef NV_EXTENSIONS
1304 if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupQuads) {
1305 builder.addCapability(spv::CapabilityComputeDerivativeGroupQuadsNV);
1306 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupQuadsNV);
1307 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1308 } else if (glslangIntermediate->getLayoutDerivativeModeNone() == glslang::LayoutDerivativeGroupLinear) {
1309 builder.addCapability(spv::CapabilityComputeDerivativeGroupLinearNV);
1310 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDerivativeGroupLinearNV);
1311 builder.addExtension(spv::E_SPV_NV_compute_shader_derivatives);
1312 }
1313#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001314 break;
1315
1316 default:
1317 break;
1318 }
John Kessenich140f3df2015-06-26 16:58:36 -06001319}
1320
John Kessenichfca82622016-11-26 13:23:20 -07001321// Finish creating SPV, after the traversal is complete.
1322void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001323{
John Kessenichf04c51b2018-08-03 15:56:12 -06001324 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001325 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001326 builder.setBuildPoint(shaderEntry->getLastBlock());
1327 builder.leaveFunction();
1328 }
1329
John Kessenich7ba63412015-12-20 17:37:07 -07001330 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001331 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1332 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001333
John Kessenichf04c51b2018-08-03 15:56:12 -06001334 // Add capabilities, extensions, remove unneeded decorations, etc.,
1335 // based on the resulting SPIR-V.
1336 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001337}
1338
John Kessenichfca82622016-11-26 13:23:20 -07001339// Write the SPV into 'out'.
1340void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001341{
John Kessenichfca82622016-11-26 13:23:20 -07001342 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001343}
1344
1345//
1346// Implement the traversal functions.
1347//
1348// Return true from interior nodes to have the external traversal
1349// continue on to children. Return false if children were
1350// already processed.
1351//
1352
1353//
qining25262b32016-05-06 17:25:16 -04001354// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001355// - uniform/input reads
1356// - output writes
1357// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1358// - something simple that degenerates into the last bullet
1359//
1360void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1361{
qining75d1d802016-04-06 14:42:01 -04001362 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1363 if (symbol->getType().getQualifier().isSpecConstant())
1364 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1365
John Kessenich140f3df2015-06-26 16:58:36 -06001366 // getSymbolId() will set up all the IO decorations on the first call.
1367 // Formal function parameters were mapped during makeFunctions().
1368 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001369
1370 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1371 if (builder.isPointer(id)) {
1372 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001373 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1374 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1375 iOSet.insert(id);
1376 }
John Kessenich7ba63412015-12-20 17:37:07 -07001377 }
1378
1379 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001380 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001381 // Prepare to generate code for the access
1382
1383 // L-value chains will be computed left to right. We're on the symbol now,
1384 // which is the left-most part of the access chain, so now is "clear" time,
1385 // followed by setting the base.
1386 builder.clearAccessChain();
1387
1388 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001389 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001390 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001391 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001392 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001393 // These are also pure R-values.
1394 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001395 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001396 builder.setAccessChainRValue(id);
1397 else
1398 builder.setAccessChainLValue(id);
1399 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001400
1401 // Process linkage-only nodes for any special additional interface work.
1402 if (linkageOnly) {
1403 if (glslangIntermediate->getHlslFunctionality1()) {
1404 // Map implicit counter buffers to their originating buffers, which should have been
1405 // seen by now, given earlier pruning of unused counters, and preservation of order
1406 // of declaration.
1407 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1408 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1409 // Save possible originating buffers for counter buffers, keyed by
1410 // making the potential counter-buffer name.
1411 std::string keyName = symbol->getName().c_str();
1412 keyName = glslangIntermediate->addCounterBufferName(keyName);
1413 counterOriginator[keyName] = symbol;
1414 } else {
1415 // Handle a counter buffer, by finding the saved originating buffer.
1416 std::string keyName = symbol->getName().c_str();
1417 auto it = counterOriginator.find(keyName);
1418 if (it != counterOriginator.end()) {
1419 id = getSymbolId(it->second);
1420 if (id != spv::NoResult) {
1421 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001422 if (counterId != spv::NoResult) {
1423 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001424 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001425 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001426 }
1427 }
1428 }
1429 }
1430 }
1431 }
John Kessenich140f3df2015-06-26 16:58:36 -06001432}
1433
1434bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1435{
John Kesseniche485c7a2017-05-31 18:50:53 -06001436 builder.setLine(node->getLoc().line);
1437
qining40887662016-04-03 22:20:42 -04001438 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1439 if (node->getType().getQualifier().isSpecConstant())
1440 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1441
John Kessenich140f3df2015-06-26 16:58:36 -06001442 // First, handle special cases
1443 switch (node->getOp()) {
1444 case glslang::EOpAssign:
1445 case glslang::EOpAddAssign:
1446 case glslang::EOpSubAssign:
1447 case glslang::EOpMulAssign:
1448 case glslang::EOpVectorTimesMatrixAssign:
1449 case glslang::EOpVectorTimesScalarAssign:
1450 case glslang::EOpMatrixTimesScalarAssign:
1451 case glslang::EOpMatrixTimesMatrixAssign:
1452 case glslang::EOpDivAssign:
1453 case glslang::EOpModAssign:
1454 case glslang::EOpAndAssign:
1455 case glslang::EOpInclusiveOrAssign:
1456 case glslang::EOpExclusiveOrAssign:
1457 case glslang::EOpLeftShiftAssign:
1458 case glslang::EOpRightShiftAssign:
1459 // A bin-op assign "a += b" means the same thing as "a = a + b"
1460 // where a is evaluated before b. For a simple assignment, GLSL
1461 // says to evaluate the left before the right. So, always, left
1462 // node then right node.
1463 {
1464 // get the left l-value, save it away
1465 builder.clearAccessChain();
1466 node->getLeft()->traverse(this);
1467 spv::Builder::AccessChain lValue = builder.getAccessChain();
1468
1469 // evaluate the right
1470 builder.clearAccessChain();
1471 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001472 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001473
1474 if (node->getOp() != glslang::EOpAssign) {
1475 // the left is also an r-value
1476 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001477 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001478
1479 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001480 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001481 TranslateNoContractionDecoration(node->getType().getQualifier()),
1482 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001483 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001484 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1485 node->getType().getBasicType());
1486
1487 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001488 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001489 }
1490
1491 // store the result
1492 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001493 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001494
1495 // assignments are expressions having an rValue after they are evaluated...
1496 builder.clearAccessChain();
1497 builder.setAccessChainRValue(rValue);
1498 }
1499 return false;
1500 case glslang::EOpIndexDirect:
1501 case glslang::EOpIndexDirectStruct:
1502 {
1503 // Get the left part of the access chain.
1504 node->getLeft()->traverse(this);
1505
1506 // Add the next element in the chain
1507
David Netoa901ffe2016-06-08 14:11:40 +01001508 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001509 if (! node->getLeft()->getType().isArray() &&
1510 node->getLeft()->getType().isVector() &&
1511 node->getOp() == glslang::EOpIndexDirect) {
1512 // This is essentially a hard-coded vector swizzle of size 1,
1513 // so short circuit the access-chain stuff with a swizzle.
1514 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001515 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001516 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001517 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001518 int spvIndex = glslangIndex;
1519 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1520 node->getOp() == glslang::EOpIndexDirectStruct)
1521 {
1522 // This may be, e.g., an anonymous block-member selection, which generally need
1523 // index remapping due to hidden members in anonymous blocks.
1524 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1525 assert(remapper.size() > 0);
1526 spvIndex = remapper[glslangIndex];
1527 }
John Kessenichebb50532016-05-16 19:22:05 -06001528
David Netoa901ffe2016-06-08 14:11:40 +01001529 // normal case for indexing array or structure or block
Jeff Bolz36831c92018-09-05 10:11:41 -05001530 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()));
David Netoa901ffe2016-06-08 14:11:40 +01001531
1532 // Add capabilities here for accessing PointSize and clip/cull distance.
1533 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001534 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001535 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001536 }
1537 }
1538 return false;
1539 case glslang::EOpIndexIndirect:
1540 {
1541 // Structure or array or vector indirection.
1542 // Will use native SPIR-V access-chain for struct and array indirection;
1543 // matrices are arrays of vectors, so will also work for a matrix.
1544 // Will use the access chain's 'component' for variable index into a vector.
1545
1546 // This adapter is building access chains left to right.
1547 // Set up the access chain to the left.
1548 node->getLeft()->traverse(this);
1549
1550 // save it so that computing the right side doesn't trash it
1551 spv::Builder::AccessChain partial = builder.getAccessChain();
1552
1553 // compute the next index in the chain
1554 builder.clearAccessChain();
1555 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001556 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001557
John Kessenich5611c6d2018-04-05 11:25:02 -06001558 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1559
John Kessenich140f3df2015-06-26 16:58:36 -06001560 // restore the saved access chain
1561 builder.setAccessChain(partial);
1562
1563 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001564 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001565 else
Jeff Bolz36831c92018-09-05 10:11:41 -05001566 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001567 }
1568 return false;
1569 case glslang::EOpVectorSwizzle:
1570 {
1571 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001572 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001573 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001574 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001575 }
1576 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001577 case glslang::EOpMatrixSwizzle:
1578 logger->missingFunctionality("matrix swizzle");
1579 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001580 case glslang::EOpLogicalOr:
1581 case glslang::EOpLogicalAnd:
1582 {
1583
1584 // These may require short circuiting, but can sometimes be done as straight
1585 // binary operations. The right operand must be short circuited if it has
1586 // side effects, and should probably be if it is complex.
1587 if (isTrivial(node->getRight()->getAsTyped()))
1588 break; // handle below as a normal binary operation
1589 // otherwise, we need to do dynamic short circuiting on the right operand
1590 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1591 builder.clearAccessChain();
1592 builder.setAccessChainRValue(result);
1593 }
1594 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001595 default:
1596 break;
1597 }
1598
1599 // Assume generic binary op...
1600
John Kessenich32cfd492016-02-02 12:37:46 -07001601 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001602 builder.clearAccessChain();
1603 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001604 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001605
John Kessenich32cfd492016-02-02 12:37:46 -07001606 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001607 builder.clearAccessChain();
1608 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001609 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001610
John Kessenich32cfd492016-02-02 12:37:46 -07001611 // get result
John Kessenichead86222018-03-28 18:01:20 -06001612 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001613 TranslateNoContractionDecoration(node->getType().getQualifier()),
1614 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001615 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001616 convertGlslangToSpvType(node->getType()), left, right,
1617 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001618
John Kessenich50e57562015-12-21 21:21:11 -07001619 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001620 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001621 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001622 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001623 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001624 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001625 return false;
1626 }
John Kessenich140f3df2015-06-26 16:58:36 -06001627}
1628
1629bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1630{
John Kesseniche485c7a2017-05-31 18:50:53 -06001631 builder.setLine(node->getLoc().line);
1632
qining40887662016-04-03 22:20:42 -04001633 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1634 if (node->getType().getQualifier().isSpecConstant())
1635 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1636
John Kessenichfc51d282015-08-19 13:34:18 -06001637 spv::Id result = spv::NoResult;
1638
1639 // try texturing first
1640 result = createImageTextureFunctionCall(node);
1641 if (result != spv::NoResult) {
1642 builder.clearAccessChain();
1643 builder.setAccessChainRValue(result);
1644
1645 return false; // done with this node
1646 }
1647
1648 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001649
1650 if (node->getOp() == glslang::EOpArrayLength) {
1651 // Quite special; won't want to evaluate the operand.
1652
John Kessenich5611c6d2018-04-05 11:25:02 -06001653 // Currently, the front-end does not allow .length() on an array until it is sized,
1654 // except for the last block membeor of an SSBO.
1655 // TODO: If this changes, link-time sized arrays might show up here, and need their
1656 // size extracted.
1657
John Kessenichc9a80832015-09-12 12:17:44 -06001658 // Normal .length() would have been constant folded by the front-end.
1659 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001660 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001661
John Kessenichc9a80832015-09-12 12:17:44 -06001662 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1663 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001664 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1665 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001666
1667 builder.clearAccessChain();
1668 builder.setAccessChainRValue(length);
1669
1670 return false;
1671 }
1672
John Kessenichfc51d282015-08-19 13:34:18 -06001673 // Start by evaluating the operand
1674
John Kessenich8c8505c2016-07-26 12:50:38 -06001675 // Does it need a swizzle inversion? If so, evaluation is inverted;
1676 // operate first on the swizzle base, then apply the swizzle.
1677 spv::Id invertedType = spv::NoType;
1678 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1679 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1680 invertedType = getInvertedSwizzleType(*node->getOperand());
1681
John Kessenich140f3df2015-06-26 16:58:36 -06001682 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001683 if (invertedType != spv::NoType)
1684 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1685 else
1686 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001687
Rex Xufc618912015-09-09 16:42:49 +08001688 spv::Id operand = spv::NoResult;
1689
1690 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1691 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001692 node->getOp() == glslang::EOpAtomicCounter ||
1693 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001694 operand = builder.accessChainGetLValue(); // Special case l-value operands
1695 else
John Kessenich32cfd492016-02-02 12:37:46 -07001696 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001697
John Kessenichead86222018-03-28 18:01:20 -06001698 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001699 TranslateNoContractionDecoration(node->getType().getQualifier()),
1700 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001701
1702 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001703 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001704 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001705
1706 // if not, then possibly an operation
1707 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001708 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001709
1710 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001711 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001712 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001713 builder.addDecoration(result, decorations.nonUniform);
1714 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001715
John Kessenich140f3df2015-06-26 16:58:36 -06001716 builder.clearAccessChain();
1717 builder.setAccessChainRValue(result);
1718
1719 return false; // done with this node
1720 }
1721
1722 // it must be a special case, check...
1723 switch (node->getOp()) {
1724 case glslang::EOpPostIncrement:
1725 case glslang::EOpPostDecrement:
1726 case glslang::EOpPreIncrement:
1727 case glslang::EOpPreDecrement:
1728 {
1729 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001730 spv::Id one = 0;
1731 if (node->getBasicType() == glslang::EbtFloat)
1732 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001733 else if (node->getBasicType() == glslang::EbtDouble)
1734 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001735 else if (node->getBasicType() == glslang::EbtFloat16)
1736 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001737 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1738 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001739 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1740 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001741 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1742 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001743 else
1744 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001745 glslang::TOperator op;
1746 if (node->getOp() == glslang::EOpPreIncrement ||
1747 node->getOp() == glslang::EOpPostIncrement)
1748 op = glslang::EOpAdd;
1749 else
1750 op = glslang::EOpSub;
1751
John Kessenichead86222018-03-28 18:01:20 -06001752 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001753 convertGlslangToSpvType(node->getType()), operand, one,
1754 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001755 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001756
1757 // The result of operation is always stored, but conditionally the
1758 // consumed result. The consumed result is always an r-value.
1759 builder.accessChainStore(result);
1760 builder.clearAccessChain();
1761 if (node->getOp() == glslang::EOpPreIncrement ||
1762 node->getOp() == glslang::EOpPreDecrement)
1763 builder.setAccessChainRValue(result);
1764 else
1765 builder.setAccessChainRValue(operand);
1766 }
1767
1768 return false;
1769
1770 case glslang::EOpEmitStreamVertex:
1771 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1772 return false;
1773 case glslang::EOpEndStreamPrimitive:
1774 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1775 return false;
1776
1777 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001778 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001779 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001780 }
John Kessenich140f3df2015-06-26 16:58:36 -06001781}
1782
1783bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1784{
qining27e04a02016-04-14 16:40:20 -04001785 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1786 if (node->getType().getQualifier().isSpecConstant())
1787 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1788
John Kessenichfc51d282015-08-19 13:34:18 -06001789 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001790 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1791 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001792
1793 // try texturing
1794 result = createImageTextureFunctionCall(node);
1795 if (result != spv::NoResult) {
1796 builder.clearAccessChain();
1797 builder.setAccessChainRValue(result);
1798
1799 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05001800 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08001801#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05001802 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08001803#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05001804 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08001805 // "imageStore" is a special case, which has no result
1806 return false;
1807 }
John Kessenichfc51d282015-08-19 13:34:18 -06001808
John Kessenich140f3df2015-06-26 16:58:36 -06001809 glslang::TOperator binOp = glslang::EOpNull;
1810 bool reduceComparison = true;
1811 bool isMatrix = false;
1812 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001813 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001814
1815 assert(node->getOp());
1816
John Kessenichf6640762016-08-01 19:44:00 -06001817 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001818
1819 switch (node->getOp()) {
1820 case glslang::EOpSequence:
1821 {
1822 if (preVisit)
1823 ++sequenceDepth;
1824 else
1825 --sequenceDepth;
1826
1827 if (sequenceDepth == 1) {
1828 // If this is the parent node of all the functions, we want to see them
1829 // early, so all call points have actual SPIR-V functions to reference.
1830 // In all cases, still let the traverser visit the children for us.
1831 makeFunctions(node->getAsAggregate()->getSequence());
1832
John Kessenich6fccb3c2016-09-19 16:01:41 -06001833 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001834 // anything else gets there, so visit out of order, doing them all now.
1835 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1836
John Kessenich6a60c2f2016-12-08 21:01:59 -07001837 // 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 -06001838 // so do them manually.
1839 visitFunctions(node->getAsAggregate()->getSequence());
1840
1841 return false;
1842 }
1843
1844 return true;
1845 }
1846 case glslang::EOpLinkerObjects:
1847 {
1848 if (visit == glslang::EvPreVisit)
1849 linkageOnly = true;
1850 else
1851 linkageOnly = false;
1852
1853 return true;
1854 }
1855 case glslang::EOpComma:
1856 {
1857 // processing from left to right naturally leaves the right-most
1858 // lying around in the access chain
1859 glslang::TIntermSequence& glslangOperands = node->getSequence();
1860 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1861 glslangOperands[i]->traverse(this);
1862
1863 return false;
1864 }
1865 case glslang::EOpFunction:
1866 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001867 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001868 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001869 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001870 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001871 } else {
1872 handleFunctionEntry(node);
1873 }
1874 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001875 if (inEntryPoint)
1876 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001877 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001878 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001879 }
1880
1881 return true;
1882 case glslang::EOpParameters:
1883 // Parameters will have been consumed by EOpFunction processing, but not
1884 // the body, so we still visited the function node's children, making this
1885 // child redundant.
1886 return false;
1887 case glslang::EOpFunctionCall:
1888 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001889 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001890 if (node->isUserDefined())
1891 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001892 // 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 -07001893 if (result) {
1894 builder.clearAccessChain();
1895 builder.setAccessChainRValue(result);
1896 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001897 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001898
1899 return false;
1900 }
1901 case glslang::EOpConstructMat2x2:
1902 case glslang::EOpConstructMat2x3:
1903 case glslang::EOpConstructMat2x4:
1904 case glslang::EOpConstructMat3x2:
1905 case glslang::EOpConstructMat3x3:
1906 case glslang::EOpConstructMat3x4:
1907 case glslang::EOpConstructMat4x2:
1908 case glslang::EOpConstructMat4x3:
1909 case glslang::EOpConstructMat4x4:
1910 case glslang::EOpConstructDMat2x2:
1911 case glslang::EOpConstructDMat2x3:
1912 case glslang::EOpConstructDMat2x4:
1913 case glslang::EOpConstructDMat3x2:
1914 case glslang::EOpConstructDMat3x3:
1915 case glslang::EOpConstructDMat3x4:
1916 case glslang::EOpConstructDMat4x2:
1917 case glslang::EOpConstructDMat4x3:
1918 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001919 case glslang::EOpConstructIMat2x2:
1920 case glslang::EOpConstructIMat2x3:
1921 case glslang::EOpConstructIMat2x4:
1922 case glslang::EOpConstructIMat3x2:
1923 case glslang::EOpConstructIMat3x3:
1924 case glslang::EOpConstructIMat3x4:
1925 case glslang::EOpConstructIMat4x2:
1926 case glslang::EOpConstructIMat4x3:
1927 case glslang::EOpConstructIMat4x4:
1928 case glslang::EOpConstructUMat2x2:
1929 case glslang::EOpConstructUMat2x3:
1930 case glslang::EOpConstructUMat2x4:
1931 case glslang::EOpConstructUMat3x2:
1932 case glslang::EOpConstructUMat3x3:
1933 case glslang::EOpConstructUMat3x4:
1934 case glslang::EOpConstructUMat4x2:
1935 case glslang::EOpConstructUMat4x3:
1936 case glslang::EOpConstructUMat4x4:
1937 case glslang::EOpConstructBMat2x2:
1938 case glslang::EOpConstructBMat2x3:
1939 case glslang::EOpConstructBMat2x4:
1940 case glslang::EOpConstructBMat3x2:
1941 case glslang::EOpConstructBMat3x3:
1942 case glslang::EOpConstructBMat3x4:
1943 case glslang::EOpConstructBMat4x2:
1944 case glslang::EOpConstructBMat4x3:
1945 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001946 case glslang::EOpConstructF16Mat2x2:
1947 case glslang::EOpConstructF16Mat2x3:
1948 case glslang::EOpConstructF16Mat2x4:
1949 case glslang::EOpConstructF16Mat3x2:
1950 case glslang::EOpConstructF16Mat3x3:
1951 case glslang::EOpConstructF16Mat3x4:
1952 case glslang::EOpConstructF16Mat4x2:
1953 case glslang::EOpConstructF16Mat4x3:
1954 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06001955 isMatrix = true;
1956 // fall through
1957 case glslang::EOpConstructFloat:
1958 case glslang::EOpConstructVec2:
1959 case glslang::EOpConstructVec3:
1960 case glslang::EOpConstructVec4:
1961 case glslang::EOpConstructDouble:
1962 case glslang::EOpConstructDVec2:
1963 case glslang::EOpConstructDVec3:
1964 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001965 case glslang::EOpConstructFloat16:
1966 case glslang::EOpConstructF16Vec2:
1967 case glslang::EOpConstructF16Vec3:
1968 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001969 case glslang::EOpConstructBool:
1970 case glslang::EOpConstructBVec2:
1971 case glslang::EOpConstructBVec3:
1972 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07001973 case glslang::EOpConstructInt8:
1974 case glslang::EOpConstructI8Vec2:
1975 case glslang::EOpConstructI8Vec3:
1976 case glslang::EOpConstructI8Vec4:
1977 case glslang::EOpConstructUint8:
1978 case glslang::EOpConstructU8Vec2:
1979 case glslang::EOpConstructU8Vec3:
1980 case glslang::EOpConstructU8Vec4:
1981 case glslang::EOpConstructInt16:
1982 case glslang::EOpConstructI16Vec2:
1983 case glslang::EOpConstructI16Vec3:
1984 case glslang::EOpConstructI16Vec4:
1985 case glslang::EOpConstructUint16:
1986 case glslang::EOpConstructU16Vec2:
1987 case glslang::EOpConstructU16Vec3:
1988 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001989 case glslang::EOpConstructInt:
1990 case glslang::EOpConstructIVec2:
1991 case glslang::EOpConstructIVec3:
1992 case glslang::EOpConstructIVec4:
1993 case glslang::EOpConstructUint:
1994 case glslang::EOpConstructUVec2:
1995 case glslang::EOpConstructUVec3:
1996 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001997 case glslang::EOpConstructInt64:
1998 case glslang::EOpConstructI64Vec2:
1999 case glslang::EOpConstructI64Vec3:
2000 case glslang::EOpConstructI64Vec4:
2001 case glslang::EOpConstructUint64:
2002 case glslang::EOpConstructU64Vec2:
2003 case glslang::EOpConstructU64Vec3:
2004 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06002005 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07002006 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06002007 {
John Kesseniche485c7a2017-05-31 18:50:53 -06002008 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06002009 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08002010 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06002011 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07002012 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06002013 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07002014 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06002015 std::vector<spv::Id> constituents;
2016 for (int c = 0; c < (int)arguments.size(); ++c)
2017 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06002018 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002019 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002020 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002021 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002022 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002023
2024 builder.clearAccessChain();
2025 builder.setAccessChainRValue(constructed);
2026
2027 return false;
2028 }
2029
2030 // These six are component-wise compares with component-wise results.
2031 // Forward on to createBinaryOperation(), requesting a vector result.
2032 case glslang::EOpLessThan:
2033 case glslang::EOpGreaterThan:
2034 case glslang::EOpLessThanEqual:
2035 case glslang::EOpGreaterThanEqual:
2036 case glslang::EOpVectorEqual:
2037 case glslang::EOpVectorNotEqual:
2038 {
2039 // Map the operation to a binary
2040 binOp = node->getOp();
2041 reduceComparison = false;
2042 switch (node->getOp()) {
2043 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2044 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2045 default: binOp = node->getOp(); break;
2046 }
2047
2048 break;
2049 }
2050 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002051 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002052 binOp = glslang::EOpMul;
2053 break;
2054 case glslang::EOpOuterProduct:
2055 // two vectors multiplied to make a matrix
2056 binOp = glslang::EOpOuterProduct;
2057 break;
2058 case glslang::EOpDot:
2059 {
qining25262b32016-05-06 17:25:16 -04002060 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002061 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002062 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002063 binOp = glslang::EOpMul;
2064 break;
2065 }
2066 case glslang::EOpMod:
2067 // when an aggregate, this is the floating-point mod built-in function,
2068 // which can be emitted by the one in createBinaryOperation()
2069 binOp = glslang::EOpMod;
2070 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002071 case glslang::EOpEmitVertex:
2072 case glslang::EOpEndPrimitive:
2073 case glslang::EOpBarrier:
2074 case glslang::EOpMemoryBarrier:
2075 case glslang::EOpMemoryBarrierAtomicCounter:
2076 case glslang::EOpMemoryBarrierBuffer:
2077 case glslang::EOpMemoryBarrierImage:
2078 case glslang::EOpMemoryBarrierShared:
2079 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002080 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002081 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002082 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002083 case glslang::EOpWorkgroupMemoryBarrier:
2084 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002085 case glslang::EOpSubgroupBarrier:
2086 case glslang::EOpSubgroupMemoryBarrier:
2087 case glslang::EOpSubgroupMemoryBarrierBuffer:
2088 case glslang::EOpSubgroupMemoryBarrierImage:
2089 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002090 noReturnValue = true;
2091 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2092 break;
2093
Jeff Bolz36831c92018-09-05 10:11:41 -05002094 case glslang::EOpAtomicStore:
2095 noReturnValue = true;
2096 // fallthrough
2097 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002098 case glslang::EOpAtomicAdd:
2099 case glslang::EOpAtomicMin:
2100 case glslang::EOpAtomicMax:
2101 case glslang::EOpAtomicAnd:
2102 case glslang::EOpAtomicOr:
2103 case glslang::EOpAtomicXor:
2104 case glslang::EOpAtomicExchange:
2105 case glslang::EOpAtomicCompSwap:
2106 atomic = true;
2107 break;
2108
John Kessenich0d0c6d32017-07-23 16:08:26 -06002109 case glslang::EOpAtomicCounterAdd:
2110 case glslang::EOpAtomicCounterSubtract:
2111 case glslang::EOpAtomicCounterMin:
2112 case glslang::EOpAtomicCounterMax:
2113 case glslang::EOpAtomicCounterAnd:
2114 case glslang::EOpAtomicCounterOr:
2115 case glslang::EOpAtomicCounterXor:
2116 case glslang::EOpAtomicCounterExchange:
2117 case glslang::EOpAtomicCounterCompSwap:
2118 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2119 builder.addCapability(spv::CapabilityAtomicStorageOps);
2120 atomic = true;
2121 break;
2122
John Kessenich140f3df2015-06-26 16:58:36 -06002123 default:
2124 break;
2125 }
2126
2127 //
2128 // See if it maps to a regular operation.
2129 //
John Kessenich140f3df2015-06-26 16:58:36 -06002130 if (binOp != glslang::EOpNull) {
2131 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2132 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2133 assert(left && right);
2134
2135 builder.clearAccessChain();
2136 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002137 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002138
2139 builder.clearAccessChain();
2140 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002141 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002142
John Kesseniche485c7a2017-05-31 18:50:53 -06002143 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06002144 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002145 TranslateNoContractionDecoration(node->getType().getQualifier()),
2146 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002147 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002148 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002149 left->getType().getBasicType(), reduceComparison);
2150
2151 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002152 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002153 builder.clearAccessChain();
2154 builder.setAccessChainRValue(result);
2155
2156 return false;
2157 }
2158
John Kessenich426394d2015-07-23 10:22:48 -06002159 //
2160 // Create the list of operands.
2161 //
John Kessenich140f3df2015-06-26 16:58:36 -06002162 glslang::TIntermSequence& glslangOperands = node->getSequence();
2163 std::vector<spv::Id> operands;
2164 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002165 // special case l-value operands; there are just a few
2166 bool lvalue = false;
2167 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002168 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002169 case glslang::EOpModf:
2170 if (arg == 1)
2171 lvalue = true;
2172 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002173 case glslang::EOpInterpolateAtSample:
2174 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002175#ifdef AMD_EXTENSIONS
2176 case glslang::EOpInterpolateAtVertex:
2177#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002178 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002179 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002180
2181 // Does it need a swizzle inversion? If so, evaluation is inverted;
2182 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002183 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002184 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2185 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2186 }
Rex Xu7a26c172015-12-08 17:12:09 +08002187 break;
Rex Xud4782c12015-09-06 16:30:11 +08002188 case glslang::EOpAtomicAdd:
2189 case glslang::EOpAtomicMin:
2190 case glslang::EOpAtomicMax:
2191 case glslang::EOpAtomicAnd:
2192 case glslang::EOpAtomicOr:
2193 case glslang::EOpAtomicXor:
2194 case glslang::EOpAtomicExchange:
2195 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002196 case glslang::EOpAtomicLoad:
2197 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002198 case glslang::EOpAtomicCounterAdd:
2199 case glslang::EOpAtomicCounterSubtract:
2200 case glslang::EOpAtomicCounterMin:
2201 case glslang::EOpAtomicCounterMax:
2202 case glslang::EOpAtomicCounterAnd:
2203 case glslang::EOpAtomicCounterOr:
2204 case glslang::EOpAtomicCounterXor:
2205 case glslang::EOpAtomicCounterExchange:
2206 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002207 if (arg == 0)
2208 lvalue = true;
2209 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002210 case glslang::EOpAddCarry:
2211 case glslang::EOpSubBorrow:
2212 if (arg == 2)
2213 lvalue = true;
2214 break;
2215 case glslang::EOpUMulExtended:
2216 case glslang::EOpIMulExtended:
2217 if (arg >= 2)
2218 lvalue = true;
2219 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002220 default:
2221 break;
2222 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002223 builder.clearAccessChain();
2224 if (invertedType != spv::NoType && arg == 0)
2225 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2226 else
2227 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002228 if (lvalue)
2229 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002230 else {
2231 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002232 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002233 }
John Kessenich140f3df2015-06-26 16:58:36 -06002234 }
John Kessenich426394d2015-07-23 10:22:48 -06002235
John Kesseniche485c7a2017-05-31 18:50:53 -06002236 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002237 if (atomic) {
2238 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002239 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002240 } else {
2241 // Pass through to generic operations.
2242 switch (glslangOperands.size()) {
2243 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002244 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002245 break;
2246 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002247 {
2248 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002249 TranslateNoContractionDecoration(node->getType().getQualifier()),
2250 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002251 result = createUnaryOperation(
2252 node->getOp(), decorations,
2253 resultType(), operands.front(),
2254 glslangOperands[0]->getAsTyped()->getBasicType());
2255 }
John Kessenich426394d2015-07-23 10:22:48 -06002256 break;
2257 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002258 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002259 break;
2260 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002261 if (invertedType)
2262 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002263 }
2264
2265 if (noReturnValue)
2266 return false;
2267
2268 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002269 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002270 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002271 } else {
2272 builder.clearAccessChain();
2273 builder.setAccessChainRValue(result);
2274 return false;
2275 }
2276}
2277
John Kessenich433e9ff2017-01-26 20:31:11 -07002278// This path handles both if-then-else and ?:
2279// The if-then-else has a node type of void, while
2280// ?: has either a void or a non-void node type
2281//
2282// Leaving the result, when not void:
2283// GLSL only has r-values as the result of a :?, but
2284// if we have an l-value, that can be more efficient if it will
2285// become the base of a complex r-value expression, because the
2286// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002287bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2288{
John Kessenich4bee5312018-02-20 21:29:05 -07002289 // See if it simple and safe, or required, to execute both sides.
2290 // Crucially, side effects must be either semantically required or avoided,
2291 // and there are performance trade-offs.
2292 // Return true if required or a good idea (and safe) to execute both sides,
2293 // false otherwise.
2294 const auto bothSidesPolicy = [&]() -> bool {
2295 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002296 if (node->getTrueBlock() == nullptr ||
2297 node->getFalseBlock() == nullptr)
2298 return false;
2299
John Kessenich4bee5312018-02-20 21:29:05 -07002300 // required? (unless we write additional code to look for side effects
2301 // and make performance trade-offs if none are present)
2302 if (!node->getShortCircuit())
2303 return true;
2304
2305 // if not required to execute both, decide based on performance/practicality...
2306
2307 // see if OpSelect can handle it
2308 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2309 node->getBasicType() == glslang::EbtVoid)
2310 return false;
2311
John Kessenich433e9ff2017-01-26 20:31:11 -07002312 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2313 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2314
2315 // return true if a single operand to ? : is okay for OpSelect
2316 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002317 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002318 };
2319
2320 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2321 operandOkay(node->getFalseBlock()->getAsTyped());
2322 };
2323
John Kessenich4bee5312018-02-20 21:29:05 -07002324 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2325 // emit the condition before doing anything with selection
2326 node->getCondition()->traverse(this);
2327 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2328
2329 // Find a way of executing both sides and selecting the right result.
2330 const auto executeBothSides = [&]() -> void {
2331 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002332 node->getTrueBlock()->traverse(this);
2333 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2334 node->getFalseBlock()->traverse(this);
2335 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2336
John Kesseniche485c7a2017-05-31 18:50:53 -06002337 builder.setLine(node->getLoc().line);
2338
John Kessenich4bee5312018-02-20 21:29:05 -07002339 // done if void
2340 if (node->getBasicType() == glslang::EbtVoid)
2341 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002342
John Kessenich4bee5312018-02-20 21:29:05 -07002343 // emit code to select between trueValue and falseValue
2344
2345 // see if OpSelect can handle it
2346 if (node->getType().isScalar() || node->getType().isVector()) {
2347 // Emit OpSelect for this selection.
2348
2349 // smear condition to vector, if necessary (AST is always scalar)
2350 if (builder.isVector(trueValue))
2351 condition = builder.smearScalar(spv::NoPrecision, condition,
2352 builder.makeVectorType(builder.makeBoolType(),
2353 builder.getNumComponents(trueValue)));
2354
2355 // OpSelect
2356 result = builder.createTriOp(spv::OpSelect,
2357 convertGlslangToSpvType(node->getType()), condition,
2358 trueValue, falseValue);
2359
2360 builder.clearAccessChain();
2361 builder.setAccessChainRValue(result);
2362 } else {
2363 // We need control flow to select the result.
2364 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2365 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2366
2367 // Selection control:
2368 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2369
2370 // make an "if" based on the value created by the condition
2371 spv::Builder::If ifBuilder(condition, control, builder);
2372
2373 // emit the "then" statement
2374 builder.createStore(trueValue, result);
2375 ifBuilder.makeBeginElse();
2376 // emit the "else" statement
2377 builder.createStore(falseValue, result);
2378
2379 // finish off the control flow
2380 ifBuilder.makeEndIf();
2381
2382 builder.clearAccessChain();
2383 builder.setAccessChainLValue(result);
2384 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002385 };
2386
John Kessenich4bee5312018-02-20 21:29:05 -07002387 // Execute the one side needed, as per the condition
2388 const auto executeOneSide = [&]() {
2389 // Always emit control flow.
2390 if (node->getBasicType() != glslang::EbtVoid)
2391 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002392
John Kessenich4bee5312018-02-20 21:29:05 -07002393 // Selection control:
2394 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2395
2396 // make an "if" based on the value created by the condition
2397 spv::Builder::If ifBuilder(condition, control, builder);
2398
2399 // emit the "then" statement
2400 if (node->getTrueBlock() != nullptr) {
2401 node->getTrueBlock()->traverse(this);
2402 if (result != spv::NoResult)
2403 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2404 }
2405
2406 if (node->getFalseBlock() != nullptr) {
2407 ifBuilder.makeBeginElse();
2408 // emit the "else" statement
2409 node->getFalseBlock()->traverse(this);
2410 if (result != spv::NoResult)
2411 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2412 }
2413
2414 // finish off the control flow
2415 ifBuilder.makeEndIf();
2416
2417 if (result != spv::NoResult) {
2418 builder.clearAccessChain();
2419 builder.setAccessChainLValue(result);
2420 }
2421 };
2422
2423 // Try for OpSelect (or a requirement to execute both sides)
2424 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002425 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2426 if (node->getType().getQualifier().isSpecConstant())
2427 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002428 executeBothSides();
2429 } else
2430 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002431
2432 return false;
2433}
2434
2435bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2436{
2437 // emit and get the condition before doing anything with switch
2438 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002439 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002440
Rex Xu57e65922017-07-04 23:23:40 +08002441 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002442 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002443
John Kessenich140f3df2015-06-26 16:58:36 -06002444 // browse the children to sort out code segments
2445 int defaultSegment = -1;
2446 std::vector<TIntermNode*> codeSegments;
2447 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2448 std::vector<int> caseValues;
2449 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2450 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2451 TIntermNode* child = *c;
2452 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002453 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002454 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002455 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002456 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2457 } else
2458 codeSegments.push_back(child);
2459 }
2460
qining25262b32016-05-06 17:25:16 -04002461 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002462 // statements between the last case and the end of the switch statement
2463 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2464 (int)codeSegments.size() == defaultSegment)
2465 codeSegments.push_back(nullptr);
2466
2467 // make the switch statement
2468 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002469 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002470
2471 // emit all the code in the segments
2472 breakForLoop.push(false);
2473 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2474 builder.nextSwitchSegment(segmentBlocks, s);
2475 if (codeSegments[s])
2476 codeSegments[s]->traverse(this);
2477 else
2478 builder.addSwitchBreak();
2479 }
2480 breakForLoop.pop();
2481
2482 builder.endSwitch(segmentBlocks);
2483
2484 return false;
2485}
2486
2487void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2488{
2489 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002490 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002491
2492 builder.clearAccessChain();
2493 builder.setAccessChainRValue(constant);
2494}
2495
2496bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2497{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002498 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002499 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002500
2501 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002502 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2503 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002504
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002505 // Spec requires back edges to target header blocks, and every header block
2506 // must dominate its merge block. Make a header block first to ensure these
2507 // conditions are met. By definition, it will contain OpLoopMerge, followed
2508 // by a block-ending branch. But we don't want to put any other body/test
2509 // instructions in it, since the body/test may have arbitrary instructions,
2510 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002511 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002512 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002513 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002514 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002515 spv::Block& test = builder.makeNewBlock();
2516 builder.createBranch(&test);
2517
2518 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002519 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002520 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002521 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2522
2523 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002524 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002525 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002526 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002527 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002528 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002529
2530 builder.setBuildPoint(&blocks.continue_target);
2531 if (node->getTerminal())
2532 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002533 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002534 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002535 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002536 builder.createBranch(&blocks.body);
2537
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002538 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002539 builder.setBuildPoint(&blocks.body);
2540 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002541 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002542 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002543 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002544
2545 builder.setBuildPoint(&blocks.continue_target);
2546 if (node->getTerminal())
2547 node->getTerminal()->traverse(this);
2548 if (node->getTest()) {
2549 node->getTest()->traverse(this);
2550 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002551 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002552 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002553 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002554 // TODO: unless there was a break/return/discard instruction
2555 // somewhere in the body, this is an infinite loop, so we should
2556 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002557 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002558 }
John Kessenich140f3df2015-06-26 16:58:36 -06002559 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002560 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002561 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002562 return false;
2563}
2564
2565bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2566{
2567 if (node->getExpression())
2568 node->getExpression()->traverse(this);
2569
John Kesseniche485c7a2017-05-31 18:50:53 -06002570 builder.setLine(node->getLoc().line);
2571
John Kessenich140f3df2015-06-26 16:58:36 -06002572 switch (node->getFlowOp()) {
2573 case glslang::EOpKill:
2574 builder.makeDiscard();
2575 break;
2576 case glslang::EOpBreak:
2577 if (breakForLoop.top())
2578 builder.createLoopExit();
2579 else
2580 builder.addSwitchBreak();
2581 break;
2582 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002583 builder.createLoopContinue();
2584 break;
2585 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002586 if (node->getExpression()) {
2587 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2588 spv::Id returnId = accessChainLoad(glslangReturnType);
2589 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2590 builder.clearAccessChain();
2591 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2592 builder.setAccessChainLValue(copyId);
2593 multiTypeStore(glslangReturnType, returnId);
2594 returnId = builder.createLoad(copyId);
2595 }
2596 builder.makeReturn(false, returnId);
2597 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002598 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002599
2600 builder.clearAccessChain();
2601 break;
2602
2603 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002604 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002605 break;
2606 }
2607
2608 return false;
2609}
2610
2611spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2612{
qining25262b32016-05-06 17:25:16 -04002613 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002614 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002615 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002616 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002617 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002618 }
2619
2620 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002621 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002622 spv::Id spvType = convertGlslangToSpvType(node->getType());
2623
Rex Xucabbb782017-03-24 13:41:14 +08002624 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2625 node->getType().containsBasicType(glslang::EbtInt16) ||
2626 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002627 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002628 switch (storageClass) {
2629 case spv::StorageClassInput:
2630 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002631 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002632 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002633 break;
2634 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002635 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002636 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002637 break;
2638 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002639 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002640 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2641 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002642 else
2643 builder.addCapability(spv::CapabilityStorageUniform16);
2644 break;
2645 case spv::StorageClassStorageBuffer:
2646 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2647 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2648 break;
2649 default:
2650 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002651 }
2652 }
Rex Xuf89ad982017-04-07 23:22:33 +08002653
John Kessenich312dcfb2018-07-03 13:19:51 -06002654 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2655 node->getType().containsBasicType(glslang::EbtUint8);
2656 if (contains8BitType) {
2657 if (storageClass == spv::StorageClassPushConstant) {
2658 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2659 builder.addCapability(spv::CapabilityStoragePushConstant8);
2660 } else if (storageClass == spv::StorageClassUniform) {
2661 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2662 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
2663 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2664 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
2665 }
2666 }
2667
John Kessenich140f3df2015-06-26 16:58:36 -06002668 const char* name = node->getName().c_str();
2669 if (glslang::IsAnonymous(name))
2670 name = "";
2671
2672 return builder.createVariable(storageClass, spvType, name);
2673}
2674
2675// Return type Id of the sampled type.
2676spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2677{
2678 switch (sampler.type) {
2679 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002680#ifdef AMD_EXTENSIONS
2681 case glslang::EbtFloat16:
2682 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2683 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2684 return builder.makeFloatType(16);
2685#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002686 case glslang::EbtInt: return builder.makeIntType(32);
2687 case glslang::EbtUint: return builder.makeUintType(32);
2688 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002689 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002690 return builder.makeFloatType(32);
2691 }
2692}
2693
John Kessenich8c8505c2016-07-26 12:50:38 -06002694// If node is a swizzle operation, return the type that should be used if
2695// the swizzle base is first consumed by another operation, before the swizzle
2696// is applied.
2697spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2698{
John Kessenichecba76f2017-01-06 00:34:48 -07002699 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002700 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2701 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2702 else
2703 return spv::NoType;
2704}
2705
2706// When inverting a swizzle with a parent op, this function
2707// will apply the swizzle operation to a completed parent operation.
2708spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2709{
2710 std::vector<unsigned> swizzle;
2711 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2712 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2713}
2714
John Kessenich8c8505c2016-07-26 12:50:38 -06002715// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2716void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2717{
2718 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2719 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2720 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2721}
2722
John Kessenich3ac051e2015-12-20 11:29:16 -07002723// Convert from a glslang type to an SPV type, by calling into a
2724// recursive version of this function. This establishes the inherited
2725// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002726spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2727{
John Kessenichead86222018-03-28 18:01:20 -06002728 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002729}
2730
2731// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002732// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002733// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002734spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2735 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002736{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002737 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002738
2739 switch (type.getBasicType()) {
2740 case glslang::EbtVoid:
2741 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002742 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002743 break;
2744 case glslang::EbtFloat:
2745 spvType = builder.makeFloatType(32);
2746 break;
2747 case glslang::EbtDouble:
2748 spvType = builder.makeFloatType(64);
2749 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002750 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002751 spvType = builder.makeFloatType(16);
2752 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002753 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002754 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2755 // a 32-bit int where non-0 means true.
2756 if (explicitLayout != glslang::ElpNone)
2757 spvType = builder.makeUintType(32);
2758 else
2759 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002760 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002761 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07002762 spvType = builder.makeIntType(8);
2763 break;
2764 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07002765 spvType = builder.makeUintType(8);
2766 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002767 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07002768 spvType = builder.makeIntType(16);
2769 break;
2770 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07002771 spvType = builder.makeUintType(16);
2772 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002773 case glslang::EbtInt:
2774 spvType = builder.makeIntType(32);
2775 break;
2776 case glslang::EbtUint:
2777 spvType = builder.makeUintType(32);
2778 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002779 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002780 spvType = builder.makeIntType(64);
2781 break;
2782 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002783 spvType = builder.makeUintType(64);
2784 break;
John Kessenich426394d2015-07-23 10:22:48 -06002785 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002786 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002787 spvType = builder.makeUintType(32);
2788 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002789 case glslang::EbtSampler:
2790 {
2791 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002792 if (sampler.sampler) {
2793 // pure sampler
2794 spvType = builder.makeSamplerType();
2795 } else {
2796 // an image is present, make its type
2797 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2798 sampler.image ? 2 : 1, TranslateImageFormat(type));
2799 if (sampler.combined) {
2800 // already has both image and sampler, make the combined type
2801 spvType = builder.makeSampledImageType(spvType);
2802 }
John Kessenich55e7d112015-11-15 21:33:39 -07002803 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002804 }
John Kessenich140f3df2015-06-26 16:58:36 -06002805 break;
2806 case glslang::EbtStruct:
2807 case glslang::EbtBlock:
2808 {
2809 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002810 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002811
2812 // Try to share structs for different layouts, but not yet for other
2813 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002814 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002815 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002816 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002817 break;
2818
2819 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002820 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002821 memberRemapper[glslangMembers].resize(glslangMembers->size());
2822 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002823 }
2824 break;
2825 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002826 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002827 break;
2828 }
2829
2830 if (type.isMatrix())
2831 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2832 else {
2833 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2834 if (type.getVectorSize() > 1)
2835 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2836 }
2837
2838 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002839 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2840
John Kessenichc9a80832015-09-12 12:17:44 -06002841 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002842 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002843 // We need to decorate array strides for types needing explicit layout, except blocks.
2844 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002845 // Use a dummy glslang type for querying internal strides of
2846 // arrays of arrays, but using just a one-dimensional array.
2847 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06002848 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
2849 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07002850
2851 // Will compute the higher-order strides here, rather than making a whole
2852 // pile of types and doing repetitive recursion on their contents.
2853 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2854 }
John Kessenichf8842e52016-01-04 19:22:56 -07002855
2856 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002857 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002858 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002859 if (stride > 0)
2860 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002861 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002862 }
2863 } else {
2864 // single-dimensional array, and don't yet have stride
2865
John Kessenichf8842e52016-01-04 19:22:56 -07002866 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002867 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2868 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002869 }
John Kessenich31ed4832015-09-09 17:51:38 -06002870
John Kessenichead86222018-03-28 18:01:20 -06002871 // Do the outer dimension, which might not be known for a runtime-sized array.
2872 // (Unsized arrays that survive through linking will be runtime-sized arrays)
2873 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07002874 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06002875 else {
2876 if (!lastBufferBlockMember) {
2877 builder.addExtension("SPV_EXT_descriptor_indexing");
2878 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
2879 }
John Kessenichead86222018-03-28 18:01:20 -06002880 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06002881 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002882 if (stride > 0)
2883 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002884 }
2885
2886 return spvType;
2887}
2888
John Kessenich0e737842017-03-24 18:38:16 -06002889// TODO: this functionality should exist at a higher level, in creating the AST
2890//
2891// Identify interface members that don't have their required extension turned on.
2892//
2893bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2894{
2895 auto& extensions = glslangIntermediate->getRequestedExtensions();
2896
Rex Xubcf291a2017-03-29 23:01:36 +08002897 if (member.getFieldName() == "gl_ViewportMask" &&
2898 extensions.find("GL_NV_viewport_array2") == extensions.end())
2899 return true;
2900 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2901 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2902 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002903 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2904 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2905 return true;
2906 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2907 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2908 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002909 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2910 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2911 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002912
2913 return false;
2914};
2915
John Kessenich6090df02016-06-30 21:18:02 -06002916// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2917// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2918// Mutually recursive with convertGlslangToSpvType().
2919spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2920 const glslang::TTypeList* glslangMembers,
2921 glslang::TLayoutPacking explicitLayout,
2922 const glslang::TQualifier& qualifier)
2923{
2924 // Create a vector of struct types for SPIR-V to consume
2925 std::vector<spv::Id> spvMembers;
2926 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 -06002927 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2928 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2929 if (glslangMember.hiddenMember()) {
2930 ++memberDelta;
2931 if (type.getBasicType() == glslang::EbtBlock)
2932 memberRemapper[glslangMembers][i] = -1;
2933 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002934 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002935 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002936 if (filterMember(glslangMember))
2937 continue;
2938 }
John Kessenich6090df02016-06-30 21:18:02 -06002939 // modify just this child's view of the qualifier
2940 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2941 InheritQualifiers(memberQualifier, qualifier);
2942
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002943 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002944 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002945 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002946
2947 // recurse
John Kessenichead86222018-03-28 18:01:20 -06002948 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
2949 i == (int)glslangMembers->size() - 1;
2950 spvMembers.push_back(
2951 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06002952 }
2953 }
2954
2955 // Make the SPIR-V type
2956 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002957 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002958 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2959
2960 // Decorate it
2961 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2962
2963 return spvType;
2964}
2965
2966void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2967 const glslang::TTypeList* glslangMembers,
2968 glslang::TLayoutPacking explicitLayout,
2969 const glslang::TQualifier& qualifier,
2970 spv::Id spvType)
2971{
2972 // Name and decorate the non-hidden members
2973 int offset = -1;
2974 int locationOffset = 0; // for use within the members of this struct
2975 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2976 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2977 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002978 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002979 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002980 if (filterMember(glslangMember))
2981 continue;
2982 }
John Kessenich6090df02016-06-30 21:18:02 -06002983
2984 // modify just this child's view of the qualifier
2985 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2986 InheritQualifiers(memberQualifier, qualifier);
2987
2988 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07002989 if (member < 0)
2990 continue;
2991
2992 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2993 builder.addMemberDecoration(spvType, member,
2994 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2995 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2996 // Add interpolation and auxiliary storage decorations only to
2997 // top-level members of Input and Output storage classes
2998 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2999 type.getQualifier().storage == glslang::EvqVaryingOut) {
3000 if (type.getBasicType() == glslang::EbtBlock ||
3001 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
3002 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
3003 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003004 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003005 }
3006 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06003007
John Kessenich5d610ee2018-03-07 18:05:55 -07003008 if (type.getBasicType() == glslang::EbtBlock &&
3009 qualifier.storage == glslang::EvqBuffer) {
3010 // Add memory decorations only to top-level members of shader storage block
3011 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05003012 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07003013 for (unsigned int i = 0; i < memory.size(); ++i)
3014 builder.addMemberDecoration(spvType, member, memory[i]);
3015 }
John Kessenich6090df02016-06-30 21:18:02 -06003016
John Kessenich5d610ee2018-03-07 18:05:55 -07003017 // Location assignment was already completed correctly by the front end,
3018 // just track whether a member needs to be decorated.
3019 // Ignore member locations if the container is an array, as that's
3020 // ill-specified and decisions have been made to not allow this.
3021 if (! type.isArray() && memberQualifier.hasLocation())
3022 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003023
John Kessenich5d610ee2018-03-07 18:05:55 -07003024 if (qualifier.hasLocation()) // track for upcoming inheritance
3025 locationOffset += glslangIntermediate->computeTypeLocationSize(
3026 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003027
John Kessenich5d610ee2018-03-07 18:05:55 -07003028 // component, XFB, others
3029 if (glslangMember.getQualifier().hasComponent())
3030 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3031 glslangMember.getQualifier().layoutComponent);
3032 if (glslangMember.getQualifier().hasXfbOffset())
3033 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3034 glslangMember.getQualifier().layoutXfbOffset);
3035 else if (explicitLayout != glslang::ElpNone) {
3036 // figure out what to do with offset, which is accumulating
3037 int nextOffset;
3038 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3039 if (offset >= 0)
3040 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3041 offset = nextOffset;
3042 }
John Kessenich6090df02016-06-30 21:18:02 -06003043
John Kessenich5d610ee2018-03-07 18:05:55 -07003044 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3045 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3046 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003047
John Kessenich5d610ee2018-03-07 18:05:55 -07003048 // built-in variable decorations
3049 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3050 if (builtIn != spv::BuiltInMax)
3051 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003052
John Kessenich5611c6d2018-04-05 11:25:02 -06003053 // nonuniform
3054 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3055
John Kessenichead86222018-03-28 18:01:20 -06003056 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3057 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3058 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3059 memberQualifier.semanticName);
3060 }
3061
chaoc771d89f2017-01-13 01:10:53 -08003062#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003063 if (builtIn == spv::BuiltInLayer) {
3064 // SPV_NV_viewport_array2 extension
3065 if (glslangMember.getQualifier().layoutViewportRelative){
3066 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3067 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3068 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003069 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003070 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3071 builder.addMemberDecoration(spvType, member,
3072 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3073 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3074 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3075 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003076 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003077 }
3078 if (glslangMember.getQualifier().layoutPassthrough) {
3079 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3080 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3081 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3082 }
chaoc771d89f2017-01-13 01:10:53 -08003083#endif
John Kessenich6090df02016-06-30 21:18:02 -06003084 }
3085
3086 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003087 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3088 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003089 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
3090 builder.addCapability(spv::CapabilityGeometryStreams);
3091 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
3092 }
John Kessenich6090df02016-06-30 21:18:02 -06003093}
3094
John Kessenich6c292d32016-02-15 20:58:50 -07003095// Turn the expression forming the array size into an id.
3096// This is not quite trivial, because of specialization constants.
3097// Sometimes, a raw constant is turned into an Id, and sometimes
3098// a specialization constant expression is.
3099spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3100{
3101 // First, see if this is sized with a node, meaning a specialization constant:
3102 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3103 if (specNode != nullptr) {
3104 builder.clearAccessChain();
3105 specNode->traverse(this);
3106 return accessChainLoad(specNode->getAsTyped()->getType());
3107 }
qining25262b32016-05-06 17:25:16 -04003108
John Kessenich6c292d32016-02-15 20:58:50 -07003109 // Otherwise, need a compile-time (front end) size, get it:
3110 int size = arraySizes.getDimSize(dim);
3111 assert(size > 0);
3112 return builder.makeUintConstant(size);
3113}
3114
John Kessenich103bef92016-02-08 21:38:15 -07003115// Wrap the builder's accessChainLoad to:
3116// - localize handling of RelaxedPrecision
3117// - use the SPIR-V inferred type instead of another conversion of the glslang type
3118// (avoids unnecessary work and possible type punning for structures)
3119// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003120spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3121{
John Kessenich103bef92016-02-08 21:38:15 -07003122 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003123
3124 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3125 coherentFlags |= TranslateCoherent(type);
3126
John Kessenich5611c6d2018-04-05 11:25:02 -06003127 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003128 TranslateNonUniformDecoration(type.getQualifier()),
3129 nominalTypeId,
3130 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
3131 TranslateMemoryScope(coherentFlags));
John Kessenich103bef92016-02-08 21:38:15 -07003132
3133 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003134 if (type.getBasicType() == glslang::EbtBool) {
3135 if (builder.isScalarType(nominalTypeId)) {
3136 // Conversion for bool
3137 spv::Id boolType = builder.makeBoolType();
3138 if (nominalTypeId != boolType)
3139 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3140 } else if (builder.isVectorType(nominalTypeId)) {
3141 // Conversion for bvec
3142 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3143 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3144 if (nominalTypeId != bvecType)
3145 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3146 }
3147 }
John Kessenich103bef92016-02-08 21:38:15 -07003148
3149 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003150}
3151
Rex Xu27253232016-02-23 17:51:09 +08003152// Wrap the builder's accessChainStore to:
3153// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003154//
3155// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003156void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3157{
3158 // Need to convert to abstract types when necessary
3159 if (type.getBasicType() == glslang::EbtBool) {
3160 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3161
3162 if (builder.isScalarType(nominalTypeId)) {
3163 // Conversion for bool
3164 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003165 if (nominalTypeId != boolType) {
3166 // keep these outside arguments, for determinant order-of-evaluation
3167 spv::Id one = builder.makeUintConstant(1);
3168 spv::Id zero = builder.makeUintConstant(0);
3169 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3170 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003171 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003172 } else if (builder.isVectorType(nominalTypeId)) {
3173 // Conversion for bvec
3174 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3175 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003176 if (nominalTypeId != bvecType) {
3177 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003178 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3179 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3180 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003181 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003182 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3183 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003184 }
3185 }
3186
Jeff Bolz36831c92018-09-05 10:11:41 -05003187 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3188 coherentFlags |= TranslateCoherent(type);
3189
3190 builder.accessChainStore(rvalue,
3191 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
3192 TranslateMemoryScope(coherentFlags));
Rex Xu27253232016-02-23 17:51:09 +08003193}
3194
John Kessenich4bf71552016-09-02 11:20:21 -06003195// For storing when types match at the glslang level, but not might match at the
3196// SPIR-V level.
3197//
3198// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003199// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003200// as in a member-decorated way.
3201//
3202// NOTE: This function can handle any store request; if it's not special it
3203// simplifies to a simple OpStore.
3204//
3205// Implicitly uses the existing builder.accessChain as the storage target.
3206void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3207{
John Kessenichb3e24e42016-09-11 12:33:43 -06003208 // we only do the complex path here if it's an aggregate
3209 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003210 accessChainStore(type, rValue);
3211 return;
3212 }
3213
John Kessenichb3e24e42016-09-11 12:33:43 -06003214 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003215 spv::Id rType = builder.getTypeId(rValue);
3216 spv::Id lValue = builder.accessChainGetLValue();
3217 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3218 if (lType == rType) {
3219 accessChainStore(type, rValue);
3220 return;
3221 }
3222
John Kessenichb3e24e42016-09-11 12:33:43 -06003223 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003224 // where the two types were the same type in GLSL. This requires member
3225 // by member copy, recursively.
3226
John Kessenichb3e24e42016-09-11 12:33:43 -06003227 // If an array, copy element by element.
3228 if (type.isArray()) {
3229 glslang::TType glslangElementType(type, 0);
3230 spv::Id elementRType = builder.getContainedTypeId(rType);
3231 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3232 // get the source member
3233 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003234
John Kessenichb3e24e42016-09-11 12:33:43 -06003235 // set up the target storage
3236 builder.clearAccessChain();
3237 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003238 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type));
John Kessenich4bf71552016-09-02 11:20:21 -06003239
John Kessenichb3e24e42016-09-11 12:33:43 -06003240 // store the member
3241 multiTypeStore(glslangElementType, elementRValue);
3242 }
3243 } else {
3244 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003245
John Kessenichb3e24e42016-09-11 12:33:43 -06003246 // loop over structure members
3247 const glslang::TTypeList& members = *type.getStruct();
3248 for (int m = 0; m < (int)members.size(); ++m) {
3249 const glslang::TType& glslangMemberType = *members[m].type;
3250
3251 // get the source member
3252 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3253 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3254
3255 // set up the target storage
3256 builder.clearAccessChain();
3257 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003258 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type));
John Kessenichb3e24e42016-09-11 12:33:43 -06003259
3260 // store the member
3261 multiTypeStore(glslangMemberType, memberRValue);
3262 }
John Kessenich4bf71552016-09-02 11:20:21 -06003263 }
3264}
3265
John Kessenichf85e8062015-12-19 13:57:10 -07003266// Decide whether or not this type should be
3267// decorated with offsets and strides, and if so
3268// whether std140 or std430 rules should be applied.
3269glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003270{
John Kessenichf85e8062015-12-19 13:57:10 -07003271 // has to be a block
3272 if (type.getBasicType() != glslang::EbtBlock)
3273 return glslang::ElpNone;
3274
3275 // has to be a uniform or buffer block
3276 if (type.getQualifier().storage != glslang::EvqUniform &&
3277 type.getQualifier().storage != glslang::EvqBuffer)
3278 return glslang::ElpNone;
3279
3280 // return the layout to use
3281 switch (type.getQualifier().layoutPacking) {
3282 case glslang::ElpStd140:
3283 case glslang::ElpStd430:
3284 return type.getQualifier().layoutPacking;
3285 default:
3286 return glslang::ElpNone;
3287 }
John Kessenich31ed4832015-09-09 17:51:38 -06003288}
3289
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003290// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003291int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003292{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003293 int size;
John Kessenich49987892015-12-29 17:11:44 -07003294 int stride;
3295 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003296
3297 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003298}
3299
John Kessenich49987892015-12-29 17:11:44 -07003300// 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 -07003301// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003302int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003303{
John Kessenich49987892015-12-29 17:11:44 -07003304 glslang::TType elementType;
3305 elementType.shallowCopy(matrixType);
3306 elementType.clearArraySizes();
3307
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003308 int size;
John Kessenich49987892015-12-29 17:11:44 -07003309 int stride;
3310 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3311
3312 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003313}
3314
John Kessenich5e4b1242015-08-06 22:53:06 -06003315// Given a member type of a struct, realign the current offset for it, and compute
3316// the next (not yet aligned) offset for the next member, which will get aligned
3317// on the next call.
3318// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3319// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3320// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003321void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003322 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003323{
3324 // this will get a positive value when deemed necessary
3325 nextOffset = -1;
3326
John Kessenich5e4b1242015-08-06 22:53:06 -06003327 // override anything in currentOffset with user-set offset
3328 if (memberType.getQualifier().hasOffset())
3329 currentOffset = memberType.getQualifier().layoutOffset;
3330
3331 // It could be that current linker usage in glslang updated all the layoutOffset,
3332 // in which case the following code does not matter. But, that's not quite right
3333 // once cross-compilation unit GLSL validation is done, as the original user
3334 // settings are needed in layoutOffset, and then the following will come into play.
3335
John Kessenichf85e8062015-12-19 13:57:10 -07003336 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003337 if (! memberType.getQualifier().hasOffset())
3338 currentOffset = -1;
3339
3340 return;
3341 }
3342
John Kessenichf85e8062015-12-19 13:57:10 -07003343 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003344 if (currentOffset < 0)
3345 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003346
John Kessenich5e4b1242015-08-06 22:53:06 -06003347 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3348 // but possibly not yet correctly aligned.
3349
3350 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003351 int dummyStride;
3352 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003353
3354 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003355 // TODO: make this consistent in early phases of code:
3356 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3357 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3358 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003359 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003360 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003361 int dummySize;
3362 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3363 if (componentAlignment <= 4)
3364 memberAlignment = componentAlignment;
3365 }
3366
3367 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003368 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003369
3370 // Bump up to vec4 if there is a bad straddle
3371 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3372 glslang::RoundToPow2(currentOffset, 16);
3373
John Kessenich5e4b1242015-08-06 22:53:06 -06003374 nextOffset = currentOffset + memberSize;
3375}
3376
David Netoa901ffe2016-06-08 14:11:40 +01003377void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003378{
David Netoa901ffe2016-06-08 14:11:40 +01003379 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3380 switch (glslangBuiltIn)
3381 {
3382 case glslang::EbvClipDistance:
3383 case glslang::EbvCullDistance:
3384 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003385#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003386 case glslang::EbvViewportMaskNV:
3387 case glslang::EbvSecondaryPositionNV:
3388 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003389 case glslang::EbvPositionPerViewNV:
3390 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08003391#endif
David Netoa901ffe2016-06-08 14:11:40 +01003392 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3393 // Alternately, we could just call this for any glslang built-in, since the
3394 // capability already guards against duplicates.
3395 TranslateBuiltInDecoration(glslangBuiltIn, false);
3396 break;
3397 default:
3398 // Capabilities were already generated when the struct was declared.
3399 break;
3400 }
John Kessenichebb50532016-05-16 19:22:05 -06003401}
3402
John Kessenich6fccb3c2016-09-19 16:01:41 -06003403bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003404{
John Kessenicheee9d532016-09-19 18:09:30 -06003405 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003406}
3407
John Kessenichd41993d2017-09-10 15:21:05 -06003408// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003409// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3410// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003411bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003412{
John Kessenich6a14f782017-12-04 02:48:10 -07003413 assert(qualifier == glslang::EvqIn ||
3414 qualifier == glslang::EvqOut ||
3415 qualifier == glslang::EvqInOut ||
3416 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003417 return qualifier != glslang::EvqConstReadOnly;
3418}
3419
3420// Is parameter pass-by-original?
3421bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3422 bool implicitThisParam)
3423{
3424 if (implicitThisParam) // implicit this
3425 return true;
3426 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003427 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003428 return paramType.containsOpaque() || // sampler, etc.
3429 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3430}
3431
John Kessenich140f3df2015-06-26 16:58:36 -06003432// Make all the functions, skeletally, without actually visiting their bodies.
3433void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3434{
Jeff Bolz36831c92018-09-05 10:11:41 -05003435 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003436 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3437 if (paramPrecision != spv::NoPrecision)
3438 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003439 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenichfad62972017-07-18 02:35:46 -06003440 };
3441
John Kessenich140f3df2015-06-26 16:58:36 -06003442 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3443 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003444 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003445 continue;
3446
3447 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003448 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003449 //
qining25262b32016-05-06 17:25:16 -04003450 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003451 // function. What it is an address of varies:
3452 //
John Kessenich4bf71552016-09-02 11:20:21 -06003453 // - "in" parameters not marked as "const" can be written to without modifying the calling
3454 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003455 //
3456 // - "const in" parameters can just be the r-value, as no writes need occur.
3457 //
John Kessenich4bf71552016-09-02 11:20:21 -06003458 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3459 // 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 -06003460
3461 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003462 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003463 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3464
John Kessenichfad62972017-07-18 02:35:46 -06003465 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3466 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003467
John Kessenichfad62972017-07-18 02:35:46 -06003468 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003469 for (int p = 0; p < (int)parameters.size(); ++p) {
3470 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3471 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003472 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003473 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003474 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003475 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3476 else
John Kessenich4bf71552016-09-02 11:20:21 -06003477 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003478 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003479 paramTypes.push_back(typeId);
3480 }
3481
3482 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003483 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3484 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003485 glslFunction->getName().c_str(), paramTypes,
3486 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003487 if (implicitThis)
3488 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003489
3490 // Track function to emit/call later
3491 functionMap[glslFunction->getName().c_str()] = function;
3492
3493 // Set the parameter id's
3494 for (int p = 0; p < (int)parameters.size(); ++p) {
3495 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3496 // give a name too
3497 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3498 }
3499 }
3500}
3501
3502// Process all the initializers, while skipping the functions and link objects
3503void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3504{
3505 builder.setBuildPoint(shaderEntry->getLastBlock());
3506 for (int i = 0; i < (int)initializers.size(); ++i) {
3507 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3508 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3509
3510 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003511 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003512 initializer->traverse(this);
3513 }
3514 }
3515}
3516
3517// Process all the functions, while skipping initializers.
3518void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3519{
3520 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3521 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003522 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003523 node->traverse(this);
3524 }
3525}
3526
3527void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3528{
qining25262b32016-05-06 17:25:16 -04003529 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003530 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003531 currentFunction = functionMap[node->getName().c_str()];
3532 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003533 builder.setBuildPoint(functionBlock);
3534}
3535
Rex Xu04db3f52015-09-16 11:44:02 +08003536void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003537{
Rex Xufc618912015-09-09 16:42:49 +08003538 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003539
3540 glslang::TSampler sampler = {};
3541 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003542#ifdef AMD_EXTENSIONS
3543 bool f16ShadowCompare = false;
3544#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003545 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003546 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3547 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003548#ifdef AMD_EXTENSIONS
3549 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3550#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003551 }
3552
John Kessenich140f3df2015-06-26 16:58:36 -06003553 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3554 builder.clearAccessChain();
3555 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003556
3557 // Special case l-value operands
3558 bool lvalue = false;
3559 switch (node.getOp()) {
3560 case glslang::EOpImageAtomicAdd:
3561 case glslang::EOpImageAtomicMin:
3562 case glslang::EOpImageAtomicMax:
3563 case glslang::EOpImageAtomicAnd:
3564 case glslang::EOpImageAtomicOr:
3565 case glslang::EOpImageAtomicXor:
3566 case glslang::EOpImageAtomicExchange:
3567 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05003568 case glslang::EOpImageAtomicLoad:
3569 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08003570 if (i == 0)
3571 lvalue = true;
3572 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003573 case glslang::EOpSparseImageLoad:
3574 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3575 lvalue = true;
3576 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003577#ifdef AMD_EXTENSIONS
3578 case glslang::EOpSparseTexture:
3579 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3580 lvalue = true;
3581 break;
3582 case glslang::EOpSparseTextureClamp:
3583 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3584 lvalue = true;
3585 break;
3586 case glslang::EOpSparseTextureLod:
3587 case glslang::EOpSparseTextureOffset:
3588 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3589 lvalue = true;
3590 break;
3591#else
Rex Xu48edadf2015-12-31 16:11:41 +08003592 case glslang::EOpSparseTexture:
3593 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3594 lvalue = true;
3595 break;
3596 case glslang::EOpSparseTextureClamp:
3597 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3598 lvalue = true;
3599 break;
3600 case glslang::EOpSparseTextureLod:
3601 case glslang::EOpSparseTextureOffset:
3602 if (i == 3)
3603 lvalue = true;
3604 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003605#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003606 case glslang::EOpSparseTextureFetch:
3607 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3608 lvalue = true;
3609 break;
3610 case glslang::EOpSparseTextureFetchOffset:
3611 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3612 lvalue = true;
3613 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003614#ifdef AMD_EXTENSIONS
3615 case glslang::EOpSparseTextureLodOffset:
3616 case glslang::EOpSparseTextureGrad:
3617 case glslang::EOpSparseTextureOffsetClamp:
3618 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3619 lvalue = true;
3620 break;
3621 case glslang::EOpSparseTextureGradOffset:
3622 case glslang::EOpSparseTextureGradClamp:
3623 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3624 lvalue = true;
3625 break;
3626 case glslang::EOpSparseTextureGradOffsetClamp:
3627 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3628 lvalue = true;
3629 break;
3630#else
Rex Xu48edadf2015-12-31 16:11:41 +08003631 case glslang::EOpSparseTextureLodOffset:
3632 case glslang::EOpSparseTextureGrad:
3633 case glslang::EOpSparseTextureOffsetClamp:
3634 if (i == 4)
3635 lvalue = true;
3636 break;
3637 case glslang::EOpSparseTextureGradOffset:
3638 case glslang::EOpSparseTextureGradClamp:
3639 if (i == 5)
3640 lvalue = true;
3641 break;
3642 case glslang::EOpSparseTextureGradOffsetClamp:
3643 if (i == 6)
3644 lvalue = true;
3645 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003646#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003647 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003648 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3649 lvalue = true;
3650 break;
3651 case glslang::EOpSparseTextureGatherOffset:
3652 case glslang::EOpSparseTextureGatherOffsets:
3653 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3654 lvalue = true;
3655 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003656#ifdef AMD_EXTENSIONS
3657 case glslang::EOpSparseTextureGatherLod:
3658 if (i == 3)
3659 lvalue = true;
3660 break;
3661 case glslang::EOpSparseTextureGatherLodOffset:
3662 case glslang::EOpSparseTextureGatherLodOffsets:
3663 if (i == 4)
3664 lvalue = true;
3665 break;
Rex Xu129799a2017-07-05 17:23:28 +08003666 case glslang::EOpSparseImageLoadLod:
3667 if (i == 3)
3668 lvalue = true;
3669 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003670#endif
Rex Xufc618912015-09-09 16:42:49 +08003671 default:
3672 break;
3673 }
3674
Rex Xu6b86d492015-09-16 17:48:22 +08003675 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003676 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003677 else
John Kessenich32cfd492016-02-02 12:37:46 -07003678 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003679 }
3680}
3681
John Kessenichfc51d282015-08-19 13:34:18 -06003682void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003683{
John Kessenichfc51d282015-08-19 13:34:18 -06003684 builder.clearAccessChain();
3685 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003686 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003687}
John Kessenich140f3df2015-06-26 16:58:36 -06003688
John Kessenichfc51d282015-08-19 13:34:18 -06003689spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3690{
John Kesseniche485c7a2017-05-31 18:50:53 -06003691 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003692 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003693
3694 builder.setLine(node->getLoc().line);
3695
John Kessenichfc51d282015-08-19 13:34:18 -06003696 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05003697
3698 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
3699 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
3700 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003701#ifdef AMD_EXTENSIONS
3702 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3703 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3704 : false;
3705#endif
3706
John Kessenichfc51d282015-08-19 13:34:18 -06003707 std::vector<spv::Id> arguments;
3708 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003709 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003710 else
3711 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003712 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003713
3714 spv::Builder::TextureParameters params = { };
3715 params.sampler = arguments[0];
3716
Rex Xu04db3f52015-09-16 11:44:02 +08003717 glslang::TCrackedTextureOp cracked;
3718 node->crackTexture(sampler, cracked);
3719
amhagan05506bb2017-06-13 16:53:02 -04003720 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003721
John Kessenichfc51d282015-08-19 13:34:18 -06003722 // Check for queries
3723 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003724 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3725 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003726 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003727
John Kessenichfc51d282015-08-19 13:34:18 -06003728 switch (node->getOp()) {
3729 case glslang::EOpImageQuerySize:
3730 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003731 if (arguments.size() > 1) {
3732 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003733 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003734 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003735 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003736 case glslang::EOpImageQuerySamples:
3737 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003738 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003739 case glslang::EOpTextureQueryLod:
3740 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003741 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003742 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003743 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003744 case glslang::EOpSparseTexelsResident:
3745 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003746 default:
3747 assert(0);
3748 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003749 }
John Kessenich140f3df2015-06-26 16:58:36 -06003750 }
3751
LoopDawg4425f242018-02-18 11:40:01 -07003752 int components = node->getType().getVectorSize();
3753
3754 if (node->getOp() == glslang::EOpTextureFetch) {
3755 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3756 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3757 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3758 // here around e.g. which ones return scalars or other types.
3759 components = 4;
3760 }
3761
3762 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3763
3764 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3765
Rex Xufc618912015-09-09 16:42:49 +08003766 // Check for image functions other than queries
3767 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06003768 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06003769 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06003770 spv::IdImmediate image = { true, *(opIt++) };
3771 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07003772
3773 // Handle subpass operations
3774 // TODO: GLSL should change to have the "MS" only on the type rather than the
3775 // built-in function.
3776 if (cracked.subpass) {
3777 // add on the (0,0) coordinate
3778 spv::Id zero = builder.makeIntConstant(0);
3779 std::vector<spv::Id> comps;
3780 comps.push_back(zero);
3781 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06003782 spv::IdImmediate coord = { true,
3783 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
3784 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07003785 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003786 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3787 operands.push_back(imageOperands);
3788 spv::IdImmediate imageOperand = { true, *(opIt++) };
3789 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07003790 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003791 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3792 builder.setPrecision(result, precision);
3793 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003794 }
3795
John Kessenich149afc32018-08-14 13:31:43 -06003796 spv::IdImmediate coord = { true, *(opIt++) };
3797 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08003798#ifdef AMD_EXTENSIONS
3799 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3800#else
John Kessenich56bab042015-09-16 10:54:31 -06003801 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003802#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05003803 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07003804 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05003805 mask = mask | spv::ImageOperandsSampleMask;
3806 }
Rex Xu129799a2017-07-05 17:23:28 +08003807#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05003808 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08003809 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3810 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05003811 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07003812 }
Jeff Bolz36831c92018-09-05 10:11:41 -05003813#endif
3814 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
3815 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
3816 if (mask) {
3817 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
3818 operands.push_back(imageOperands);
3819 }
3820 if (mask & spv::ImageOperandsSampleMask) {
3821 spv::IdImmediate imageOperand = { true, *opIt++ };
3822 operands.push_back(imageOperand);
3823 }
3824#ifdef AMD_EXTENSIONS
3825 if (mask & spv::ImageOperandsLodMask) {
3826 spv::IdImmediate imageOperand = { true, *opIt++ };
3827 operands.push_back(imageOperand);
3828 }
3829#endif
3830 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
3831 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
3832 operands.push_back(imageOperand);
3833 }
3834
John Kessenich149afc32018-08-14 13:31:43 -06003835 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07003836 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003837
John Kessenich149afc32018-08-14 13:31:43 -06003838 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07003839 builder.setPrecision(result[0], precision);
3840
3841 // If needed, add a conversion constructor to the proper size.
3842 if (components != node->getType().getVectorSize())
3843 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3844
3845 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003846#ifdef AMD_EXTENSIONS
3847 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3848#else
John Kessenich56bab042015-09-16 10:54:31 -06003849 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003850#endif
Rex Xu129799a2017-07-05 17:23:28 +08003851
Jeff Bolz36831c92018-09-05 10:11:41 -05003852 // Push the texel value before the operands
3853#ifdef AMD_EXTENSIONS
3854 if (sampler.ms || cracked.lod) {
3855#else
3856 if (sampler.ms) {
3857#endif
John Kessenich149afc32018-08-14 13:31:43 -06003858 spv::IdImmediate texel = { true, *(opIt + 1) };
3859 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06003860 } else {
3861 spv::IdImmediate texel = { true, *opIt };
3862 operands.push_back(texel);
3863 }
Jeff Bolz36831c92018-09-05 10:11:41 -05003864
3865 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
3866 if (sampler.ms) {
3867 mask = mask | spv::ImageOperandsSampleMask;
3868 }
3869#ifdef AMD_EXTENSIONS
3870 if (cracked.lod) {
3871 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3872 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3873 mask = mask | spv::ImageOperandsLodMask;
3874 }
3875#endif
3876 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
3877 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
3878 if (mask) {
3879 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
3880 operands.push_back(imageOperands);
3881 }
3882 if (mask & spv::ImageOperandsSampleMask) {
3883 spv::IdImmediate imageOperand = { true, *opIt++ };
3884 operands.push_back(imageOperand);
3885 }
3886#ifdef AMD_EXTENSIONS
3887 if (mask & spv::ImageOperandsLodMask) {
3888 spv::IdImmediate imageOperand = { true, *opIt++ };
3889 operands.push_back(imageOperand);
3890 }
3891#endif
3892 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
3893 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
3894 operands.push_back(imageOperand);
3895 }
3896
John Kessenich56bab042015-09-16 10:54:31 -06003897 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06003898 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07003899 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003900 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003901#ifdef AMD_EXTENSIONS
3902 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3903#else
Rex Xu5eafa472016-02-19 22:24:03 +08003904 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003905#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003906 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06003907 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08003908 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3909
Jeff Bolz36831c92018-09-05 10:11:41 -05003910 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08003911 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05003912 mask = mask | spv::ImageOperandsSampleMask;
3913 }
Rex Xu129799a2017-07-05 17:23:28 +08003914#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05003915 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08003916 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3917 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3918
Jeff Bolz36831c92018-09-05 10:11:41 -05003919 mask = mask | spv::ImageOperandsLodMask;
3920 }
3921#endif
3922 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
3923 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
3924 if (mask) {
3925 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06003926 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05003927 }
3928 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06003929 spv::IdImmediate imageOperand = { true, *opIt++ };
3930 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05003931 }
3932#ifdef AMD_EXTENSIONS
3933 if (mask & spv::ImageOperandsLodMask) {
3934 spv::IdImmediate imageOperand = { true, *opIt++ };
3935 operands.push_back(imageOperand);
3936 }
Rex Xu129799a2017-07-05 17:23:28 +08003937#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05003938 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
3939 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
3940 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08003941 }
3942
3943 // Create the return type that was a special structure
3944 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003945 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003946 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3947 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3948
3949 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3950
3951 // Decode the return type
3952 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3953 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003954 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003955 // Process image atomic operations
3956
3957 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3958 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06003959 // For non-MS, the sample value should be 0
3960 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
3961 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06003962
Jeff Bolz36831c92018-09-05 10:11:41 -05003963 spv::Id resultTypeId;
3964 // imageAtomicStore has a void return type so base the pointer type on
3965 // the type of the value operand.
3966 if (node->getOp() == glslang::EOpImageAtomicStore) {
3967 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
3968 } else {
3969 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
3970 }
John Kessenich56bab042015-09-16 10:54:31 -06003971 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003972
3973 std::vector<spv::Id> operands;
3974 operands.push_back(pointer);
3975 for (; opIt != arguments.end(); ++opIt)
3976 operands.push_back(*opIt);
3977
John Kessenich8c8505c2016-07-26 12:50:38 -06003978 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003979 }
3980 }
3981
amhagan05506bb2017-06-13 16:53:02 -04003982#ifdef AMD_EXTENSIONS
3983 // Check for fragment mask functions other than queries
3984 if (cracked.fragMask) {
3985 assert(sampler.ms);
3986
3987 auto opIt = arguments.begin();
3988 std::vector<spv::Id> operands;
3989
3990 // Extract the image if necessary
3991 if (builder.isSampledImage(params.sampler))
3992 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3993
3994 operands.push_back(params.sampler);
3995 ++opIt;
3996
3997 if (sampler.isSubpass()) {
3998 // add on the (0,0) coordinate
3999 spv::Id zero = builder.makeIntConstant(0);
4000 std::vector<spv::Id> comps;
4001 comps.push_back(zero);
4002 comps.push_back(zero);
4003 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
4004 }
4005
4006 for (; opIt != arguments.end(); ++opIt)
4007 operands.push_back(*opIt);
4008
4009 spv::Op fragMaskOp = spv::OpNop;
4010 if (node->getOp() == glslang::EOpFragmentMaskFetch)
4011 fragMaskOp = spv::OpFragmentMaskFetchAMD;
4012 else if (node->getOp() == glslang::EOpFragmentFetch)
4013 fragMaskOp = spv::OpFragmentFetchAMD;
4014
4015 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
4016 builder.addCapability(spv::CapabilityFragmentMaskAMD);
4017 return builder.createOp(fragMaskOp, resultType(), operands);
4018 }
4019#endif
4020
Rex Xufc618912015-09-09 16:42:49 +08004021 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004022 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08004023 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4024
John Kessenichfc51d282015-08-19 13:34:18 -06004025 // check for bias argument
4026 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004027#ifdef AMD_EXTENSIONS
4028 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4029#else
Rex Xu71519fe2015-11-11 15:35:47 +08004030 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004031#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004032 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004033#ifdef AMD_EXTENSIONS
4034 if (cracked.gather)
4035 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004036
4037 if (f16ShadowCompare)
4038 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004039#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004040 if (cracked.offset)
4041 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004042#ifdef AMD_EXTENSIONS
4043 else if (cracked.offsets)
4044 ++nonBiasArgCount;
4045#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004046 if (cracked.grad)
4047 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004048 if (cracked.lodClamp)
4049 ++nonBiasArgCount;
4050 if (sparse)
4051 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004052
4053 if ((int)arguments.size() > nonBiasArgCount)
4054 bias = true;
4055 }
4056
John Kessenicha5c33d62016-06-02 23:45:21 -06004057 // See if the sampler param should really be just the SPV image part
4058 if (cracked.fetch) {
4059 // a fetch needs to have the image extracted first
4060 if (builder.isSampledImage(params.sampler))
4061 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4062 }
4063
Rex Xu225e0fc2016-11-17 17:47:59 +08004064#ifdef AMD_EXTENSIONS
4065 if (cracked.gather) {
4066 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4067 if (bias || cracked.lod ||
4068 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4069 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004070 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004071 }
4072 }
4073#endif
4074
John Kessenichfc51d282015-08-19 13:34:18 -06004075 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004076
John Kessenichfc51d282015-08-19 13:34:18 -06004077 params.coords = arguments[1];
4078 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004079 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004080
4081 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004082#ifdef AMD_EXTENSIONS
4083 if (cubeCompare || f16ShadowCompare) {
4084#else
Rex Xu48edadf2015-12-31 16:11:41 +08004085 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004086#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004087 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004088 ++extraArgs;
4089 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004090 params.Dref = arguments[2];
4091 ++extraArgs;
4092 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004093 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004094 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004095 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004096 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004097 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004098 dRefComp = builder.getNumComponents(params.coords) - 1;
4099 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004100 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4101 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004102
4103 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004104 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004105 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004106 ++extraArgs;
Chao Chenbeae2252018-09-19 11:40:45 -07004107 } else if (glslangIntermediate->getStage() != EShLangFragment
4108#ifdef NV_EXTENSIONS
4109 // NV_compute_shader_derivatives layout qualifiers allow for implicit LODs
4110 && !(glslangIntermediate->getStage() == EShLangCompute &&
4111 (glslangIntermediate->getLayoutDerivativeModeNone() != glslang::LayoutDerivativeNone))
4112#endif
4113 ) {
John Kessenich019f08f2016-02-15 15:40:42 -07004114 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4115 noImplicitLod = true;
4116 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004117
4118 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004119 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004120 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004121 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004122 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004123
4124 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004125 if (cracked.grad) {
4126 params.gradX = arguments[2 + extraArgs];
4127 params.gradY = arguments[3 + extraArgs];
4128 extraArgs += 2;
4129 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004130
4131 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004132 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004133 params.offset = arguments[2 + extraArgs];
4134 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004135 } else if (cracked.offsets) {
4136 params.offsets = arguments[2 + extraArgs];
4137 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004138 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004139
4140 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004141 if (cracked.lodClamp) {
4142 params.lodClamp = arguments[2 + extraArgs];
4143 ++extraArgs;
4144 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004145
4146 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004147 if (sparse) {
4148 params.texelOut = arguments[2 + extraArgs];
4149 ++extraArgs;
4150 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004151
John Kessenich76d4dfc2016-06-16 12:43:23 -06004152 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004153 if (cracked.gather && ! sampler.shadow) {
4154 // default component is 0, if missing, otherwise an argument
4155 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004156 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004157 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004158 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004159 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004160 }
4161
4162 // bias
4163 if (bias) {
4164 params.bias = arguments[2 + extraArgs];
4165 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004166 }
John Kessenichfc51d282015-08-19 13:34:18 -06004167
John Kessenich65336482016-06-16 14:06:26 -06004168 // projective component (might not to move)
4169 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4170 // are divided by the last component of P."
4171 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4172 // unused components will appear after all used components."
4173 if (cracked.proj) {
4174 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4175 int projTargetComp;
4176 switch (sampler.dim) {
4177 case glslang::Esd1D: projTargetComp = 1; break;
4178 case glslang::Esd2D: projTargetComp = 2; break;
4179 case glslang::EsdRect: projTargetComp = 2; break;
4180 default: projTargetComp = projSourceComp; break;
4181 }
4182 // copy the projective coordinate if we have to
4183 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004184 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004185 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4186 projSourceComp);
4187 params.coords = builder.createCompositeInsert(projComp, params.coords,
4188 builder.getTypeId(params.coords), projTargetComp);
4189 }
4190 }
4191
Jeff Bolz36831c92018-09-05 10:11:41 -05004192 // nonprivate
4193 if (imageType.getQualifier().nonprivate) {
4194 params.nonprivate = true;
4195 }
4196
4197 // volatile
4198 if (imageType.getQualifier().volatil) {
4199 params.volatil = true;
4200 }
4201
St0fFa1184dd2018-04-09 21:08:14 +02004202 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004203 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004204 );
LoopDawg4425f242018-02-18 11:40:01 -07004205
4206 if (components != node->getType().getVectorSize())
4207 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4208
4209 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004210}
4211
4212spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4213{
4214 // Grab the function's pointer from the previously created function
4215 spv::Function* function = functionMap[node->getName().c_str()];
4216 if (! function)
4217 return 0;
4218
4219 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4220 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4221
4222 // See comments in makeFunctions() for details about the semantics for parameter passing.
4223 //
4224 // These imply we need a four step process:
4225 // 1. Evaluate the arguments
4226 // 2. Allocate and make copies of in, out, and inout arguments
4227 // 3. Make the call
4228 // 4. Copy back the results
4229
John Kessenichd3ed90b2018-05-04 11:43:03 -06004230 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004231 std::vector<spv::Builder::AccessChain> lValues;
4232 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004233 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004234 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004235 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004236 // build l-value
4237 builder.clearAccessChain();
4238 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004239 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004240 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004241 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004242 // save l-value
4243 lValues.push_back(builder.getAccessChain());
4244 } else {
4245 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004246 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004247 }
4248 }
4249
4250 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4251 // copy the original into that space.
4252 //
4253 // Also, build up the list of actual arguments to pass in for the call
4254 int lValueCount = 0;
4255 int rValueCount = 0;
4256 std::vector<spv::Id> spvArgs;
4257 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4258 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004259 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004260 builder.setAccessChain(lValues[lValueCount]);
4261 arg = builder.accessChainGetLValue();
4262 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004263 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004264 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004265 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004266 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4267 // need to copy the input into output space
4268 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004269 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004270 builder.clearAccessChain();
4271 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004272 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004273 }
4274 ++lValueCount;
4275 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004276 // process r-value, which involves a copy for a type mismatch
4277 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4278 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4279 builder.clearAccessChain();
4280 builder.setAccessChainLValue(argCopy);
4281 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4282 arg = builder.createLoad(argCopy);
4283 } else
4284 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004285 ++rValueCount;
4286 }
4287 spvArgs.push_back(arg);
4288 }
4289
4290 // 3. Make the call.
4291 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004292 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004293
4294 // 4. Copy back out an "out" arguments.
4295 lValueCount = 0;
4296 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004297 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004298 ++lValueCount;
4299 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004300 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4301 spv::Id copy = builder.createLoad(spvArgs[a]);
4302 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004303 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004304 }
4305 ++lValueCount;
4306 }
4307 }
4308
4309 return result;
4310}
4311
4312// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004313spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004314 spv::Id typeId, spv::Id left, spv::Id right,
4315 glslang::TBasicType typeProxy, bool reduceComparison)
4316{
John Kessenich66011cb2018-03-06 16:12:04 -07004317 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4318 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004319 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004320
4321 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004322 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004323 bool comparison = false;
4324
4325 switch (op) {
4326 case glslang::EOpAdd:
4327 case glslang::EOpAddAssign:
4328 if (isFloat)
4329 binOp = spv::OpFAdd;
4330 else
4331 binOp = spv::OpIAdd;
4332 break;
4333 case glslang::EOpSub:
4334 case glslang::EOpSubAssign:
4335 if (isFloat)
4336 binOp = spv::OpFSub;
4337 else
4338 binOp = spv::OpISub;
4339 break;
4340 case glslang::EOpMul:
4341 case glslang::EOpMulAssign:
4342 if (isFloat)
4343 binOp = spv::OpFMul;
4344 else
4345 binOp = spv::OpIMul;
4346 break;
4347 case glslang::EOpVectorTimesScalar:
4348 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004349 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004350 if (builder.isVector(right))
4351 std::swap(left, right);
4352 assert(builder.isScalar(right));
4353 needMatchingVectors = false;
4354 binOp = spv::OpVectorTimesScalar;
4355 } else
4356 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004357 break;
4358 case glslang::EOpVectorTimesMatrix:
4359 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004360 binOp = spv::OpVectorTimesMatrix;
4361 break;
4362 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004363 binOp = spv::OpMatrixTimesVector;
4364 break;
4365 case glslang::EOpMatrixTimesScalar:
4366 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004367 binOp = spv::OpMatrixTimesScalar;
4368 break;
4369 case glslang::EOpMatrixTimesMatrix:
4370 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004371 binOp = spv::OpMatrixTimesMatrix;
4372 break;
4373 case glslang::EOpOuterProduct:
4374 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004375 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004376 break;
4377
4378 case glslang::EOpDiv:
4379 case glslang::EOpDivAssign:
4380 if (isFloat)
4381 binOp = spv::OpFDiv;
4382 else if (isUnsigned)
4383 binOp = spv::OpUDiv;
4384 else
4385 binOp = spv::OpSDiv;
4386 break;
4387 case glslang::EOpMod:
4388 case glslang::EOpModAssign:
4389 if (isFloat)
4390 binOp = spv::OpFMod;
4391 else if (isUnsigned)
4392 binOp = spv::OpUMod;
4393 else
4394 binOp = spv::OpSMod;
4395 break;
4396 case glslang::EOpRightShift:
4397 case glslang::EOpRightShiftAssign:
4398 if (isUnsigned)
4399 binOp = spv::OpShiftRightLogical;
4400 else
4401 binOp = spv::OpShiftRightArithmetic;
4402 break;
4403 case glslang::EOpLeftShift:
4404 case glslang::EOpLeftShiftAssign:
4405 binOp = spv::OpShiftLeftLogical;
4406 break;
4407 case glslang::EOpAnd:
4408 case glslang::EOpAndAssign:
4409 binOp = spv::OpBitwiseAnd;
4410 break;
4411 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004412 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004413 binOp = spv::OpLogicalAnd;
4414 break;
4415 case glslang::EOpInclusiveOr:
4416 case glslang::EOpInclusiveOrAssign:
4417 binOp = spv::OpBitwiseOr;
4418 break;
4419 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004420 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004421 binOp = spv::OpLogicalOr;
4422 break;
4423 case glslang::EOpExclusiveOr:
4424 case glslang::EOpExclusiveOrAssign:
4425 binOp = spv::OpBitwiseXor;
4426 break;
4427 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004428 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004429 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004430 break;
4431
4432 case glslang::EOpLessThan:
4433 case glslang::EOpGreaterThan:
4434 case glslang::EOpLessThanEqual:
4435 case glslang::EOpGreaterThanEqual:
4436 case glslang::EOpEqual:
4437 case glslang::EOpNotEqual:
4438 case glslang::EOpVectorEqual:
4439 case glslang::EOpVectorNotEqual:
4440 comparison = true;
4441 break;
4442 default:
4443 break;
4444 }
4445
John Kessenich7c1aa102015-10-15 13:29:11 -06004446 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004447 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004448 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004449 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004450 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004451
4452 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004453 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004454 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004455
qining25262b32016-05-06 17:25:16 -04004456 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004457 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004458 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004459 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004460 }
4461
4462 if (! comparison)
4463 return 0;
4464
John Kessenich7c1aa102015-10-15 13:29:11 -06004465 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004466
John Kessenich4583b612016-08-07 19:14:22 -06004467 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004468 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4469 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004470 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004471 return result;
4472 }
John Kessenich140f3df2015-06-26 16:58:36 -06004473
4474 switch (op) {
4475 case glslang::EOpLessThan:
4476 if (isFloat)
4477 binOp = spv::OpFOrdLessThan;
4478 else if (isUnsigned)
4479 binOp = spv::OpULessThan;
4480 else
4481 binOp = spv::OpSLessThan;
4482 break;
4483 case glslang::EOpGreaterThan:
4484 if (isFloat)
4485 binOp = spv::OpFOrdGreaterThan;
4486 else if (isUnsigned)
4487 binOp = spv::OpUGreaterThan;
4488 else
4489 binOp = spv::OpSGreaterThan;
4490 break;
4491 case glslang::EOpLessThanEqual:
4492 if (isFloat)
4493 binOp = spv::OpFOrdLessThanEqual;
4494 else if (isUnsigned)
4495 binOp = spv::OpULessThanEqual;
4496 else
4497 binOp = spv::OpSLessThanEqual;
4498 break;
4499 case glslang::EOpGreaterThanEqual:
4500 if (isFloat)
4501 binOp = spv::OpFOrdGreaterThanEqual;
4502 else if (isUnsigned)
4503 binOp = spv::OpUGreaterThanEqual;
4504 else
4505 binOp = spv::OpSGreaterThanEqual;
4506 break;
4507 case glslang::EOpEqual:
4508 case glslang::EOpVectorEqual:
4509 if (isFloat)
4510 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004511 else if (isBool)
4512 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004513 else
4514 binOp = spv::OpIEqual;
4515 break;
4516 case glslang::EOpNotEqual:
4517 case glslang::EOpVectorNotEqual:
4518 if (isFloat)
4519 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004520 else if (isBool)
4521 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004522 else
4523 binOp = spv::OpINotEqual;
4524 break;
4525 default:
4526 break;
4527 }
4528
qining25262b32016-05-06 17:25:16 -04004529 if (binOp != spv::OpNop) {
4530 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004531 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004532 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004533 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004534 }
John Kessenich140f3df2015-06-26 16:58:36 -06004535
4536 return 0;
4537}
4538
John Kessenich04bb8a02015-12-12 12:28:14 -07004539//
4540// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4541// These can be any of:
4542//
4543// matrix * scalar
4544// scalar * matrix
4545// matrix * matrix linear algebraic
4546// matrix * vector
4547// vector * matrix
4548// matrix * matrix componentwise
4549// matrix op matrix op in {+, -, /}
4550// matrix op scalar op in {+, -, /}
4551// scalar op matrix op in {+, -, /}
4552//
John Kessenichead86222018-03-28 18:01:20 -06004553spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4554 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004555{
4556 bool firstClass = true;
4557
4558 // First, handle first-class matrix operations (* and matrix/scalar)
4559 switch (op) {
4560 case spv::OpFDiv:
4561 if (builder.isMatrix(left) && builder.isScalar(right)) {
4562 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004563 spv::Id resultType = builder.getTypeId(right);
4564 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004565 op = spv::OpMatrixTimesScalar;
4566 } else
4567 firstClass = false;
4568 break;
4569 case spv::OpMatrixTimesScalar:
4570 if (builder.isMatrix(right))
4571 std::swap(left, right);
4572 assert(builder.isScalar(right));
4573 break;
4574 case spv::OpVectorTimesMatrix:
4575 assert(builder.isVector(left));
4576 assert(builder.isMatrix(right));
4577 break;
4578 case spv::OpMatrixTimesVector:
4579 assert(builder.isMatrix(left));
4580 assert(builder.isVector(right));
4581 break;
4582 case spv::OpMatrixTimesMatrix:
4583 assert(builder.isMatrix(left));
4584 assert(builder.isMatrix(right));
4585 break;
4586 default:
4587 firstClass = false;
4588 break;
4589 }
4590
qining25262b32016-05-06 17:25:16 -04004591 if (firstClass) {
4592 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004593 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004594 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004595 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004596 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004597
LoopDawg592860c2016-06-09 08:57:35 -06004598 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004599 // The result type of all of them is the same type as the (a) matrix operand.
4600 // The algorithm is to:
4601 // - break the matrix(es) into vectors
4602 // - smear any scalar to a vector
4603 // - do vector operations
4604 // - make a matrix out the vector results
4605 switch (op) {
4606 case spv::OpFAdd:
4607 case spv::OpFSub:
4608 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004609 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004610 case spv::OpFMul:
4611 {
4612 // one time set up...
4613 bool leftMat = builder.isMatrix(left);
4614 bool rightMat = builder.isMatrix(right);
4615 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4616 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4617 spv::Id scalarType = builder.getScalarTypeId(typeId);
4618 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4619 std::vector<spv::Id> results;
4620 spv::Id smearVec = spv::NoResult;
4621 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004622 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004623 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004624 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004625
4626 // do each vector op
4627 for (unsigned int c = 0; c < numCols; ++c) {
4628 std::vector<unsigned int> indexes;
4629 indexes.push_back(c);
4630 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4631 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004632 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004633 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004634 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004635 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004636 }
4637
4638 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004639 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004640 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004641 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004642 }
4643 default:
4644 assert(0);
4645 return spv::NoResult;
4646 }
4647}
4648
John Kessenichead86222018-03-28 18:01:20 -06004649spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4650 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004651{
4652 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004653 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004654 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004655 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4656 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004657
4658 switch (op) {
4659 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004660 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004661 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004662 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004663 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004664 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004665 unaryOp = spv::OpSNegate;
4666 break;
4667
4668 case glslang::EOpLogicalNot:
4669 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004670 unaryOp = spv::OpLogicalNot;
4671 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004672 case glslang::EOpBitwiseNot:
4673 unaryOp = spv::OpNot;
4674 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004675
John Kessenich140f3df2015-06-26 16:58:36 -06004676 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004677 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004678 break;
4679 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004680 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004681 break;
4682 case glslang::EOpTranspose:
4683 unaryOp = spv::OpTranspose;
4684 break;
4685
4686 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004687 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004688 break;
4689 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004690 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004691 break;
4692 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004693 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004694 break;
4695 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004696 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004697 break;
4698 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004699 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004700 break;
4701 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004702 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004703 break;
4704 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004705 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004706 break;
4707 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004708 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004709 break;
4710
4711 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004712 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004713 break;
4714 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004715 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004716 break;
4717 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004718 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004719 break;
4720 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004721 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004722 break;
4723 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004724 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004725 break;
4726 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004727 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004728 break;
4729
4730 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004731 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004732 break;
4733 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004734 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004735 break;
4736
4737 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004738 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004739 break;
4740 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004741 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004742 break;
4743 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004744 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004745 break;
4746 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004747 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004748 break;
4749 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004750 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004751 break;
4752 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004753 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004754 break;
4755
4756 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004757 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004758 break;
4759 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004760 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004761 break;
4762 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004763 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004764 break;
4765 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004766 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004767 break;
4768 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004769 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004770 break;
4771 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004772 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004773 break;
4774
4775 case glslang::EOpIsNan:
4776 unaryOp = spv::OpIsNan;
4777 break;
4778 case glslang::EOpIsInf:
4779 unaryOp = spv::OpIsInf;
4780 break;
LoopDawg592860c2016-06-09 08:57:35 -06004781 case glslang::EOpIsFinite:
4782 unaryOp = spv::OpIsFinite;
4783 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004784
Rex Xucbc426e2015-12-15 16:03:10 +08004785 case glslang::EOpFloatBitsToInt:
4786 case glslang::EOpFloatBitsToUint:
4787 case glslang::EOpIntBitsToFloat:
4788 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004789 case glslang::EOpDoubleBitsToInt64:
4790 case glslang::EOpDoubleBitsToUint64:
4791 case glslang::EOpInt64BitsToDouble:
4792 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004793 case glslang::EOpFloat16BitsToInt16:
4794 case glslang::EOpFloat16BitsToUint16:
4795 case glslang::EOpInt16BitsToFloat16:
4796 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08004797 unaryOp = spv::OpBitcast;
4798 break;
4799
John Kessenich140f3df2015-06-26 16:58:36 -06004800 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004801 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004802 break;
4803 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004804 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004805 break;
4806 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004807 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004808 break;
4809 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004810 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004811 break;
4812 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004813 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004814 break;
4815 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004816 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004817 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004818 case glslang::EOpPackSnorm4x8:
4819 libCall = spv::GLSLstd450PackSnorm4x8;
4820 break;
4821 case glslang::EOpUnpackSnorm4x8:
4822 libCall = spv::GLSLstd450UnpackSnorm4x8;
4823 break;
4824 case glslang::EOpPackUnorm4x8:
4825 libCall = spv::GLSLstd450PackUnorm4x8;
4826 break;
4827 case glslang::EOpUnpackUnorm4x8:
4828 libCall = spv::GLSLstd450UnpackUnorm4x8;
4829 break;
4830 case glslang::EOpPackDouble2x32:
4831 libCall = spv::GLSLstd450PackDouble2x32;
4832 break;
4833 case glslang::EOpUnpackDouble2x32:
4834 libCall = spv::GLSLstd450UnpackDouble2x32;
4835 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004836
Rex Xu8ff43de2016-04-22 16:51:45 +08004837 case glslang::EOpPackInt2x32:
4838 case glslang::EOpUnpackInt2x32:
4839 case glslang::EOpPackUint2x32:
4840 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07004841 case glslang::EOpPack16:
4842 case glslang::EOpPack32:
4843 case glslang::EOpPack64:
4844 case glslang::EOpUnpack32:
4845 case glslang::EOpUnpack16:
4846 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08004847 case glslang::EOpPackInt2x16:
4848 case glslang::EOpUnpackInt2x16:
4849 case glslang::EOpPackUint2x16:
4850 case glslang::EOpUnpackUint2x16:
4851 case glslang::EOpPackInt4x16:
4852 case glslang::EOpUnpackInt4x16:
4853 case glslang::EOpPackUint4x16:
4854 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004855 case glslang::EOpPackFloat2x16:
4856 case glslang::EOpUnpackFloat2x16:
4857 unaryOp = spv::OpBitcast;
4858 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004859
John Kessenich140f3df2015-06-26 16:58:36 -06004860 case glslang::EOpDPdx:
4861 unaryOp = spv::OpDPdx;
4862 break;
4863 case glslang::EOpDPdy:
4864 unaryOp = spv::OpDPdy;
4865 break;
4866 case glslang::EOpFwidth:
4867 unaryOp = spv::OpFwidth;
4868 break;
4869 case glslang::EOpDPdxFine:
4870 unaryOp = spv::OpDPdxFine;
4871 break;
4872 case glslang::EOpDPdyFine:
4873 unaryOp = spv::OpDPdyFine;
4874 break;
4875 case glslang::EOpFwidthFine:
4876 unaryOp = spv::OpFwidthFine;
4877 break;
4878 case glslang::EOpDPdxCoarse:
4879 unaryOp = spv::OpDPdxCoarse;
4880 break;
4881 case glslang::EOpDPdyCoarse:
4882 unaryOp = spv::OpDPdyCoarse;
4883 break;
4884 case glslang::EOpFwidthCoarse:
4885 unaryOp = spv::OpFwidthCoarse;
4886 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004887 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08004888#ifdef AMD_EXTENSIONS
4889 if (typeProxy == glslang::EbtFloat16)
4890 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
4891#endif
Rex Xu7a26c172015-12-08 17:12:09 +08004892 libCall = spv::GLSLstd450InterpolateAtCentroid;
4893 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004894 case glslang::EOpAny:
4895 unaryOp = spv::OpAny;
4896 break;
4897 case glslang::EOpAll:
4898 unaryOp = spv::OpAll;
4899 break;
4900
4901 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004902 if (isFloat)
4903 libCall = spv::GLSLstd450FAbs;
4904 else
4905 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004906 break;
4907 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004908 if (isFloat)
4909 libCall = spv::GLSLstd450FSign;
4910 else
4911 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004912 break;
4913
John Kessenichfc51d282015-08-19 13:34:18 -06004914 case glslang::EOpAtomicCounterIncrement:
4915 case glslang::EOpAtomicCounterDecrement:
4916 case glslang::EOpAtomicCounter:
4917 {
4918 // Handle all of the atomics in one place, in createAtomicOperation()
4919 std::vector<spv::Id> operands;
4920 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06004921 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004922 }
4923
John Kessenichfc51d282015-08-19 13:34:18 -06004924 case glslang::EOpBitFieldReverse:
4925 unaryOp = spv::OpBitReverse;
4926 break;
4927 case glslang::EOpBitCount:
4928 unaryOp = spv::OpBitCount;
4929 break;
4930 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004931 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004932 break;
4933 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004934 if (isUnsigned)
4935 libCall = spv::GLSLstd450FindUMsb;
4936 else
4937 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004938 break;
4939
Rex Xu574ab042016-04-14 16:53:07 +08004940 case glslang::EOpBallot:
4941 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004942 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004943 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004944 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004945#ifdef AMD_EXTENSIONS
4946 case glslang::EOpMinInvocations:
4947 case glslang::EOpMaxInvocations:
4948 case glslang::EOpAddInvocations:
4949 case glslang::EOpMinInvocationsNonUniform:
4950 case glslang::EOpMaxInvocationsNonUniform:
4951 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004952 case glslang::EOpMinInvocationsInclusiveScan:
4953 case glslang::EOpMaxInvocationsInclusiveScan:
4954 case glslang::EOpAddInvocationsInclusiveScan:
4955 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4956 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4957 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4958 case glslang::EOpMinInvocationsExclusiveScan:
4959 case glslang::EOpMaxInvocationsExclusiveScan:
4960 case glslang::EOpAddInvocationsExclusiveScan:
4961 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4962 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4963 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004964#endif
Rex Xu51596642016-09-21 18:56:12 +08004965 {
4966 std::vector<spv::Id> operands;
4967 operands.push_back(operand);
4968 return createInvocationsOperation(op, typeId, operands, typeProxy);
4969 }
John Kessenich66011cb2018-03-06 16:12:04 -07004970 case glslang::EOpSubgroupAll:
4971 case glslang::EOpSubgroupAny:
4972 case glslang::EOpSubgroupAllEqual:
4973 case glslang::EOpSubgroupBroadcastFirst:
4974 case glslang::EOpSubgroupBallot:
4975 case glslang::EOpSubgroupInverseBallot:
4976 case glslang::EOpSubgroupBallotBitCount:
4977 case glslang::EOpSubgroupBallotInclusiveBitCount:
4978 case glslang::EOpSubgroupBallotExclusiveBitCount:
4979 case glslang::EOpSubgroupBallotFindLSB:
4980 case glslang::EOpSubgroupBallotFindMSB:
4981 case glslang::EOpSubgroupAdd:
4982 case glslang::EOpSubgroupMul:
4983 case glslang::EOpSubgroupMin:
4984 case glslang::EOpSubgroupMax:
4985 case glslang::EOpSubgroupAnd:
4986 case glslang::EOpSubgroupOr:
4987 case glslang::EOpSubgroupXor:
4988 case glslang::EOpSubgroupInclusiveAdd:
4989 case glslang::EOpSubgroupInclusiveMul:
4990 case glslang::EOpSubgroupInclusiveMin:
4991 case glslang::EOpSubgroupInclusiveMax:
4992 case glslang::EOpSubgroupInclusiveAnd:
4993 case glslang::EOpSubgroupInclusiveOr:
4994 case glslang::EOpSubgroupInclusiveXor:
4995 case glslang::EOpSubgroupExclusiveAdd:
4996 case glslang::EOpSubgroupExclusiveMul:
4997 case glslang::EOpSubgroupExclusiveMin:
4998 case glslang::EOpSubgroupExclusiveMax:
4999 case glslang::EOpSubgroupExclusiveAnd:
5000 case glslang::EOpSubgroupExclusiveOr:
5001 case glslang::EOpSubgroupExclusiveXor:
5002 case glslang::EOpSubgroupQuadSwapHorizontal:
5003 case glslang::EOpSubgroupQuadSwapVertical:
5004 case glslang::EOpSubgroupQuadSwapDiagonal: {
5005 std::vector<spv::Id> operands;
5006 operands.push_back(operand);
5007 return createSubgroupOperation(op, typeId, operands, typeProxy);
5008 }
Rex Xu9d93a232016-05-05 12:30:44 +08005009#ifdef AMD_EXTENSIONS
5010 case glslang::EOpMbcnt:
5011 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5012 libCall = spv::MbcntAMD;
5013 break;
5014
5015 case glslang::EOpCubeFaceIndex:
5016 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5017 libCall = spv::CubeFaceIndexAMD;
5018 break;
5019
5020 case glslang::EOpCubeFaceCoord:
5021 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
5022 libCall = spv::CubeFaceCoordAMD;
5023 break;
5024#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005025#ifdef NV_EXTENSIONS
5026 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005027 unaryOp = spv::OpGroupNonUniformPartitionNV;
5028 break;
5029#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005030 default:
5031 return 0;
5032 }
5033
5034 spv::Id id;
5035 if (libCall >= 0) {
5036 std::vector<spv::Id> args;
5037 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005038 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005039 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005040 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005041 }
John Kessenich140f3df2015-06-26 16:58:36 -06005042
John Kessenichead86222018-03-28 18:01:20 -06005043 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005044 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005045 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005046}
5047
John Kessenich7a53f762016-01-20 11:19:27 -07005048// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005049spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5050 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005051{
5052 // Handle unary operations vector by vector.
5053 // The result type is the same type as the original type.
5054 // The algorithm is to:
5055 // - break the matrix into vectors
5056 // - apply the operation to each vector
5057 // - make a matrix out the vector results
5058
5059 // get the types sorted out
5060 int numCols = builder.getNumColumns(operand);
5061 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005062 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5063 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005064 std::vector<spv::Id> results;
5065
5066 // do each vector op
5067 for (int c = 0; c < numCols; ++c) {
5068 std::vector<unsigned int> indexes;
5069 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005070 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5071 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005072 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005073 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005074 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005075 }
5076
5077 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005078 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005079 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005080 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005081}
5082
John Kessenichad7645f2018-06-04 19:11:25 -06005083// For converting integers where both the bitwidth and the signedness could
5084// change, but only do the width change here. The caller is still responsible
5085// for the signedness conversion.
5086spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005087{
John Kessenichad7645f2018-06-04 19:11:25 -06005088 // Get the result type width, based on the type to convert to.
5089 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005090 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005091 case glslang::EOpConvInt16ToUint8:
5092 case glslang::EOpConvIntToUint8:
5093 case glslang::EOpConvInt64ToUint8:
5094 case glslang::EOpConvUint16ToInt8:
5095 case glslang::EOpConvUintToInt8:
5096 case glslang::EOpConvUint64ToInt8:
5097 width = 8;
5098 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005099 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005100 case glslang::EOpConvIntToUint16:
5101 case glslang::EOpConvInt64ToUint16:
5102 case glslang::EOpConvUint8ToInt16:
5103 case glslang::EOpConvUintToInt16:
5104 case glslang::EOpConvUint64ToInt16:
5105 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005106 break;
5107 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005108 case glslang::EOpConvInt16ToUint:
5109 case glslang::EOpConvInt64ToUint:
5110 case glslang::EOpConvUint8ToInt:
5111 case glslang::EOpConvUint16ToInt:
5112 case glslang::EOpConvUint64ToInt:
5113 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005114 break;
5115 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005116 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005117 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005118 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005119 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005120 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005121 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005122 break;
5123
5124 default:
5125 assert(false && "Default missing");
5126 break;
5127 }
5128
John Kessenichad7645f2018-06-04 19:11:25 -06005129 // Get the conversion operation and result type,
5130 // based on the target width, but the source type.
5131 spv::Id type = spv::NoType;
5132 spv::Op convOp = spv::OpNop;
5133 switch(op) {
5134 case glslang::EOpConvInt8ToUint16:
5135 case glslang::EOpConvInt8ToUint:
5136 case glslang::EOpConvInt8ToUint64:
5137 case glslang::EOpConvInt16ToUint8:
5138 case glslang::EOpConvInt16ToUint:
5139 case glslang::EOpConvInt16ToUint64:
5140 case glslang::EOpConvIntToUint8:
5141 case glslang::EOpConvIntToUint16:
5142 case glslang::EOpConvIntToUint64:
5143 case glslang::EOpConvInt64ToUint8:
5144 case glslang::EOpConvInt64ToUint16:
5145 case glslang::EOpConvInt64ToUint:
5146 convOp = spv::OpSConvert;
5147 type = builder.makeIntType(width);
5148 break;
5149 default:
5150 convOp = spv::OpUConvert;
5151 type = builder.makeUintType(width);
5152 break;
5153 }
5154
John Kessenich66011cb2018-03-06 16:12:04 -07005155 if (vectorSize > 0)
5156 type = builder.makeVectorType(type, vectorSize);
5157
John Kessenichad7645f2018-06-04 19:11:25 -06005158 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005159}
5160
John Kessenichead86222018-03-28 18:01:20 -06005161spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5162 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005163{
5164 spv::Op convOp = spv::OpNop;
5165 spv::Id zero = 0;
5166 spv::Id one = 0;
5167
5168 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5169
5170 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005171 case glslang::EOpConvInt8ToBool:
5172 case glslang::EOpConvUint8ToBool:
5173 zero = builder.makeUint8Constant(0);
5174 zero = makeSmearedConstant(zero, vectorSize);
5175 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005176 case glslang::EOpConvInt16ToBool:
5177 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005178 zero = builder.makeUint16Constant(0);
5179 zero = makeSmearedConstant(zero, vectorSize);
5180 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5181 case glslang::EOpConvIntToBool:
5182 case glslang::EOpConvUintToBool:
5183 zero = builder.makeUintConstant(0);
5184 zero = makeSmearedConstant(zero, vectorSize);
5185 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5186 case glslang::EOpConvInt64ToBool:
5187 case glslang::EOpConvUint64ToBool:
5188 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005189 zero = makeSmearedConstant(zero, vectorSize);
5190 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5191
5192 case glslang::EOpConvFloatToBool:
5193 zero = builder.makeFloatConstant(0.0F);
5194 zero = makeSmearedConstant(zero, vectorSize);
5195 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5196
5197 case glslang::EOpConvDoubleToBool:
5198 zero = builder.makeDoubleConstant(0.0);
5199 zero = makeSmearedConstant(zero, vectorSize);
5200 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5201
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005202 case glslang::EOpConvFloat16ToBool:
5203 zero = builder.makeFloat16Constant(0.0F);
5204 zero = makeSmearedConstant(zero, vectorSize);
5205 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005206
John Kessenich140f3df2015-06-26 16:58:36 -06005207 case glslang::EOpConvBoolToFloat:
5208 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005209 zero = builder.makeFloatConstant(0.0F);
5210 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005211 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005212
John Kessenich140f3df2015-06-26 16:58:36 -06005213 case glslang::EOpConvBoolToDouble:
5214 convOp = spv::OpSelect;
5215 zero = builder.makeDoubleConstant(0.0);
5216 one = builder.makeDoubleConstant(1.0);
5217 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005218
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005219 case glslang::EOpConvBoolToFloat16:
5220 convOp = spv::OpSelect;
5221 zero = builder.makeFloat16Constant(0.0F);
5222 one = builder.makeFloat16Constant(1.0F);
5223 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005224
5225 case glslang::EOpConvBoolToInt8:
5226 zero = builder.makeInt8Constant(0);
5227 one = builder.makeInt8Constant(1);
5228 convOp = spv::OpSelect;
5229 break;
5230
5231 case glslang::EOpConvBoolToUint8:
5232 zero = builder.makeUint8Constant(0);
5233 one = builder.makeUint8Constant(1);
5234 convOp = spv::OpSelect;
5235 break;
5236
5237 case glslang::EOpConvBoolToInt16:
5238 zero = builder.makeInt16Constant(0);
5239 one = builder.makeInt16Constant(1);
5240 convOp = spv::OpSelect;
5241 break;
5242
5243 case glslang::EOpConvBoolToUint16:
5244 zero = builder.makeUint16Constant(0);
5245 one = builder.makeUint16Constant(1);
5246 convOp = spv::OpSelect;
5247 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005248
John Kessenich140f3df2015-06-26 16:58:36 -06005249 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005250 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005251 if (op == glslang::EOpConvBoolToInt64)
5252 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005253 else
5254 zero = builder.makeIntConstant(0);
5255
5256 if (op == glslang::EOpConvBoolToInt64)
5257 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005258 else
5259 one = builder.makeIntConstant(1);
5260
John Kessenich140f3df2015-06-26 16:58:36 -06005261 convOp = spv::OpSelect;
5262 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005263
John Kessenich140f3df2015-06-26 16:58:36 -06005264 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005265 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005266 if (op == glslang::EOpConvBoolToUint64)
5267 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005268 else
5269 zero = builder.makeUintConstant(0);
5270
5271 if (op == glslang::EOpConvBoolToUint64)
5272 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005273 else
5274 one = builder.makeUintConstant(1);
5275
John Kessenich140f3df2015-06-26 16:58:36 -06005276 convOp = spv::OpSelect;
5277 break;
5278
John Kessenich66011cb2018-03-06 16:12:04 -07005279 case glslang::EOpConvInt8ToFloat16:
5280 case glslang::EOpConvInt8ToFloat:
5281 case glslang::EOpConvInt8ToDouble:
5282 case glslang::EOpConvInt16ToFloat16:
5283 case glslang::EOpConvInt16ToFloat:
5284 case glslang::EOpConvInt16ToDouble:
5285 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005286 case glslang::EOpConvIntToFloat:
5287 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005288 case glslang::EOpConvInt64ToFloat:
5289 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005290 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005291 convOp = spv::OpConvertSToF;
5292 break;
5293
John Kessenich66011cb2018-03-06 16:12:04 -07005294 case glslang::EOpConvUint8ToFloat16:
5295 case glslang::EOpConvUint8ToFloat:
5296 case glslang::EOpConvUint8ToDouble:
5297 case glslang::EOpConvUint16ToFloat16:
5298 case glslang::EOpConvUint16ToFloat:
5299 case glslang::EOpConvUint16ToDouble:
5300 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005301 case glslang::EOpConvUintToFloat:
5302 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005303 case glslang::EOpConvUint64ToFloat:
5304 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005305 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005306 convOp = spv::OpConvertUToF;
5307 break;
5308
5309 case glslang::EOpConvDoubleToFloat:
5310 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005311 case glslang::EOpConvDoubleToFloat16:
5312 case glslang::EOpConvFloat16ToDouble:
5313 case glslang::EOpConvFloatToFloat16:
5314 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005315 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005316 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005317 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005318 break;
5319
John Kessenich66011cb2018-03-06 16:12:04 -07005320 case glslang::EOpConvFloat16ToInt8:
5321 case glslang::EOpConvFloatToInt8:
5322 case glslang::EOpConvDoubleToInt8:
5323 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005324 case glslang::EOpConvFloatToInt16:
5325 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005326 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005327 case glslang::EOpConvFloatToInt:
5328 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005329 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005330 case glslang::EOpConvFloatToInt64:
5331 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005332 convOp = spv::OpConvertFToS;
5333 break;
5334
John Kessenich66011cb2018-03-06 16:12:04 -07005335 case glslang::EOpConvUint8ToInt8:
5336 case glslang::EOpConvInt8ToUint8:
5337 case glslang::EOpConvUint16ToInt16:
5338 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005339 case glslang::EOpConvUintToInt:
5340 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005341 case glslang::EOpConvUint64ToInt64:
5342 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005343 if (builder.isInSpecConstCodeGenMode()) {
5344 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005345 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5346 zero = builder.makeUint8Constant(0);
5347 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005348 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005349 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5350 zero = builder.makeUint64Constant(0);
5351 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005352 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005353 }
qining189b2032016-04-12 23:16:20 -04005354 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005355 // Use OpIAdd, instead of OpBitcast to do the conversion when
5356 // generating for OpSpecConstantOp instruction.
5357 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5358 }
5359 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005360 convOp = spv::OpBitcast;
5361 break;
5362
John Kessenich66011cb2018-03-06 16:12:04 -07005363 case glslang::EOpConvFloat16ToUint8:
5364 case glslang::EOpConvFloatToUint8:
5365 case glslang::EOpConvDoubleToUint8:
5366 case glslang::EOpConvFloat16ToUint16:
5367 case glslang::EOpConvFloatToUint16:
5368 case glslang::EOpConvDoubleToUint16:
5369 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005370 case glslang::EOpConvFloatToUint:
5371 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005372 case glslang::EOpConvFloatToUint64:
5373 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005374 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005375 convOp = spv::OpConvertFToU;
5376 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005377
John Kessenich66011cb2018-03-06 16:12:04 -07005378 case glslang::EOpConvInt8ToInt16:
5379 case glslang::EOpConvInt8ToInt:
5380 case glslang::EOpConvInt8ToInt64:
5381 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005382 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005383 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005384 case glslang::EOpConvIntToInt8:
5385 case glslang::EOpConvIntToInt16:
5386 case glslang::EOpConvIntToInt64:
5387 case glslang::EOpConvInt64ToInt8:
5388 case glslang::EOpConvInt64ToInt16:
5389 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005390 convOp = spv::OpSConvert;
5391 break;
5392
John Kessenich66011cb2018-03-06 16:12:04 -07005393 case glslang::EOpConvUint8ToUint16:
5394 case glslang::EOpConvUint8ToUint:
5395 case glslang::EOpConvUint8ToUint64:
5396 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005397 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005398 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005399 case glslang::EOpConvUintToUint8:
5400 case glslang::EOpConvUintToUint16:
5401 case glslang::EOpConvUintToUint64:
5402 case glslang::EOpConvUint64ToUint8:
5403 case glslang::EOpConvUint64ToUint16:
5404 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005405 convOp = spv::OpUConvert;
5406 break;
5407
John Kessenich66011cb2018-03-06 16:12:04 -07005408 case glslang::EOpConvInt8ToUint16:
5409 case glslang::EOpConvInt8ToUint:
5410 case glslang::EOpConvInt8ToUint64:
5411 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005412 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005413 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005414 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005415 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005416 case glslang::EOpConvIntToUint64:
5417 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005418 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005419 case glslang::EOpConvInt64ToUint:
5420 case glslang::EOpConvUint8ToInt16:
5421 case glslang::EOpConvUint8ToInt:
5422 case glslang::EOpConvUint8ToInt64:
5423 case glslang::EOpConvUint16ToInt8:
5424 case glslang::EOpConvUint16ToInt:
5425 case glslang::EOpConvUint16ToInt64:
5426 case glslang::EOpConvUintToInt8:
5427 case glslang::EOpConvUintToInt16:
5428 case glslang::EOpConvUintToInt64:
5429 case glslang::EOpConvUint64ToInt8:
5430 case glslang::EOpConvUint64ToInt16:
5431 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005432 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005433 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005434
5435 if (builder.isInSpecConstCodeGenMode()) {
5436 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005437 switch(op) {
5438 case glslang::EOpConvInt16ToUint8:
5439 case glslang::EOpConvIntToUint8:
5440 case glslang::EOpConvInt64ToUint8:
5441 case glslang::EOpConvUint16ToInt8:
5442 case glslang::EOpConvUintToInt8:
5443 case glslang::EOpConvUint64ToInt8:
5444 zero = builder.makeUint8Constant(0);
5445 break;
5446 case glslang::EOpConvInt8ToUint16:
5447 case glslang::EOpConvIntToUint16:
5448 case glslang::EOpConvInt64ToUint16:
5449 case glslang::EOpConvUint8ToInt16:
5450 case glslang::EOpConvUintToInt16:
5451 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005452 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005453 break;
5454 case glslang::EOpConvInt8ToUint:
5455 case glslang::EOpConvInt16ToUint:
5456 case glslang::EOpConvInt64ToUint:
5457 case glslang::EOpConvUint8ToInt:
5458 case glslang::EOpConvUint16ToInt:
5459 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005460 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005461 break;
5462 case glslang::EOpConvInt8ToUint64:
5463 case glslang::EOpConvInt16ToUint64:
5464 case glslang::EOpConvIntToUint64:
5465 case glslang::EOpConvUint8ToInt64:
5466 case glslang::EOpConvUint16ToInt64:
5467 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005468 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005469 break;
5470 default:
5471 assert(false && "Default missing");
5472 break;
5473 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005474 zero = makeSmearedConstant(zero, vectorSize);
5475 // Use OpIAdd, instead of OpBitcast to do the conversion when
5476 // generating for OpSpecConstantOp instruction.
5477 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5478 }
5479 // For normal run-time conversion instruction, use OpBitcast.
5480 convOp = spv::OpBitcast;
5481 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005482 default:
5483 break;
5484 }
5485
5486 spv::Id result = 0;
5487 if (convOp == spv::OpNop)
5488 return result;
5489
5490 if (convOp == spv::OpSelect) {
5491 zero = makeSmearedConstant(zero, vectorSize);
5492 one = makeSmearedConstant(one, vectorSize);
5493 result = builder.createTriOp(convOp, destType, operand, one, zero);
5494 } else
5495 result = builder.createUnaryOp(convOp, destType, operand);
5496
John Kessenichead86222018-03-28 18:01:20 -06005497 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005498 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005499 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005500}
5501
5502spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5503{
5504 if (vectorSize == 0)
5505 return constant;
5506
5507 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5508 std::vector<spv::Id> components;
5509 for (int c = 0; c < vectorSize; ++c)
5510 components.push_back(constant);
5511 return builder.makeCompositeConstant(vectorTypeId, components);
5512}
5513
John Kessenich426394d2015-07-23 10:22:48 -06005514// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005515spv::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 -06005516{
5517 spv::Op opCode = spv::OpNop;
5518
5519 switch (op) {
5520 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005521 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005522 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005523 opCode = spv::OpAtomicIAdd;
5524 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005525 case glslang::EOpAtomicCounterSubtract:
5526 opCode = spv::OpAtomicISub;
5527 break;
John Kessenich426394d2015-07-23 10:22:48 -06005528 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005529 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005530 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005531 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005532 break;
5533 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005534 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005535 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005536 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005537 break;
5538 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005539 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005540 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005541 opCode = spv::OpAtomicAnd;
5542 break;
5543 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005544 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005545 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005546 opCode = spv::OpAtomicOr;
5547 break;
5548 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005549 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005550 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005551 opCode = spv::OpAtomicXor;
5552 break;
5553 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005554 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005555 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005556 opCode = spv::OpAtomicExchange;
5557 break;
5558 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005559 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005560 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005561 opCode = spv::OpAtomicCompareExchange;
5562 break;
5563 case glslang::EOpAtomicCounterIncrement:
5564 opCode = spv::OpAtomicIIncrement;
5565 break;
5566 case glslang::EOpAtomicCounterDecrement:
5567 opCode = spv::OpAtomicIDecrement;
5568 break;
5569 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05005570 case glslang::EOpImageAtomicLoad:
5571 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06005572 opCode = spv::OpAtomicLoad;
5573 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05005574 case glslang::EOpAtomicStore:
5575 case glslang::EOpImageAtomicStore:
5576 opCode = spv::OpAtomicStore;
5577 break;
John Kessenich426394d2015-07-23 10:22:48 -06005578 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005579 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005580 break;
5581 }
5582
Rex Xue8fe8b02017-09-26 15:42:56 +08005583 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5584 builder.addCapability(spv::CapabilityInt64Atomics);
5585
John Kessenich426394d2015-07-23 10:22:48 -06005586 // Sort out the operands
5587 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05005588 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06005589 // - compare-exchange swaps the value and comparator
5590 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005591 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05005592 spv::Id pointerId = 0, compareId = 0, valueId = 0;
5593 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
5594 spv::Id scopeId;
5595 if (glslangIntermediate->usingVulkanMemoryModel()) {
5596 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
5597 } else {
5598 scopeId = builder.makeUintConstant(spv::ScopeDevice);
5599 }
5600 // semantics default to relaxed
5601 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
5602 spv::Id semanticsId2 = semanticsId;
5603
5604 pointerId = operands[0];
5605 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
5606 // no additional operands
5607 } else if (opCode == spv::OpAtomicCompareExchange) {
5608 compareId = operands[1];
5609 valueId = operands[2];
5610 if (operands.size() > 3) {
5611 scopeId = operands[3];
5612 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
5613 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
5614 }
5615 } else if (opCode == spv::OpAtomicLoad) {
5616 if (operands.size() > 1) {
5617 scopeId = operands[1];
5618 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
5619 }
5620 } else {
5621 // atomic store or RMW
5622 valueId = operands[1];
5623 if (operands.size() > 2) {
5624 scopeId = operands[2];
5625 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
5626 }
Rex Xu04db3f52015-09-16 11:44:02 +08005627 }
John Kessenich426394d2015-07-23 10:22:48 -06005628
Jeff Bolz36831c92018-09-05 10:11:41 -05005629 // Check for capabilities
5630 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
5631 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
5632 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
5633 }
John Kessenich426394d2015-07-23 10:22:48 -06005634
Jeff Bolz36831c92018-09-05 10:11:41 -05005635 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
5636 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
5637 }
John Kessenich48d6e792017-10-06 21:21:48 -06005638
Jeff Bolz36831c92018-09-05 10:11:41 -05005639 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5640 spvAtomicOperands.push_back(pointerId);
5641 spvAtomicOperands.push_back(scopeId);
5642 spvAtomicOperands.push_back(semanticsId);
5643 if (opCode == spv::OpAtomicCompareExchange) {
5644 spvAtomicOperands.push_back(semanticsId2);
5645 spvAtomicOperands.push_back(valueId);
5646 spvAtomicOperands.push_back(compareId);
5647 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
5648 spvAtomicOperands.push_back(valueId);
5649 }
John Kessenich48d6e792017-10-06 21:21:48 -06005650
Jeff Bolz36831c92018-09-05 10:11:41 -05005651 if (opCode == spv::OpAtomicStore) {
5652 builder.createNoResultOp(opCode, spvAtomicOperands);
5653 return 0;
5654 } else {
5655 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5656
5657 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5658 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5659 if (op == glslang::EOpAtomicCounterDecrement)
5660 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5661
5662 return resultId;
5663 }
John Kessenich426394d2015-07-23 10:22:48 -06005664}
5665
John Kessenich91cef522016-05-05 16:45:40 -06005666// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005667spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005668{
Corentin Walleze7061422018-08-08 15:20:15 +02005669#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07005670 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5671 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02005672#endif
Rex Xu9d93a232016-05-05 12:30:44 +08005673
Rex Xu51596642016-09-21 18:56:12 +08005674 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06005675 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005676 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5677
chaocf200da82016-12-20 12:44:35 -08005678 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5679 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005680 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5681 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005682 } else if (op == glslang::EOpAnyInvocation ||
5683 op == glslang::EOpAllInvocations ||
5684 op == glslang::EOpAllInvocationsEqual) {
5685 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5686 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005687 } else {
5688 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005689#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005690 if (op == glslang::EOpMinInvocationsNonUniform ||
5691 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005692 op == glslang::EOpAddInvocationsNonUniform ||
5693 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5694 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5695 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5696 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5697 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5698 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005699 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005700#endif
Rex Xu51596642016-09-21 18:56:12 +08005701
Rex Xu9d93a232016-05-05 12:30:44 +08005702#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005703 switch (op) {
5704 case glslang::EOpMinInvocations:
5705 case glslang::EOpMaxInvocations:
5706 case glslang::EOpAddInvocations:
5707 case glslang::EOpMinInvocationsNonUniform:
5708 case glslang::EOpMaxInvocationsNonUniform:
5709 case glslang::EOpAddInvocationsNonUniform:
5710 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08005711 break;
5712 case glslang::EOpMinInvocationsInclusiveScan:
5713 case glslang::EOpMaxInvocationsInclusiveScan:
5714 case glslang::EOpAddInvocationsInclusiveScan:
5715 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5716 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5717 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5718 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005719 break;
5720 case glslang::EOpMinInvocationsExclusiveScan:
5721 case glslang::EOpMaxInvocationsExclusiveScan:
5722 case glslang::EOpAddInvocationsExclusiveScan:
5723 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5724 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5725 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5726 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005727 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005728 default:
5729 break;
Rex Xu430ef402016-10-14 17:22:23 +08005730 }
John Kessenich149afc32018-08-14 13:31:43 -06005731 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5732 spvGroupOperands.push_back(scope);
5733 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06005734 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06005735 spvGroupOperands.push_back(groupOp);
5736 }
Rex Xu9d93a232016-05-05 12:30:44 +08005737#endif
Rex Xu51596642016-09-21 18:56:12 +08005738 }
5739
John Kessenich149afc32018-08-14 13:31:43 -06005740 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
5741 spv::IdImmediate op = { true, *opIt };
5742 spvGroupOperands.push_back(op);
5743 }
John Kessenich91cef522016-05-05 16:45:40 -06005744
5745 switch (op) {
5746 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005747 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005748 break;
John Kessenich91cef522016-05-05 16:45:40 -06005749 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005750 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005751 break;
John Kessenich91cef522016-05-05 16:45:40 -06005752 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005753 opCode = spv::OpSubgroupAllEqualKHR;
5754 break;
Rex Xu51596642016-09-21 18:56:12 +08005755 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005756 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005757 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005758 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005759 break;
5760 case glslang::EOpReadFirstInvocation:
5761 opCode = spv::OpSubgroupFirstInvocationKHR;
5762 break;
5763 case glslang::EOpBallot:
5764 {
5765 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5766 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5767 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5768 //
5769 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5770 //
5771 spv::Id uintType = builder.makeUintType(32);
5772 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5773 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5774
5775 std::vector<spv::Id> components;
5776 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5777 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5778
5779 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5780 return builder.createUnaryOp(spv::OpBitcast, typeId,
5781 builder.createCompositeConstruct(uvec2Type, components));
5782 }
5783
Rex Xu9d93a232016-05-05 12:30:44 +08005784#ifdef AMD_EXTENSIONS
5785 case glslang::EOpMinInvocations:
5786 case glslang::EOpMaxInvocations:
5787 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005788 case glslang::EOpMinInvocationsInclusiveScan:
5789 case glslang::EOpMaxInvocationsInclusiveScan:
5790 case glslang::EOpAddInvocationsInclusiveScan:
5791 case glslang::EOpMinInvocationsExclusiveScan:
5792 case glslang::EOpMaxInvocationsExclusiveScan:
5793 case glslang::EOpAddInvocationsExclusiveScan:
5794 if (op == glslang::EOpMinInvocations ||
5795 op == glslang::EOpMinInvocationsInclusiveScan ||
5796 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005797 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005798 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005799 else {
5800 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005801 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005802 else
Rex Xu51596642016-09-21 18:56:12 +08005803 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005804 }
Rex Xu430ef402016-10-14 17:22:23 +08005805 } else if (op == glslang::EOpMaxInvocations ||
5806 op == glslang::EOpMaxInvocationsInclusiveScan ||
5807 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005808 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005809 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005810 else {
5811 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005812 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005813 else
Rex Xu51596642016-09-21 18:56:12 +08005814 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005815 }
5816 } else {
5817 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005818 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005819 else
Rex Xu51596642016-09-21 18:56:12 +08005820 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005821 }
5822
Rex Xu2bbbe062016-08-23 15:41:05 +08005823 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005824 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005825
5826 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005827 case glslang::EOpMinInvocationsNonUniform:
5828 case glslang::EOpMaxInvocationsNonUniform:
5829 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005830 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5831 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5832 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5833 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5834 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5835 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5836 if (op == glslang::EOpMinInvocationsNonUniform ||
5837 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5838 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005839 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005840 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005841 else {
5842 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005843 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005844 else
Rex Xu51596642016-09-21 18:56:12 +08005845 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005846 }
5847 }
Rex Xu430ef402016-10-14 17:22:23 +08005848 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5849 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5850 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005851 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005852 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005853 else {
5854 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005855 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005856 else
Rex Xu51596642016-09-21 18:56:12 +08005857 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005858 }
5859 }
5860 else {
5861 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005862 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005863 else
Rex Xu51596642016-09-21 18:56:12 +08005864 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005865 }
5866
Rex Xu2bbbe062016-08-23 15:41:05 +08005867 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005868 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005869
5870 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005871#endif
John Kessenich91cef522016-05-05 16:45:40 -06005872 default:
5873 logger->missingFunctionality("invocation operation");
5874 return spv::NoResult;
5875 }
Rex Xu51596642016-09-21 18:56:12 +08005876
5877 assert(opCode != spv::OpNop);
5878 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005879}
5880
Rex Xu2bbbe062016-08-23 15:41:05 +08005881// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06005882spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
5883 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005884{
Rex Xub7072052016-09-26 15:53:40 +08005885#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005886 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5887 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005888 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005889 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005890 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5891 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5892 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005893#else
5894 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5895 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005896 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5897 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005898#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005899
5900 // Handle group invocation operations scalar by scalar.
5901 // The result type is the same type as the original type.
5902 // The algorithm is to:
5903 // - break the vector into scalars
5904 // - apply the operation to each scalar
5905 // - make a vector out the scalar results
5906
5907 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005908 int numComponents = builder.getNumComponents(operands[0]);
5909 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005910 std::vector<spv::Id> results;
5911
5912 // do each scalar op
5913 for (int comp = 0; comp < numComponents; ++comp) {
5914 std::vector<unsigned int> indexes;
5915 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06005916 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
5917 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005918 if (op == spv::OpSubgroupReadInvocationKHR) {
5919 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06005920 spv::IdImmediate operand = { true, operands[1] };
5921 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08005922 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06005923 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5924 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08005925 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06005926 spv::IdImmediate operand = { true, operands[1] };
5927 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08005928 } else {
John Kessenich149afc32018-08-14 13:31:43 -06005929 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5930 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06005931 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06005932 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08005933 spvGroupOperands.push_back(scalar);
5934 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005935
Rex Xub7072052016-09-26 15:53:40 +08005936 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005937 }
5938
5939 // put the pieces together
5940 return builder.createCompositeConstruct(typeId, results);
5941}
Rex Xu2bbbe062016-08-23 15:41:05 +08005942
John Kessenich66011cb2018-03-06 16:12:04 -07005943// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06005944spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
5945 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07005946{
5947 // Add the required capabilities.
5948 switch (op) {
5949 case glslang::EOpSubgroupElect:
5950 builder.addCapability(spv::CapabilityGroupNonUniform);
5951 break;
5952 case glslang::EOpSubgroupAll:
5953 case glslang::EOpSubgroupAny:
5954 case glslang::EOpSubgroupAllEqual:
5955 builder.addCapability(spv::CapabilityGroupNonUniform);
5956 builder.addCapability(spv::CapabilityGroupNonUniformVote);
5957 break;
5958 case glslang::EOpSubgroupBroadcast:
5959 case glslang::EOpSubgroupBroadcastFirst:
5960 case glslang::EOpSubgroupBallot:
5961 case glslang::EOpSubgroupInverseBallot:
5962 case glslang::EOpSubgroupBallotBitExtract:
5963 case glslang::EOpSubgroupBallotBitCount:
5964 case glslang::EOpSubgroupBallotInclusiveBitCount:
5965 case glslang::EOpSubgroupBallotExclusiveBitCount:
5966 case glslang::EOpSubgroupBallotFindLSB:
5967 case glslang::EOpSubgroupBallotFindMSB:
5968 builder.addCapability(spv::CapabilityGroupNonUniform);
5969 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
5970 break;
5971 case glslang::EOpSubgroupShuffle:
5972 case glslang::EOpSubgroupShuffleXor:
5973 builder.addCapability(spv::CapabilityGroupNonUniform);
5974 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
5975 break;
5976 case glslang::EOpSubgroupShuffleUp:
5977 case glslang::EOpSubgroupShuffleDown:
5978 builder.addCapability(spv::CapabilityGroupNonUniform);
5979 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
5980 break;
5981 case glslang::EOpSubgroupAdd:
5982 case glslang::EOpSubgroupMul:
5983 case glslang::EOpSubgroupMin:
5984 case glslang::EOpSubgroupMax:
5985 case glslang::EOpSubgroupAnd:
5986 case glslang::EOpSubgroupOr:
5987 case glslang::EOpSubgroupXor:
5988 case glslang::EOpSubgroupInclusiveAdd:
5989 case glslang::EOpSubgroupInclusiveMul:
5990 case glslang::EOpSubgroupInclusiveMin:
5991 case glslang::EOpSubgroupInclusiveMax:
5992 case glslang::EOpSubgroupInclusiveAnd:
5993 case glslang::EOpSubgroupInclusiveOr:
5994 case glslang::EOpSubgroupInclusiveXor:
5995 case glslang::EOpSubgroupExclusiveAdd:
5996 case glslang::EOpSubgroupExclusiveMul:
5997 case glslang::EOpSubgroupExclusiveMin:
5998 case glslang::EOpSubgroupExclusiveMax:
5999 case glslang::EOpSubgroupExclusiveAnd:
6000 case glslang::EOpSubgroupExclusiveOr:
6001 case glslang::EOpSubgroupExclusiveXor:
6002 builder.addCapability(spv::CapabilityGroupNonUniform);
6003 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
6004 break;
6005 case glslang::EOpSubgroupClusteredAdd:
6006 case glslang::EOpSubgroupClusteredMul:
6007 case glslang::EOpSubgroupClusteredMin:
6008 case glslang::EOpSubgroupClusteredMax:
6009 case glslang::EOpSubgroupClusteredAnd:
6010 case glslang::EOpSubgroupClusteredOr:
6011 case glslang::EOpSubgroupClusteredXor:
6012 builder.addCapability(spv::CapabilityGroupNonUniform);
6013 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
6014 break;
6015 case glslang::EOpSubgroupQuadBroadcast:
6016 case glslang::EOpSubgroupQuadSwapHorizontal:
6017 case glslang::EOpSubgroupQuadSwapVertical:
6018 case glslang::EOpSubgroupQuadSwapDiagonal:
6019 builder.addCapability(spv::CapabilityGroupNonUniform);
6020 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
6021 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006022#ifdef NV_EXTENSIONS
6023 case glslang::EOpSubgroupPartitionedAdd:
6024 case glslang::EOpSubgroupPartitionedMul:
6025 case glslang::EOpSubgroupPartitionedMin:
6026 case glslang::EOpSubgroupPartitionedMax:
6027 case glslang::EOpSubgroupPartitionedAnd:
6028 case glslang::EOpSubgroupPartitionedOr:
6029 case glslang::EOpSubgroupPartitionedXor:
6030 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6031 case glslang::EOpSubgroupPartitionedInclusiveMul:
6032 case glslang::EOpSubgroupPartitionedInclusiveMin:
6033 case glslang::EOpSubgroupPartitionedInclusiveMax:
6034 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6035 case glslang::EOpSubgroupPartitionedInclusiveOr:
6036 case glslang::EOpSubgroupPartitionedInclusiveXor:
6037 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6038 case glslang::EOpSubgroupPartitionedExclusiveMul:
6039 case glslang::EOpSubgroupPartitionedExclusiveMin:
6040 case glslang::EOpSubgroupPartitionedExclusiveMax:
6041 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6042 case glslang::EOpSubgroupPartitionedExclusiveOr:
6043 case glslang::EOpSubgroupPartitionedExclusiveXor:
6044 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6045 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6046 break;
6047#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006048 default: assert(0 && "Unhandled subgroup operation!");
6049 }
6050
6051 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6052 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6053 const bool isBool = typeProxy == glslang::EbtBool;
6054
6055 spv::Op opCode = spv::OpNop;
6056
6057 // Figure out which opcode to use.
6058 switch (op) {
6059 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6060 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6061 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6062 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6063 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6064 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6065 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6066 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6067 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6068 case glslang::EOpSubgroupBallotBitCount:
6069 case glslang::EOpSubgroupBallotInclusiveBitCount:
6070 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6071 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6072 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6073 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6074 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6075 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6076 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6077 case glslang::EOpSubgroupAdd:
6078 case glslang::EOpSubgroupInclusiveAdd:
6079 case glslang::EOpSubgroupExclusiveAdd:
6080 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006081#ifdef NV_EXTENSIONS
6082 case glslang::EOpSubgroupPartitionedAdd:
6083 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6084 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6085#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006086 if (isFloat) {
6087 opCode = spv::OpGroupNonUniformFAdd;
6088 } else {
6089 opCode = spv::OpGroupNonUniformIAdd;
6090 }
6091 break;
6092 case glslang::EOpSubgroupMul:
6093 case glslang::EOpSubgroupInclusiveMul:
6094 case glslang::EOpSubgroupExclusiveMul:
6095 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006096#ifdef NV_EXTENSIONS
6097 case glslang::EOpSubgroupPartitionedMul:
6098 case glslang::EOpSubgroupPartitionedInclusiveMul:
6099 case glslang::EOpSubgroupPartitionedExclusiveMul:
6100#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006101 if (isFloat) {
6102 opCode = spv::OpGroupNonUniformFMul;
6103 } else {
6104 opCode = spv::OpGroupNonUniformIMul;
6105 }
6106 break;
6107 case glslang::EOpSubgroupMin:
6108 case glslang::EOpSubgroupInclusiveMin:
6109 case glslang::EOpSubgroupExclusiveMin:
6110 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006111#ifdef NV_EXTENSIONS
6112 case glslang::EOpSubgroupPartitionedMin:
6113 case glslang::EOpSubgroupPartitionedInclusiveMin:
6114 case glslang::EOpSubgroupPartitionedExclusiveMin:
6115#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006116 if (isFloat) {
6117 opCode = spv::OpGroupNonUniformFMin;
6118 } else if (isUnsigned) {
6119 opCode = spv::OpGroupNonUniformUMin;
6120 } else {
6121 opCode = spv::OpGroupNonUniformSMin;
6122 }
6123 break;
6124 case glslang::EOpSubgroupMax:
6125 case glslang::EOpSubgroupInclusiveMax:
6126 case glslang::EOpSubgroupExclusiveMax:
6127 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006128#ifdef NV_EXTENSIONS
6129 case glslang::EOpSubgroupPartitionedMax:
6130 case glslang::EOpSubgroupPartitionedInclusiveMax:
6131 case glslang::EOpSubgroupPartitionedExclusiveMax:
6132#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006133 if (isFloat) {
6134 opCode = spv::OpGroupNonUniformFMax;
6135 } else if (isUnsigned) {
6136 opCode = spv::OpGroupNonUniformUMax;
6137 } else {
6138 opCode = spv::OpGroupNonUniformSMax;
6139 }
6140 break;
6141 case glslang::EOpSubgroupAnd:
6142 case glslang::EOpSubgroupInclusiveAnd:
6143 case glslang::EOpSubgroupExclusiveAnd:
6144 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006145#ifdef NV_EXTENSIONS
6146 case glslang::EOpSubgroupPartitionedAnd:
6147 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6148 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6149#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006150 if (isBool) {
6151 opCode = spv::OpGroupNonUniformLogicalAnd;
6152 } else {
6153 opCode = spv::OpGroupNonUniformBitwiseAnd;
6154 }
6155 break;
6156 case glslang::EOpSubgroupOr:
6157 case glslang::EOpSubgroupInclusiveOr:
6158 case glslang::EOpSubgroupExclusiveOr:
6159 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006160#ifdef NV_EXTENSIONS
6161 case glslang::EOpSubgroupPartitionedOr:
6162 case glslang::EOpSubgroupPartitionedInclusiveOr:
6163 case glslang::EOpSubgroupPartitionedExclusiveOr:
6164#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006165 if (isBool) {
6166 opCode = spv::OpGroupNonUniformLogicalOr;
6167 } else {
6168 opCode = spv::OpGroupNonUniformBitwiseOr;
6169 }
6170 break;
6171 case glslang::EOpSubgroupXor:
6172 case glslang::EOpSubgroupInclusiveXor:
6173 case glslang::EOpSubgroupExclusiveXor:
6174 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006175#ifdef NV_EXTENSIONS
6176 case glslang::EOpSubgroupPartitionedXor:
6177 case glslang::EOpSubgroupPartitionedInclusiveXor:
6178 case glslang::EOpSubgroupPartitionedExclusiveXor:
6179#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006180 if (isBool) {
6181 opCode = spv::OpGroupNonUniformLogicalXor;
6182 } else {
6183 opCode = spv::OpGroupNonUniformBitwiseXor;
6184 }
6185 break;
6186 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6187 case glslang::EOpSubgroupQuadSwapHorizontal:
6188 case glslang::EOpSubgroupQuadSwapVertical:
6189 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6190 default: assert(0 && "Unhandled subgroup operation!");
6191 }
6192
John Kessenich149afc32018-08-14 13:31:43 -06006193 // get the right Group Operation
6194 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006195 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006196 default:
6197 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006198 case glslang::EOpSubgroupBallotBitCount:
6199 case glslang::EOpSubgroupAdd:
6200 case glslang::EOpSubgroupMul:
6201 case glslang::EOpSubgroupMin:
6202 case glslang::EOpSubgroupMax:
6203 case glslang::EOpSubgroupAnd:
6204 case glslang::EOpSubgroupOr:
6205 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006206 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006207 break;
6208 case glslang::EOpSubgroupBallotInclusiveBitCount:
6209 case glslang::EOpSubgroupInclusiveAdd:
6210 case glslang::EOpSubgroupInclusiveMul:
6211 case glslang::EOpSubgroupInclusiveMin:
6212 case glslang::EOpSubgroupInclusiveMax:
6213 case glslang::EOpSubgroupInclusiveAnd:
6214 case glslang::EOpSubgroupInclusiveOr:
6215 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006216 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006217 break;
6218 case glslang::EOpSubgroupBallotExclusiveBitCount:
6219 case glslang::EOpSubgroupExclusiveAdd:
6220 case glslang::EOpSubgroupExclusiveMul:
6221 case glslang::EOpSubgroupExclusiveMin:
6222 case glslang::EOpSubgroupExclusiveMax:
6223 case glslang::EOpSubgroupExclusiveAnd:
6224 case glslang::EOpSubgroupExclusiveOr:
6225 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006226 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006227 break;
6228 case glslang::EOpSubgroupClusteredAdd:
6229 case glslang::EOpSubgroupClusteredMul:
6230 case glslang::EOpSubgroupClusteredMin:
6231 case glslang::EOpSubgroupClusteredMax:
6232 case glslang::EOpSubgroupClusteredAnd:
6233 case glslang::EOpSubgroupClusteredOr:
6234 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006235 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006236 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006237#ifdef NV_EXTENSIONS
6238 case glslang::EOpSubgroupPartitionedAdd:
6239 case glslang::EOpSubgroupPartitionedMul:
6240 case glslang::EOpSubgroupPartitionedMin:
6241 case glslang::EOpSubgroupPartitionedMax:
6242 case glslang::EOpSubgroupPartitionedAnd:
6243 case glslang::EOpSubgroupPartitionedOr:
6244 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006245 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006246 break;
6247 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6248 case glslang::EOpSubgroupPartitionedInclusiveMul:
6249 case glslang::EOpSubgroupPartitionedInclusiveMin:
6250 case glslang::EOpSubgroupPartitionedInclusiveMax:
6251 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6252 case glslang::EOpSubgroupPartitionedInclusiveOr:
6253 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006254 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006255 break;
6256 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6257 case glslang::EOpSubgroupPartitionedExclusiveMul:
6258 case glslang::EOpSubgroupPartitionedExclusiveMin:
6259 case glslang::EOpSubgroupPartitionedExclusiveMax:
6260 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6261 case glslang::EOpSubgroupPartitionedExclusiveOr:
6262 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006263 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006264 break;
6265#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006266 }
6267
John Kessenich149afc32018-08-14 13:31:43 -06006268 // build the instruction
6269 std::vector<spv::IdImmediate> spvGroupOperands;
6270
6271 // Every operation begins with the Execution Scope operand.
6272 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6273 spvGroupOperands.push_back(executionScope);
6274
6275 // Next, for all operations that use a Group Operation, push that as an operand.
6276 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006277 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006278 spvGroupOperands.push_back(groupOperand);
6279 }
6280
John Kessenich66011cb2018-03-06 16:12:04 -07006281 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006282 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6283 spv::IdImmediate operand = { true, *opIt };
6284 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006285 }
6286
6287 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006288 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006289 switch (op) {
6290 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006291 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6292 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6293 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6294 }
6295 if (directionId != spv::NoResult) {
6296 spv::IdImmediate direction = { true, directionId };
6297 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006298 }
6299
6300 return builder.createOp(opCode, typeId, spvGroupOperands);
6301}
6302
John Kessenich5e4b1242015-08-06 22:53:06 -06006303spv::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 -06006304{
John Kessenich66011cb2018-03-06 16:12:04 -07006305 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6306 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006307
John Kessenich140f3df2015-06-26 16:58:36 -06006308 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006309 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006310 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006311 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006312 spv::Id typeId0 = 0;
6313 if (consumedOperands > 0)
6314 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006315 spv::Id typeId1 = 0;
6316 if (consumedOperands > 1)
6317 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006318 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006319
6320 switch (op) {
6321 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006322 if (isFloat)
6323 libCall = spv::GLSLstd450FMin;
6324 else if (isUnsigned)
6325 libCall = spv::GLSLstd450UMin;
6326 else
6327 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006328 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006329 break;
6330 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006331 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006332 break;
6333 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006334 if (isFloat)
6335 libCall = spv::GLSLstd450FMax;
6336 else if (isUnsigned)
6337 libCall = spv::GLSLstd450UMax;
6338 else
6339 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006340 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006341 break;
6342 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006343 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006344 break;
6345 case glslang::EOpDot:
6346 opCode = spv::OpDot;
6347 break;
6348 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006349 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006350 break;
6351
6352 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006353 if (isFloat)
6354 libCall = spv::GLSLstd450FClamp;
6355 else if (isUnsigned)
6356 libCall = spv::GLSLstd450UClamp;
6357 else
6358 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006359 builder.promoteScalar(precision, operands.front(), operands[1]);
6360 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006361 break;
6362 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006363 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6364 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006365 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006366 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006367 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006368 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006369 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006370 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006371 break;
6372 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006373 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006374 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006375 break;
6376 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006377 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006378 builder.promoteScalar(precision, operands[0], operands[2]);
6379 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006380 break;
6381
6382 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006383 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006384 break;
6385 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006386 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006387 break;
6388 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006389 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006390 break;
6391 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006392 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006393 break;
6394 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006395 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006396 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006397 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006398#ifdef AMD_EXTENSIONS
6399 if (typeProxy == glslang::EbtFloat16)
6400 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6401#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006402 libCall = spv::GLSLstd450InterpolateAtSample;
6403 break;
6404 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006405#ifdef AMD_EXTENSIONS
6406 if (typeProxy == glslang::EbtFloat16)
6407 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6408#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006409 libCall = spv::GLSLstd450InterpolateAtOffset;
6410 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006411 case glslang::EOpAddCarry:
6412 opCode = spv::OpIAddCarry;
6413 typeId = builder.makeStructResultType(typeId0, typeId0);
6414 consumedOperands = 2;
6415 break;
6416 case glslang::EOpSubBorrow:
6417 opCode = spv::OpISubBorrow;
6418 typeId = builder.makeStructResultType(typeId0, typeId0);
6419 consumedOperands = 2;
6420 break;
6421 case glslang::EOpUMulExtended:
6422 opCode = spv::OpUMulExtended;
6423 typeId = builder.makeStructResultType(typeId0, typeId0);
6424 consumedOperands = 2;
6425 break;
6426 case glslang::EOpIMulExtended:
6427 opCode = spv::OpSMulExtended;
6428 typeId = builder.makeStructResultType(typeId0, typeId0);
6429 consumedOperands = 2;
6430 break;
6431 case glslang::EOpBitfieldExtract:
6432 if (isUnsigned)
6433 opCode = spv::OpBitFieldUExtract;
6434 else
6435 opCode = spv::OpBitFieldSExtract;
6436 break;
6437 case glslang::EOpBitfieldInsert:
6438 opCode = spv::OpBitFieldInsert;
6439 break;
6440
6441 case glslang::EOpFma:
6442 libCall = spv::GLSLstd450Fma;
6443 break;
6444 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006445 {
6446 libCall = spv::GLSLstd450FrexpStruct;
6447 assert(builder.isPointerType(typeId1));
6448 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006449 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006450#ifdef AMD_EXTENSIONS
6451 if (width == 16)
6452 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6453 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6454#endif
Rex Xu470026f2017-03-29 17:12:40 +08006455 if (builder.getNumComponents(operands[0]) == 1)
6456 frexpIntType = builder.makeIntegerType(width, true);
6457 else
6458 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6459 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6460 consumedOperands = 1;
6461 }
John Kessenich55e7d112015-11-15 21:33:39 -07006462 break;
6463 case glslang::EOpLdexp:
6464 libCall = spv::GLSLstd450Ldexp;
6465 break;
6466
Rex Xu574ab042016-04-14 16:53:07 +08006467 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006468 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006469
John Kessenich66011cb2018-03-06 16:12:04 -07006470 case glslang::EOpSubgroupBroadcast:
6471 case glslang::EOpSubgroupBallotBitExtract:
6472 case glslang::EOpSubgroupShuffle:
6473 case glslang::EOpSubgroupShuffleXor:
6474 case glslang::EOpSubgroupShuffleUp:
6475 case glslang::EOpSubgroupShuffleDown:
6476 case glslang::EOpSubgroupClusteredAdd:
6477 case glslang::EOpSubgroupClusteredMul:
6478 case glslang::EOpSubgroupClusteredMin:
6479 case glslang::EOpSubgroupClusteredMax:
6480 case glslang::EOpSubgroupClusteredAnd:
6481 case glslang::EOpSubgroupClusteredOr:
6482 case glslang::EOpSubgroupClusteredXor:
6483 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006484#ifdef NV_EXTENSIONS
6485 case glslang::EOpSubgroupPartitionedAdd:
6486 case glslang::EOpSubgroupPartitionedMul:
6487 case glslang::EOpSubgroupPartitionedMin:
6488 case glslang::EOpSubgroupPartitionedMax:
6489 case glslang::EOpSubgroupPartitionedAnd:
6490 case glslang::EOpSubgroupPartitionedOr:
6491 case glslang::EOpSubgroupPartitionedXor:
6492 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6493 case glslang::EOpSubgroupPartitionedInclusiveMul:
6494 case glslang::EOpSubgroupPartitionedInclusiveMin:
6495 case glslang::EOpSubgroupPartitionedInclusiveMax:
6496 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6497 case glslang::EOpSubgroupPartitionedInclusiveOr:
6498 case glslang::EOpSubgroupPartitionedInclusiveXor:
6499 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6500 case glslang::EOpSubgroupPartitionedExclusiveMul:
6501 case glslang::EOpSubgroupPartitionedExclusiveMin:
6502 case glslang::EOpSubgroupPartitionedExclusiveMax:
6503 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6504 case glslang::EOpSubgroupPartitionedExclusiveOr:
6505 case glslang::EOpSubgroupPartitionedExclusiveXor:
6506#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006507 return createSubgroupOperation(op, typeId, operands, typeProxy);
6508
Rex Xu9d93a232016-05-05 12:30:44 +08006509#ifdef AMD_EXTENSIONS
6510 case glslang::EOpSwizzleInvocations:
6511 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6512 libCall = spv::SwizzleInvocationsAMD;
6513 break;
6514 case glslang::EOpSwizzleInvocationsMasked:
6515 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6516 libCall = spv::SwizzleInvocationsMaskedAMD;
6517 break;
6518 case glslang::EOpWriteInvocation:
6519 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6520 libCall = spv::WriteInvocationAMD;
6521 break;
6522
6523 case glslang::EOpMin3:
6524 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6525 if (isFloat)
6526 libCall = spv::FMin3AMD;
6527 else {
6528 if (isUnsigned)
6529 libCall = spv::UMin3AMD;
6530 else
6531 libCall = spv::SMin3AMD;
6532 }
6533 break;
6534 case glslang::EOpMax3:
6535 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6536 if (isFloat)
6537 libCall = spv::FMax3AMD;
6538 else {
6539 if (isUnsigned)
6540 libCall = spv::UMax3AMD;
6541 else
6542 libCall = spv::SMax3AMD;
6543 }
6544 break;
6545 case glslang::EOpMid3:
6546 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6547 if (isFloat)
6548 libCall = spv::FMid3AMD;
6549 else {
6550 if (isUnsigned)
6551 libCall = spv::UMid3AMD;
6552 else
6553 libCall = spv::SMid3AMD;
6554 }
6555 break;
6556
6557 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006558 if (typeProxy == glslang::EbtFloat16)
6559 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08006560 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6561 libCall = spv::InterpolateAtVertexAMD;
6562 break;
6563#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05006564 case glslang::EOpBarrier:
6565 {
6566 // This is for the extended controlBarrier function, with four operands.
6567 // The unextended barrier() goes through createNoArgOperation.
6568 assert(operands.size() == 4);
6569 unsigned int executionScope = builder.getConstantScalar(operands[0]);
6570 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
6571 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
6572 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6573 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6574 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6575 }
6576 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
6577 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6578 }
6579 return 0;
6580 }
6581 break;
6582 case glslang::EOpMemoryBarrier:
6583 {
6584 // This is for the extended memoryBarrier function, with three operands.
6585 // The unextended memoryBarrier() goes through createNoArgOperation.
6586 assert(operands.size() == 3);
6587 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
6588 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
6589 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6590 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6591 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6592 }
6593 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
6594 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6595 }
6596 return 0;
6597 }
6598 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006599 default:
6600 return 0;
6601 }
6602
6603 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006604 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006605 // Use an extended instruction from the standard library.
6606 // Construct the call arguments, without modifying the original operands vector.
6607 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6608 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006609 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006610 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006611 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006612 case 0:
6613 // should all be handled by visitAggregate and createNoArgOperation
6614 assert(0);
6615 return 0;
6616 case 1:
6617 // should all be handled by createUnaryOperation
6618 assert(0);
6619 return 0;
6620 case 2:
6621 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6622 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006623 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006624 // anything 3 or over doesn't have l-value operands, so all should be consumed
6625 assert(consumedOperands == operands.size());
6626 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006627 break;
6628 }
6629 }
6630
John Kessenich55e7d112015-11-15 21:33:39 -07006631 // Decode the return types that were structures
6632 switch (op) {
6633 case glslang::EOpAddCarry:
6634 case glslang::EOpSubBorrow:
6635 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6636 id = builder.createCompositeExtract(id, typeId0, 0);
6637 break;
6638 case glslang::EOpUMulExtended:
6639 case glslang::EOpIMulExtended:
6640 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6641 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6642 break;
6643 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006644 {
6645 assert(operands.size() == 2);
6646 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6647 // "exp" is floating-point type (from HLSL intrinsic)
6648 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6649 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6650 builder.createStore(member1, operands[1]);
6651 } else
6652 // "exp" is integer type (from GLSL built-in function)
6653 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6654 id = builder.createCompositeExtract(id, typeId0, 0);
6655 }
John Kessenich55e7d112015-11-15 21:33:39 -07006656 break;
6657 default:
6658 break;
6659 }
6660
John Kessenich32cfd492016-02-02 12:37:46 -07006661 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006662}
6663
Rex Xu9d93a232016-05-05 12:30:44 +08006664// Intrinsics with no arguments (or no return value, and no precision).
6665spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006666{
Jeff Bolz36831c92018-09-05 10:11:41 -05006667 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
6668 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06006669
6670 switch (op) {
6671 case glslang::EOpEmitVertex:
6672 builder.createNoResultOp(spv::OpEmitVertex);
6673 return 0;
6674 case glslang::EOpEndPrimitive:
6675 builder.createNoResultOp(spv::OpEndPrimitive);
6676 return 0;
6677 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006678 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006679 if (glslangIntermediate->usingVulkanMemoryModel()) {
6680 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6681 spv::MemorySemanticsOutputMemoryKHRMask |
6682 spv::MemorySemanticsAcquireReleaseMask);
6683 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6684 } else {
6685 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6686 }
John Kessenich82979362017-12-11 04:02:24 -07006687 } else {
6688 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6689 spv::MemorySemanticsWorkgroupMemoryMask |
6690 spv::MemorySemanticsAcquireReleaseMask);
6691 }
John Kessenich140f3df2015-06-26 16:58:36 -06006692 return 0;
6693 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05006694 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
6695 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006696 return 0;
6697 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006698 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
6699 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006700 return 0;
6701 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05006702 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
6703 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006704 return 0;
6705 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05006706 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
6707 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006708 return 0;
6709 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05006710 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
6711 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006712 return 0;
6713 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006714 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
6715 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006716 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06006717 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006718 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07006719 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07006720 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006721 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07006722 case glslang::EOpDeviceMemoryBarrier:
6723 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6724 spv::MemorySemanticsImageMemoryMask |
6725 spv::MemorySemanticsAcquireReleaseMask);
6726 return 0;
6727 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
6728 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6729 spv::MemorySemanticsImageMemoryMask |
6730 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006731 return 0;
6732 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07006733 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6734 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006735 return 0;
6736 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006737 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6738 spv::MemorySemanticsWorkgroupMemoryMask |
6739 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006740 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07006741 case glslang::EOpSubgroupBarrier:
6742 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6743 spv::MemorySemanticsAcquireReleaseMask);
6744 return spv::NoResult;
6745 case glslang::EOpSubgroupMemoryBarrier:
6746 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6747 spv::MemorySemanticsAcquireReleaseMask);
6748 return spv::NoResult;
6749 case glslang::EOpSubgroupMemoryBarrierBuffer:
6750 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
6751 spv::MemorySemanticsAcquireReleaseMask);
6752 return spv::NoResult;
6753 case glslang::EOpSubgroupMemoryBarrierImage:
6754 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
6755 spv::MemorySemanticsAcquireReleaseMask);
6756 return spv::NoResult;
6757 case glslang::EOpSubgroupMemoryBarrierShared:
6758 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6759 spv::MemorySemanticsAcquireReleaseMask);
6760 return spv::NoResult;
6761 case glslang::EOpSubgroupElect: {
6762 std::vector<spv::Id> operands;
6763 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
6764 }
Rex Xu9d93a232016-05-05 12:30:44 +08006765#ifdef AMD_EXTENSIONS
6766 case glslang::EOpTime:
6767 {
6768 std::vector<spv::Id> args; // Dummy arguments
6769 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
6770 return builder.setPrecision(id, precision);
6771 }
6772#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006773 default:
Lei Zhang17535f72016-05-04 15:55:59 -04006774 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06006775 return 0;
6776 }
6777}
6778
6779spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
6780{
John Kessenich2f273362015-07-18 22:34:27 -06006781 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06006782 spv::Id id;
6783 if (symbolValues.end() != iter) {
6784 id = iter->second;
6785 return id;
6786 }
6787
6788 // it was not found, create it
6789 id = createSpvVariable(symbol);
6790 symbolValues[symbol->getId()] = id;
6791
Rex Xuc884b4a2016-06-29 15:03:44 +08006792 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006793 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
6794 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
6795 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07006796 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07006797 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06006798 if (symbol->getQualifier().hasIndex())
6799 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
6800 if (symbol->getQualifier().hasComponent())
6801 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06006802 // atomic counters use this:
6803 if (symbol->getQualifier().hasOffset())
6804 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006805 }
6806
scygan2c864272016-05-18 18:09:17 +02006807 if (symbol->getQualifier().hasLocation())
6808 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07006809 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07006810 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07006811 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06006812 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07006813 }
John Kessenich140f3df2015-06-26 16:58:36 -06006814 if (symbol->getQualifier().hasSet())
6815 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07006816 else if (IsDescriptorResource(symbol->getType())) {
6817 // default to 0
6818 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
6819 }
John Kessenich140f3df2015-06-26 16:58:36 -06006820 if (symbol->getQualifier().hasBinding())
6821 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07006822 if (symbol->getQualifier().hasAttachment())
6823 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06006824 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07006825 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06006826 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06006827 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07006828 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06006829 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07006830 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
6831 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
6832 builder.addDecoration(id, spv::DecorationXfbStride, stride);
6833 }
6834 if (symbol->getQualifier().hasXfbOffset())
6835 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006836 }
6837
Rex Xu1da878f2016-02-21 20:59:01 +08006838 if (symbol->getType().isImage()) {
6839 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05006840 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08006841 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07006842 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08006843 }
6844
John Kessenich140f3df2015-06-26 16:58:36 -06006845 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06006846 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06006847 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07006848 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06006849
John Kessenich5611c6d2018-04-05 11:25:02 -06006850 // nonuniform
6851 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
6852
John Kessenichecba76f2017-01-06 00:34:48 -07006853#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08006854 if (builtIn == spv::BuiltInSampleMask) {
6855 spv::Decoration decoration;
6856 // GL_NV_sample_mask_override_coverage extension
6857 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08006858 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08006859 else
6860 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07006861 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08006862 if (decoration != spv::DecorationMax) {
6863 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
6864 }
6865 }
chaoc771d89f2017-01-13 01:10:53 -08006866 else if (builtIn == spv::BuiltInLayer) {
6867 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06006868 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006869 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08006870 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
6871 builder.addExtension(spv::E_SPV_NV_viewport_array2);
6872 }
John Kessenichb41bff62017-08-11 13:07:17 -06006873 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006874 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
6875 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08006876 builder.addCapability(spv::CapabilityShaderStereoViewNV);
6877 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
6878 }
6879 }
6880
chaoc6e5acae2016-12-20 13:28:52 -08006881 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006882 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08006883 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08006884 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
6885 }
Chao Chen9eada4b2018-09-19 11:39:56 -07006886 if (symbol->getQualifier().pervertexNV) {
6887 builder.addDecoration(id, spv::DecorationPerVertexNV);
6888 builder.addCapability(spv::CapabilityFragmentBarycentricNV);
6889 builder.addExtension(spv::E_SPV_NV_fragment_shader_barycentric);
6890 }
chaoc0ad6a4e2016-12-19 16:29:34 -08006891#endif
6892
John Kessenich5d610ee2018-03-07 18:05:55 -07006893 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
6894 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
6895 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
6896 symbol->getType().getQualifier().semanticName);
6897 }
6898
John Kessenich140f3df2015-06-26 16:58:36 -06006899 return id;
6900}
6901
John Kessenich55e7d112015-11-15 21:33:39 -07006902// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07006903// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07006904//
6905// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
6906//
6907// Recursively walk the nodes. The nodes form a tree whose leaves are
6908// regular constants, which themselves are trees that createSpvConstant()
6909// recursively walks. So, this function walks the "top" of the tree:
6910// - emit specialization constant-building instructions for specConstant
6911// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04006912spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07006913{
John Kessenich7cc0e282016-03-20 00:46:02 -06006914 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07006915
qining4f4bb812016-04-03 23:55:17 -04006916 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07006917 if (! node.getQualifier().specConstant) {
6918 // hand off to the non-spec-constant path
6919 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
6920 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04006921 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07006922 nextConst, false);
6923 }
6924
6925 // We now know we have a specialization constant to build
6926
John Kessenichd94c0032016-05-30 19:29:40 -06006927 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04006928 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
6929 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
6930 std::vector<spv::Id> dimConstId;
6931 for (int dim = 0; dim < 3; ++dim) {
6932 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
6933 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07006934 if (specConst) {
6935 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
6936 glslangIntermediate->getLocalSizeSpecId(dim));
6937 }
qining4f4bb812016-04-03 23:55:17 -04006938 }
6939 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
6940 }
6941
6942 // An AST node labelled as specialization constant should be a symbol node.
6943 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
6944 if (auto* sn = node.getAsSymbolNode()) {
6945 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04006946 // Traverse the constant constructor sub tree like generating normal run-time instructions.
6947 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
6948 // will set the builder into spec constant op instruction generating mode.
6949 sub_tree->traverse(this);
6950 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04006951 } else if (auto* const_union_array = &sn->getConstArray()){
6952 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01006953 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
6954 builder.addName(id, sn->getName().c_str());
6955 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07006956 }
6957 }
qining4f4bb812016-04-03 23:55:17 -04006958
6959 // Neither a front-end constant node, nor a specialization constant node with constant union array or
6960 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04006961 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04006962 exit(1);
6963 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07006964}
6965
John Kessenich140f3df2015-06-26 16:58:36 -06006966// Use 'consts' as the flattened glslang source of scalar constants to recursively
6967// build the aggregate SPIR-V constant.
6968//
6969// If there are not enough elements present in 'consts', 0 will be substituted;
6970// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
6971//
qining08408382016-03-21 09:51:37 -04006972spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06006973{
6974 // vector of constants for SPIR-V
6975 std::vector<spv::Id> spvConsts;
6976
6977 // Type is used for struct and array constants
6978 spv::Id typeId = convertGlslangToSpvType(glslangType);
6979
6980 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006981 glslang::TType elementType(glslangType, 0);
6982 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04006983 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006984 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006985 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06006986 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04006987 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006988 } else if (glslangType.getStruct()) {
6989 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
6990 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04006991 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06006992 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06006993 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
6994 bool zero = nextConst >= consts.size();
6995 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006996 case glslang::EbtInt8:
6997 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
6998 break;
6999 case glslang::EbtUint8:
7000 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
7001 break;
7002 case glslang::EbtInt16:
7003 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
7004 break;
7005 case glslang::EbtUint16:
7006 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
7007 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007008 case glslang::EbtInt:
7009 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
7010 break;
7011 case glslang::EbtUint:
7012 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
7013 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007014 case glslang::EbtInt64:
7015 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
7016 break;
7017 case glslang::EbtUint64:
7018 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
7019 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007020 case glslang::EbtFloat:
7021 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7022 break;
7023 case glslang::EbtDouble:
7024 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
7025 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007026 case glslang::EbtFloat16:
7027 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
7028 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007029 case glslang::EbtBool:
7030 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7031 break;
7032 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007033 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007034 break;
7035 }
7036 ++nextConst;
7037 }
7038 } else {
7039 // we have a non-aggregate (scalar) constant
7040 bool zero = nextConst >= consts.size();
7041 spv::Id scalar = 0;
7042 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007043 case glslang::EbtInt8:
7044 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7045 break;
7046 case glslang::EbtUint8:
7047 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7048 break;
7049 case glslang::EbtInt16:
7050 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7051 break;
7052 case glslang::EbtUint16:
7053 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7054 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007055 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007056 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007057 break;
7058 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007059 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007060 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007061 case glslang::EbtInt64:
7062 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7063 break;
7064 case glslang::EbtUint64:
7065 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7066 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007067 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007068 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007069 break;
7070 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007071 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007072 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007073 case glslang::EbtFloat16:
7074 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7075 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007076 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007077 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007078 break;
7079 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007080 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007081 break;
7082 }
7083 ++nextConst;
7084 return scalar;
7085 }
7086
7087 return builder.makeCompositeConstant(typeId, spvConsts);
7088}
7089
John Kessenich7c1aa102015-10-15 13:29:11 -06007090// Return true if the node is a constant or symbol whose reading has no
7091// non-trivial observable cost or effect.
7092bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7093{
7094 // don't know what this is
7095 if (node == nullptr)
7096 return false;
7097
7098 // a constant is safe
7099 if (node->getAsConstantUnion() != nullptr)
7100 return true;
7101
7102 // not a symbol means non-trivial
7103 if (node->getAsSymbolNode() == nullptr)
7104 return false;
7105
7106 // a symbol, depends on what's being read
7107 switch (node->getType().getQualifier().storage) {
7108 case glslang::EvqTemporary:
7109 case glslang::EvqGlobal:
7110 case glslang::EvqIn:
7111 case glslang::EvqInOut:
7112 case glslang::EvqConst:
7113 case glslang::EvqConstReadOnly:
7114 case glslang::EvqUniform:
7115 return true;
7116 default:
7117 return false;
7118 }
qining25262b32016-05-06 17:25:16 -04007119}
John Kessenich7c1aa102015-10-15 13:29:11 -06007120
7121// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007122// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007123// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007124// Return true if trivial.
7125bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7126{
7127 if (node == nullptr)
7128 return false;
7129
John Kessenich84cc15f2017-05-24 16:44:47 -06007130 // count non scalars as trivial, as well as anything coming from HLSL
7131 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007132 return true;
7133
John Kessenich7c1aa102015-10-15 13:29:11 -06007134 // symbols and constants are trivial
7135 if (isTrivialLeaf(node))
7136 return true;
7137
7138 // otherwise, it needs to be a simple operation or one or two leaf nodes
7139
7140 // not a simple operation
7141 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7142 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7143 if (binaryNode == nullptr && unaryNode == nullptr)
7144 return false;
7145
7146 // not on leaf nodes
7147 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7148 return false;
7149
7150 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7151 return false;
7152 }
7153
7154 switch (node->getAsOperator()->getOp()) {
7155 case glslang::EOpLogicalNot:
7156 case glslang::EOpConvIntToBool:
7157 case glslang::EOpConvUintToBool:
7158 case glslang::EOpConvFloatToBool:
7159 case glslang::EOpConvDoubleToBool:
7160 case glslang::EOpEqual:
7161 case glslang::EOpNotEqual:
7162 case glslang::EOpLessThan:
7163 case glslang::EOpGreaterThan:
7164 case glslang::EOpLessThanEqual:
7165 case glslang::EOpGreaterThanEqual:
7166 case glslang::EOpIndexDirect:
7167 case glslang::EOpIndexDirectStruct:
7168 case glslang::EOpLogicalXor:
7169 case glslang::EOpAny:
7170 case glslang::EOpAll:
7171 return true;
7172 default:
7173 return false;
7174 }
7175}
7176
7177// Emit short-circuiting code, where 'right' is never evaluated unless
7178// the left side is true (for &&) or false (for ||).
7179spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7180{
7181 spv::Id boolTypeId = builder.makeBoolType();
7182
7183 // emit left operand
7184 builder.clearAccessChain();
7185 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007186 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007187
7188 // Operands to accumulate OpPhi operands
7189 std::vector<spv::Id> phiOperands;
7190 // accumulate left operand's phi information
7191 phiOperands.push_back(leftId);
7192 phiOperands.push_back(builder.getBuildPoint()->getId());
7193
7194 // Make the two kinds of operation symmetric with a "!"
7195 // || => emit "if (! left) result = right"
7196 // && => emit "if ( left) result = right"
7197 //
7198 // TODO: this runtime "not" for || could be avoided by adding functionality
7199 // to 'builder' to have an "else" without an "then"
7200 if (op == glslang::EOpLogicalOr)
7201 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7202
7203 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007204 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007205
7206 // emit right operand as the "then" part of the "if"
7207 builder.clearAccessChain();
7208 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007209 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007210
7211 // accumulate left operand's phi information
7212 phiOperands.push_back(rightId);
7213 phiOperands.push_back(builder.getBuildPoint()->getId());
7214
7215 // finish the "if"
7216 ifBuilder.makeEndIf();
7217
7218 // phi together the two results
7219 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7220}
7221
Frank Henigman541f7bb2018-01-16 00:18:26 -05007222#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007223// Return type Id of the imported set of extended instructions corresponds to the name.
7224// Import this set if it has not been imported yet.
7225spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7226{
7227 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7228 return extBuiltinMap[name];
7229 else {
Rex Xu51596642016-09-21 18:56:12 +08007230 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007231 spv::Id extBuiltins = builder.import(name);
7232 extBuiltinMap[name] = extBuiltins;
7233 return extBuiltins;
7234 }
7235}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007236#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007237
John Kessenich140f3df2015-06-26 16:58:36 -06007238}; // end anonymous namespace
7239
7240namespace glslang {
7241
John Kessenich68d78fd2015-07-12 19:28:10 -06007242void GetSpirvVersion(std::string& version)
7243{
John Kessenich9e55f632015-07-15 10:03:39 -06007244 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007245 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007246 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007247 version = buf;
7248}
7249
John Kessenicha372a3e2017-11-02 22:32:14 -06007250// For low-order part of the generator's magic number. Bump up
7251// when there is a change in the style (e.g., if SSA form changes,
7252// or a different instruction sequence to do something gets used).
7253int GetSpirvGeneratorVersion()
7254{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007255 // return 1; // start
7256 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007257 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007258 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007259 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007260 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7261 // versions 4 and 6 each generate OpArrayLength as it has long been done
7262 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007263}
7264
John Kessenich140f3df2015-06-26 16:58:36 -06007265// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007266void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007267{
7268 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007269 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007270 if (out.fail())
7271 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007272 for (int i = 0; i < (int)spirv.size(); ++i) {
7273 unsigned int word = spirv[i];
7274 out.write((const char*)&word, 4);
7275 }
7276 out.close();
7277}
7278
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007279// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007280void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007281{
7282 std::ofstream out;
7283 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007284 if (out.fail())
7285 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007286 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007287 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007288 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007289 if (varName != nullptr) {
7290 out << "\t #pragma once" << std::endl;
7291 out << "const uint32_t " << varName << "[] = {" << std::endl;
7292 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007293 const int WORDS_PER_LINE = 8;
7294 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7295 out << "\t";
7296 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7297 const unsigned int word = spirv[i + j];
7298 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7299 if (i + j + 1 < (int)spirv.size()) {
7300 out << ",";
7301 }
7302 }
7303 out << std::endl;
7304 }
Flavio15017db2017-02-15 14:29:33 -08007305 if (varName != nullptr) {
7306 out << "};";
7307 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007308 out.close();
7309}
7310
John Kessenich140f3df2015-06-26 16:58:36 -06007311//
7312// Set up the glslang traversal
7313//
John Kessenich4e11b612018-08-30 16:56:59 -06007314void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007315{
Lei Zhang17535f72016-05-04 15:55:59 -04007316 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007317 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007318}
7319
John Kessenich4e11b612018-08-30 16:56:59 -06007320void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007321 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007322{
John Kessenich140f3df2015-06-26 16:58:36 -06007323 TIntermNode* root = intermediate.getTreeRoot();
7324
7325 if (root == 0)
7326 return;
7327
John Kessenich4e11b612018-08-30 16:56:59 -06007328 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007329 if (options == nullptr)
7330 options = &defaultOptions;
7331
John Kessenich4e11b612018-08-30 16:56:59 -06007332 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007333
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007334 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007335 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007336 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007337 it.dumpSpv(spirv);
7338
GregFfb03a552018-03-29 11:49:14 -06007339#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007340 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7341 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007342 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007343 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007344
John Kessenich4e11b612018-08-30 16:56:59 -06007345 if (options->validate)
7346 SpirvToolsValidate(intermediate, spirv, logger);
7347
John Kessenich717c80a2018-08-23 15:17:10 -06007348 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007349 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007350
GregFcd1f1692017-09-21 18:40:22 -06007351#endif
7352
John Kessenich4e11b612018-08-30 16:56:59 -06007353 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06007354}
7355
7356}; // end namespace glslang