blob: 3a36b38aee1a0c475de567c845e987759cdef666 [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;
chaoc771d89f2017-01-13 01:10:53 -0800830#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800831 default:
832 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600833 }
834}
835
Rex Xufc618912015-09-09 16:42:49 +0800836// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700837spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800838{
839 assert(type.getBasicType() == glslang::EbtSampler);
840
John Kessenich5d0fa972016-02-15 11:57:00 -0700841 // Check for capabilities
842 switch (type.getQualifier().layoutFormat) {
843 case glslang::ElfRg32f:
844 case glslang::ElfRg16f:
845 case glslang::ElfR11fG11fB10f:
846 case glslang::ElfR16f:
847 case glslang::ElfRgba16:
848 case glslang::ElfRgb10A2:
849 case glslang::ElfRg16:
850 case glslang::ElfRg8:
851 case glslang::ElfR16:
852 case glslang::ElfR8:
853 case glslang::ElfRgba16Snorm:
854 case glslang::ElfRg16Snorm:
855 case glslang::ElfRg8Snorm:
856 case glslang::ElfR16Snorm:
857 case glslang::ElfR8Snorm:
858
859 case glslang::ElfRg32i:
860 case glslang::ElfRg16i:
861 case glslang::ElfRg8i:
862 case glslang::ElfR16i:
863 case glslang::ElfR8i:
864
865 case glslang::ElfRgb10a2ui:
866 case glslang::ElfRg32ui:
867 case glslang::ElfRg16ui:
868 case glslang::ElfRg8ui:
869 case glslang::ElfR16ui:
870 case glslang::ElfR8ui:
871 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
872 break;
873
874 default:
875 break;
876 }
877
878 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800879 switch (type.getQualifier().layoutFormat) {
880 case glslang::ElfNone: return spv::ImageFormatUnknown;
881 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
882 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
883 case glslang::ElfR32f: return spv::ImageFormatR32f;
884 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
885 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
886 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
887 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
888 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
889 case glslang::ElfR16f: return spv::ImageFormatR16f;
890 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
891 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
892 case glslang::ElfRg16: return spv::ImageFormatRg16;
893 case glslang::ElfRg8: return spv::ImageFormatRg8;
894 case glslang::ElfR16: return spv::ImageFormatR16;
895 case glslang::ElfR8: return spv::ImageFormatR8;
896 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
897 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
898 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
899 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
900 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
901 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
902 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
903 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
904 case glslang::ElfR32i: return spv::ImageFormatR32i;
905 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
906 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
907 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
908 case glslang::ElfR16i: return spv::ImageFormatR16i;
909 case glslang::ElfR8i: return spv::ImageFormatR8i;
910 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
911 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
912 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
913 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
914 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
915 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
916 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
917 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
918 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
919 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600920 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800921 }
922}
923
John Kesseniche18fd202018-01-30 11:01:39 -0700924spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +0800925{
John Kesseniche18fd202018-01-30 11:01:39 -0700926 if (selectionNode.getFlatten())
927 return spv::SelectionControlFlattenMask;
928 if (selectionNode.getDontFlatten())
929 return spv::SelectionControlDontFlattenMask;
930 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +0800931}
932
John Kesseniche18fd202018-01-30 11:01:39 -0700933spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -0600934{
John Kesseniche18fd202018-01-30 11:01:39 -0700935 if (switchNode.getFlatten())
936 return spv::SelectionControlFlattenMask;
937 if (switchNode.getDontFlatten())
938 return spv::SelectionControlDontFlattenMask;
939 return spv::SelectionControlMaskNone;
940}
941
John Kessenicha2858d92018-01-31 08:11:18 -0700942// return a non-0 dependency if the dependency argument must be set
943spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
944 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -0700945{
946 spv::LoopControlMask control = spv::LoopControlMaskNone;
947
948 if (loopNode.getDontUnroll())
949 control = control | spv::LoopControlDontUnrollMask;
950 if (loopNode.getUnroll())
951 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -0700952 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -0700953 control = control | spv::LoopControlDependencyInfiniteMask;
954 else if (loopNode.getLoopDependency() > 0) {
955 control = control | spv::LoopControlDependencyLengthMask;
956 dependencyLength = loopNode.getLoopDependency();
957 }
John Kesseniche18fd202018-01-30 11:01:39 -0700958
959 return control;
steve-lunargf1709e72017-05-02 20:14:50 -0600960}
961
John Kessenicha5c5fb62017-05-05 05:09:58 -0600962// Translate glslang type to SPIR-V storage class.
963spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
964{
965 if (type.getQualifier().isPipeInput())
966 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600967 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600968 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600969
970 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
971 type.getQualifier().storage == glslang::EvqUniform) {
972 if (type.getBasicType() == glslang::EbtAtomicUint)
973 return spv::StorageClassAtomicCounter;
974 if (type.containsOpaque())
975 return spv::StorageClassUniformConstant;
976 }
977
978 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -0700979 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -0600980 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600981 }
982
983 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600984 if (type.getQualifier().layoutPushConstant)
985 return spv::StorageClassPushConstant;
986 if (type.getBasicType() == glslang::EbtBlock)
987 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600988 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600989 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600990
991 switch (type.getQualifier().storage) {
992 case glslang::EvqShared: return spv::StorageClassWorkgroup;
993 case glslang::EvqGlobal: return spv::StorageClassPrivate;
994 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
995 case glslang::EvqTemporary: return spv::StorageClassFunction;
996 default:
997 assert(0);
998 break;
999 }
1000
1001 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -06001002}
1003
John Kessenich5611c6d2018-04-05 11:25:02 -06001004// Add capabilities pertaining to how an array is indexed.
1005void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
1006 const glslang::TType& indexType)
1007{
1008 if (indexType.getQualifier().isNonUniform()) {
1009 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -05001010 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -06001011 if (baseType.getBasicType() == glslang::EbtSampler) {
1012 if (baseType.getQualifier().hasAttachment())
1013 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
1014 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
1015 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
1016 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
1017 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
1018 else if (baseType.isImage())
1019 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
1020 else if (baseType.isTexture())
1021 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
1022 } else if (baseType.getBasicType() == glslang::EbtBlock) {
1023 if (baseType.getQualifier().storage == glslang::EvqBuffer)
1024 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
1025 else if (baseType.getQualifier().storage == glslang::EvqUniform)
1026 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
1027 }
1028 } else {
1029 // assume a dynamically uniform index
1030 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -05001031 if (baseType.getQualifier().hasAttachment()) {
1032 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001033 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001034 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
1035 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001036 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001037 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
1038 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -06001039 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -05001040 }
John Kessenich5611c6d2018-04-05 11:25:02 -06001041 }
1042 }
1043}
1044
qining25262b32016-05-06 17:25:16 -04001045// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -07001046// descriptor set.
1047bool IsDescriptorResource(const glslang::TType& type)
1048{
John Kessenichf7497e22016-03-08 21:36:22 -07001049 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -07001050 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -07001051 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -07001052
1053 // non block...
1054 // basically samplerXXX/subpass/sampler/texture are all included
1055 // if they are the global-scope-class, not the function parameter
1056 // (or local, if they ever exist) class.
1057 if (type.getBasicType() == glslang::EbtSampler)
1058 return type.getQualifier().isUniformOrBuffer();
1059
1060 // None of the above.
1061 return false;
1062}
1063
John Kesseniche0b6cad2015-12-24 10:30:13 -07001064void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
1065{
1066 if (child.layoutMatrix == glslang::ElmNone)
1067 child.layoutMatrix = parent.layoutMatrix;
1068
1069 if (parent.invariant)
1070 child.invariant = true;
1071 if (parent.nopersp)
1072 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +08001073#ifdef AMD_EXTENSIONS
1074 if (parent.explicitInterp)
1075 child.explicitInterp = true;
1076#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -07001077 if (parent.flat)
1078 child.flat = true;
1079 if (parent.centroid)
1080 child.centroid = true;
1081 if (parent.patch)
1082 child.patch = true;
1083 if (parent.sample)
1084 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001085 if (parent.coherent)
1086 child.coherent = true;
Jeff Bolz36831c92018-09-05 10:11:41 -05001087 if (parent.devicecoherent)
1088 child.devicecoherent = true;
1089 if (parent.queuefamilycoherent)
1090 child.queuefamilycoherent = true;
1091 if (parent.workgroupcoherent)
1092 child.workgroupcoherent = true;
1093 if (parent.subgroupcoherent)
1094 child.subgroupcoherent = true;
1095 if (parent.nonprivate)
1096 child.nonprivate = true;
Rex Xu1da878f2016-02-21 20:59:01 +08001097 if (parent.volatil)
1098 child.volatil = true;
1099 if (parent.restrict)
1100 child.restrict = true;
1101 if (parent.readonly)
1102 child.readonly = true;
1103 if (parent.writeonly)
1104 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001105}
1106
John Kessenichf2b7f332016-09-01 17:05:23 -06001107bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001108{
John Kessenich7b9fa252016-01-21 18:56:57 -07001109 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001110 // - struct members might inherit from a struct declaration
1111 // (note that non-block structs don't explicitly inherit,
1112 // only implicitly, meaning no decoration involved)
1113 // - affect decorations on the struct members
1114 // (note smooth does not, and expecting something like volatile
1115 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001116 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001117 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001118}
1119
John Kessenich140f3df2015-06-26 16:58:36 -06001120//
1121// Implement the TGlslangToSpvTraverser class.
1122//
1123
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001124TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001125 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1126 : TIntermTraverser(true, false, true),
1127 options(options),
1128 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001129 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001130 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001131 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001132 glslangIntermediate(glslangIntermediate)
1133{
1134 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1135
1136 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001137 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1138 glslangIntermediate->getVersion());
1139
John Kessenich121853f2017-05-31 17:11:16 -06001140 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001141 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001142 builder.setSourceFile(glslangIntermediate->getSourceFile());
1143
1144 // Set the source shader's text. If for SPV version 1.0, include
1145 // a preamble in comments stating the OpModuleProcessed instructions.
1146 // Otherwise, emit those as actual instructions.
1147 std::string text;
1148 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1149 for (int p = 0; p < (int)processes.size(); ++p) {
1150 if (glslangIntermediate->getSpv().spv < 0x00010100) {
1151 text.append("// OpModuleProcessed ");
1152 text.append(processes[p]);
1153 text.append("\n");
1154 } else
1155 builder.addModuleProcessed(processes[p]);
1156 }
1157 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
1158 text.append("#line 1\n");
1159 text.append(glslangIntermediate->getSourceText());
1160 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -06001161 }
John Kessenich140f3df2015-06-26 16:58:36 -06001162 stdBuiltins = builder.import("GLSL.std.450");
Jeff Bolz36831c92018-09-05 10:11:41 -05001163 if (glslangIntermediate->usingVulkanMemoryModel()) {
1164 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelVulkanKHR);
1165 builder.addExtension(spv::E_SPV_KHR_vulkan_memory_model);
1166 } else {
1167 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
1168 }
John Kessenicheee9d532016-09-19 18:09:30 -06001169 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1170 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001171
1172 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001173 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1174 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001175 builder.addSourceExtension(it->c_str());
1176
1177 // Add the top-level modes for this shader.
1178
John Kessenich92187592016-02-01 13:45:25 -07001179 if (glslangIntermediate->getXfbMode()) {
1180 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001181 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001182 }
John Kessenich140f3df2015-06-26 16:58:36 -06001183
1184 unsigned int mode;
1185 switch (glslangIntermediate->getStage()) {
1186 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001187 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001188 break;
1189
steve-lunarge7412492017-03-23 11:56:07 -06001190 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001191 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001192 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001193
steve-lunarge7412492017-03-23 11:56:07 -06001194 glslang::TLayoutGeometry primitive;
1195
1196 if (glslangIntermediate->getStage() == EShLangTessControl) {
1197 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1198 primitive = glslangIntermediate->getOutputPrimitive();
1199 } else {
1200 primitive = glslangIntermediate->getInputPrimitive();
1201 }
1202
1203 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001204 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1205 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1206 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001207 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001208 }
John Kessenich4016e382016-07-15 11:53:56 -06001209 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001210 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1211
John Kesseniche6903322015-10-13 16:29:02 -06001212 switch (glslangIntermediate->getVertexSpacing()) {
1213 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1214 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1215 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001216 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001217 }
John Kessenich4016e382016-07-15 11:53:56 -06001218 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001219 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1220
1221 switch (glslangIntermediate->getVertexOrder()) {
1222 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1223 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; 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 if (glslangIntermediate->getPointMode())
1230 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001231 break;
1232
1233 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001234 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001235 switch (glslangIntermediate->getInputPrimitive()) {
1236 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1237 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1238 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001239 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001240 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001241 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001242 }
John Kessenich4016e382016-07-15 11:53:56 -06001243 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001244 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001245
John Kessenich140f3df2015-06-26 16:58:36 -06001246 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1247
1248 switch (glslangIntermediate->getOutputPrimitive()) {
1249 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1250 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1251 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001252 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001253 }
John Kessenich4016e382016-07-15 11:53:56 -06001254 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001255 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1256 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1257 break;
1258
1259 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001260 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001261 if (glslangIntermediate->getPixelCenterInteger())
1262 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001263
John Kessenich140f3df2015-06-26 16:58:36 -06001264 if (glslangIntermediate->getOriginUpperLeft())
1265 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001266 else
1267 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001268
1269 if (glslangIntermediate->getEarlyFragmentTests())
1270 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1271
chaocc1204522017-06-30 17:14:30 -07001272 if (glslangIntermediate->getPostDepthCoverage()) {
1273 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1274 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1275 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1276 }
1277
John Kesseniche6903322015-10-13 16:29:02 -06001278 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001279 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1280 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001281 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001282 }
John Kessenich4016e382016-07-15 11:53:56 -06001283 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001284 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1285
1286 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1287 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001288 break;
1289
1290 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001291 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001292 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1293 glslangIntermediate->getLocalSize(1),
1294 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001295 break;
1296
1297 default:
1298 break;
1299 }
John Kessenich140f3df2015-06-26 16:58:36 -06001300}
1301
John Kessenichfca82622016-11-26 13:23:20 -07001302// Finish creating SPV, after the traversal is complete.
1303void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001304{
John Kessenichf04c51b2018-08-03 15:56:12 -06001305 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001306 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001307 builder.setBuildPoint(shaderEntry->getLastBlock());
1308 builder.leaveFunction();
1309 }
1310
John Kessenich7ba63412015-12-20 17:37:07 -07001311 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001312 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1313 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001314
John Kessenichf04c51b2018-08-03 15:56:12 -06001315 // Add capabilities, extensions, remove unneeded decorations, etc.,
1316 // based on the resulting SPIR-V.
1317 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001318}
1319
John Kessenichfca82622016-11-26 13:23:20 -07001320// Write the SPV into 'out'.
1321void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001322{
John Kessenichfca82622016-11-26 13:23:20 -07001323 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001324}
1325
1326//
1327// Implement the traversal functions.
1328//
1329// Return true from interior nodes to have the external traversal
1330// continue on to children. Return false if children were
1331// already processed.
1332//
1333
1334//
qining25262b32016-05-06 17:25:16 -04001335// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001336// - uniform/input reads
1337// - output writes
1338// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1339// - something simple that degenerates into the last bullet
1340//
1341void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1342{
qining75d1d802016-04-06 14:42:01 -04001343 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1344 if (symbol->getType().getQualifier().isSpecConstant())
1345 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1346
John Kessenich140f3df2015-06-26 16:58:36 -06001347 // getSymbolId() will set up all the IO decorations on the first call.
1348 // Formal function parameters were mapped during makeFunctions().
1349 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001350
1351 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1352 if (builder.isPointer(id)) {
1353 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001354 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1355 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1356 iOSet.insert(id);
1357 }
John Kessenich7ba63412015-12-20 17:37:07 -07001358 }
1359
1360 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001361 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001362 // Prepare to generate code for the access
1363
1364 // L-value chains will be computed left to right. We're on the symbol now,
1365 // which is the left-most part of the access chain, so now is "clear" time,
1366 // followed by setting the base.
1367 builder.clearAccessChain();
1368
1369 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001370 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001371 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001372 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001373 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001374 // These are also pure R-values.
1375 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001376 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001377 builder.setAccessChainRValue(id);
1378 else
1379 builder.setAccessChainLValue(id);
1380 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001381
1382 // Process linkage-only nodes for any special additional interface work.
1383 if (linkageOnly) {
1384 if (glslangIntermediate->getHlslFunctionality1()) {
1385 // Map implicit counter buffers to their originating buffers, which should have been
1386 // seen by now, given earlier pruning of unused counters, and preservation of order
1387 // of declaration.
1388 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1389 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1390 // Save possible originating buffers for counter buffers, keyed by
1391 // making the potential counter-buffer name.
1392 std::string keyName = symbol->getName().c_str();
1393 keyName = glslangIntermediate->addCounterBufferName(keyName);
1394 counterOriginator[keyName] = symbol;
1395 } else {
1396 // Handle a counter buffer, by finding the saved originating buffer.
1397 std::string keyName = symbol->getName().c_str();
1398 auto it = counterOriginator.find(keyName);
1399 if (it != counterOriginator.end()) {
1400 id = getSymbolId(it->second);
1401 if (id != spv::NoResult) {
1402 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001403 if (counterId != spv::NoResult) {
1404 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001405 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001406 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001407 }
1408 }
1409 }
1410 }
1411 }
1412 }
John Kessenich140f3df2015-06-26 16:58:36 -06001413}
1414
1415bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1416{
John Kesseniche485c7a2017-05-31 18:50:53 -06001417 builder.setLine(node->getLoc().line);
1418
qining40887662016-04-03 22:20:42 -04001419 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1420 if (node->getType().getQualifier().isSpecConstant())
1421 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1422
John Kessenich140f3df2015-06-26 16:58:36 -06001423 // First, handle special cases
1424 switch (node->getOp()) {
1425 case glslang::EOpAssign:
1426 case glslang::EOpAddAssign:
1427 case glslang::EOpSubAssign:
1428 case glslang::EOpMulAssign:
1429 case glslang::EOpVectorTimesMatrixAssign:
1430 case glslang::EOpVectorTimesScalarAssign:
1431 case glslang::EOpMatrixTimesScalarAssign:
1432 case glslang::EOpMatrixTimesMatrixAssign:
1433 case glslang::EOpDivAssign:
1434 case glslang::EOpModAssign:
1435 case glslang::EOpAndAssign:
1436 case glslang::EOpInclusiveOrAssign:
1437 case glslang::EOpExclusiveOrAssign:
1438 case glslang::EOpLeftShiftAssign:
1439 case glslang::EOpRightShiftAssign:
1440 // A bin-op assign "a += b" means the same thing as "a = a + b"
1441 // where a is evaluated before b. For a simple assignment, GLSL
1442 // says to evaluate the left before the right. So, always, left
1443 // node then right node.
1444 {
1445 // get the left l-value, save it away
1446 builder.clearAccessChain();
1447 node->getLeft()->traverse(this);
1448 spv::Builder::AccessChain lValue = builder.getAccessChain();
1449
1450 // evaluate the right
1451 builder.clearAccessChain();
1452 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001453 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001454
1455 if (node->getOp() != glslang::EOpAssign) {
1456 // the left is also an r-value
1457 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001458 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001459
1460 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001461 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001462 TranslateNoContractionDecoration(node->getType().getQualifier()),
1463 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001464 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001465 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1466 node->getType().getBasicType());
1467
1468 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001469 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001470 }
1471
1472 // store the result
1473 builder.setAccessChain(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05001474 multiTypeStore(node->getLeft()->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001475
1476 // assignments are expressions having an rValue after they are evaluated...
1477 builder.clearAccessChain();
1478 builder.setAccessChainRValue(rValue);
1479 }
1480 return false;
1481 case glslang::EOpIndexDirect:
1482 case glslang::EOpIndexDirectStruct:
1483 {
1484 // Get the left part of the access chain.
1485 node->getLeft()->traverse(this);
1486
1487 // Add the next element in the chain
1488
David Netoa901ffe2016-06-08 14:11:40 +01001489 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001490 if (! node->getLeft()->getType().isArray() &&
1491 node->getLeft()->getType().isVector() &&
1492 node->getOp() == glslang::EOpIndexDirect) {
1493 // This is essentially a hard-coded vector swizzle of size 1,
1494 // so short circuit the access-chain stuff with a swizzle.
1495 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001496 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001497 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001498 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001499 int spvIndex = glslangIndex;
1500 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1501 node->getOp() == glslang::EOpIndexDirectStruct)
1502 {
1503 // This may be, e.g., an anonymous block-member selection, which generally need
1504 // index remapping due to hidden members in anonymous blocks.
1505 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1506 assert(remapper.size() > 0);
1507 spvIndex = remapper[glslangIndex];
1508 }
John Kessenichebb50532016-05-16 19:22:05 -06001509
David Netoa901ffe2016-06-08 14:11:40 +01001510 // normal case for indexing array or structure or block
Jeff Bolz36831c92018-09-05 10:11:41 -05001511 builder.accessChainPush(builder.makeIntConstant(spvIndex), TranslateCoherent(node->getLeft()->getType()));
David Netoa901ffe2016-06-08 14:11:40 +01001512
1513 // Add capabilities here for accessing PointSize and clip/cull distance.
1514 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001515 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001516 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001517 }
1518 }
1519 return false;
1520 case glslang::EOpIndexIndirect:
1521 {
1522 // Structure or array or vector indirection.
1523 // Will use native SPIR-V access-chain for struct and array indirection;
1524 // matrices are arrays of vectors, so will also work for a matrix.
1525 // Will use the access chain's 'component' for variable index into a vector.
1526
1527 // This adapter is building access chains left to right.
1528 // Set up the access chain to the left.
1529 node->getLeft()->traverse(this);
1530
1531 // save it so that computing the right side doesn't trash it
1532 spv::Builder::AccessChain partial = builder.getAccessChain();
1533
1534 // compute the next index in the chain
1535 builder.clearAccessChain();
1536 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001537 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001538
John Kessenich5611c6d2018-04-05 11:25:02 -06001539 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1540
John Kessenich140f3df2015-06-26 16:58:36 -06001541 // restore the saved access chain
1542 builder.setAccessChain(partial);
1543
1544 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001545 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001546 else
Jeff Bolz36831c92018-09-05 10:11:41 -05001547 builder.accessChainPush(index, TranslateCoherent(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001548 }
1549 return false;
1550 case glslang::EOpVectorSwizzle:
1551 {
1552 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001553 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001554 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001555 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001556 }
1557 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001558 case glslang::EOpMatrixSwizzle:
1559 logger->missingFunctionality("matrix swizzle");
1560 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001561 case glslang::EOpLogicalOr:
1562 case glslang::EOpLogicalAnd:
1563 {
1564
1565 // These may require short circuiting, but can sometimes be done as straight
1566 // binary operations. The right operand must be short circuited if it has
1567 // side effects, and should probably be if it is complex.
1568 if (isTrivial(node->getRight()->getAsTyped()))
1569 break; // handle below as a normal binary operation
1570 // otherwise, we need to do dynamic short circuiting on the right operand
1571 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1572 builder.clearAccessChain();
1573 builder.setAccessChainRValue(result);
1574 }
1575 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001576 default:
1577 break;
1578 }
1579
1580 // Assume generic binary op...
1581
John Kessenich32cfd492016-02-02 12:37:46 -07001582 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001583 builder.clearAccessChain();
1584 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001585 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001586
John Kessenich32cfd492016-02-02 12:37:46 -07001587 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001588 builder.clearAccessChain();
1589 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001590 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001591
John Kessenich32cfd492016-02-02 12:37:46 -07001592 // get result
John Kessenichead86222018-03-28 18:01:20 -06001593 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001594 TranslateNoContractionDecoration(node->getType().getQualifier()),
1595 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001596 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001597 convertGlslangToSpvType(node->getType()), left, right,
1598 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001599
John Kessenich50e57562015-12-21 21:21:11 -07001600 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001601 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001602 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001603 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001604 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001605 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001606 return false;
1607 }
John Kessenich140f3df2015-06-26 16:58:36 -06001608}
1609
1610bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1611{
John Kesseniche485c7a2017-05-31 18:50:53 -06001612 builder.setLine(node->getLoc().line);
1613
qining40887662016-04-03 22:20:42 -04001614 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1615 if (node->getType().getQualifier().isSpecConstant())
1616 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1617
John Kessenichfc51d282015-08-19 13:34:18 -06001618 spv::Id result = spv::NoResult;
1619
1620 // try texturing first
1621 result = createImageTextureFunctionCall(node);
1622 if (result != spv::NoResult) {
1623 builder.clearAccessChain();
1624 builder.setAccessChainRValue(result);
1625
1626 return false; // done with this node
1627 }
1628
1629 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001630
1631 if (node->getOp() == glslang::EOpArrayLength) {
1632 // Quite special; won't want to evaluate the operand.
1633
John Kessenich5611c6d2018-04-05 11:25:02 -06001634 // Currently, the front-end does not allow .length() on an array until it is sized,
1635 // except for the last block membeor of an SSBO.
1636 // TODO: If this changes, link-time sized arrays might show up here, and need their
1637 // size extracted.
1638
John Kessenichc9a80832015-09-12 12:17:44 -06001639 // Normal .length() would have been constant folded by the front-end.
1640 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001641 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001642
John Kessenichc9a80832015-09-12 12:17:44 -06001643 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1644 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001645 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1646 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001647
1648 builder.clearAccessChain();
1649 builder.setAccessChainRValue(length);
1650
1651 return false;
1652 }
1653
John Kessenichfc51d282015-08-19 13:34:18 -06001654 // Start by evaluating the operand
1655
John Kessenich8c8505c2016-07-26 12:50:38 -06001656 // Does it need a swizzle inversion? If so, evaluation is inverted;
1657 // operate first on the swizzle base, then apply the swizzle.
1658 spv::Id invertedType = spv::NoType;
1659 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1660 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1661 invertedType = getInvertedSwizzleType(*node->getOperand());
1662
John Kessenich140f3df2015-06-26 16:58:36 -06001663 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001664 if (invertedType != spv::NoType)
1665 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1666 else
1667 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001668
Rex Xufc618912015-09-09 16:42:49 +08001669 spv::Id operand = spv::NoResult;
1670
1671 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1672 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001673 node->getOp() == glslang::EOpAtomicCounter ||
1674 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001675 operand = builder.accessChainGetLValue(); // Special case l-value operands
1676 else
John Kessenich32cfd492016-02-02 12:37:46 -07001677 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001678
John Kessenichead86222018-03-28 18:01:20 -06001679 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001680 TranslateNoContractionDecoration(node->getType().getQualifier()),
1681 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001682
1683 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001684 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001685 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001686
1687 // if not, then possibly an operation
1688 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001689 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001690
1691 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001692 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001693 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001694 builder.addDecoration(result, decorations.nonUniform);
1695 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001696
John Kessenich140f3df2015-06-26 16:58:36 -06001697 builder.clearAccessChain();
1698 builder.setAccessChainRValue(result);
1699
1700 return false; // done with this node
1701 }
1702
1703 // it must be a special case, check...
1704 switch (node->getOp()) {
1705 case glslang::EOpPostIncrement:
1706 case glslang::EOpPostDecrement:
1707 case glslang::EOpPreIncrement:
1708 case glslang::EOpPreDecrement:
1709 {
1710 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001711 spv::Id one = 0;
1712 if (node->getBasicType() == glslang::EbtFloat)
1713 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001714 else if (node->getBasicType() == glslang::EbtDouble)
1715 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001716 else if (node->getBasicType() == glslang::EbtFloat16)
1717 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001718 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1719 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001720 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1721 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001722 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1723 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001724 else
1725 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001726 glslang::TOperator op;
1727 if (node->getOp() == glslang::EOpPreIncrement ||
1728 node->getOp() == glslang::EOpPostIncrement)
1729 op = glslang::EOpAdd;
1730 else
1731 op = glslang::EOpSub;
1732
John Kessenichead86222018-03-28 18:01:20 -06001733 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001734 convertGlslangToSpvType(node->getType()), operand, one,
1735 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001736 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001737
1738 // The result of operation is always stored, but conditionally the
1739 // consumed result. The consumed result is always an r-value.
1740 builder.accessChainStore(result);
1741 builder.clearAccessChain();
1742 if (node->getOp() == glslang::EOpPreIncrement ||
1743 node->getOp() == glslang::EOpPreDecrement)
1744 builder.setAccessChainRValue(result);
1745 else
1746 builder.setAccessChainRValue(operand);
1747 }
1748
1749 return false;
1750
1751 case glslang::EOpEmitStreamVertex:
1752 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1753 return false;
1754 case glslang::EOpEndStreamPrimitive:
1755 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1756 return false;
1757
1758 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001759 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001760 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001761 }
John Kessenich140f3df2015-06-26 16:58:36 -06001762}
1763
1764bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1765{
qining27e04a02016-04-14 16:40:20 -04001766 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1767 if (node->getType().getQualifier().isSpecConstant())
1768 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1769
John Kessenichfc51d282015-08-19 13:34:18 -06001770 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001771 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1772 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001773
1774 // try texturing
1775 result = createImageTextureFunctionCall(node);
1776 if (result != spv::NoResult) {
1777 builder.clearAccessChain();
1778 builder.setAccessChainRValue(result);
1779
1780 return false;
Jeff Bolz36831c92018-09-05 10:11:41 -05001781 } else if (node->getOp() == glslang::EOpImageStore ||
Rex Xu129799a2017-07-05 17:23:28 +08001782#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05001783 node->getOp() == glslang::EOpImageStoreLod ||
Rex Xu129799a2017-07-05 17:23:28 +08001784#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05001785 node->getOp() == glslang::EOpImageAtomicStore) {
Rex Xufc618912015-09-09 16:42:49 +08001786 // "imageStore" is a special case, which has no result
1787 return false;
1788 }
John Kessenichfc51d282015-08-19 13:34:18 -06001789
John Kessenich140f3df2015-06-26 16:58:36 -06001790 glslang::TOperator binOp = glslang::EOpNull;
1791 bool reduceComparison = true;
1792 bool isMatrix = false;
1793 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001794 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001795
1796 assert(node->getOp());
1797
John Kessenichf6640762016-08-01 19:44:00 -06001798 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001799
1800 switch (node->getOp()) {
1801 case glslang::EOpSequence:
1802 {
1803 if (preVisit)
1804 ++sequenceDepth;
1805 else
1806 --sequenceDepth;
1807
1808 if (sequenceDepth == 1) {
1809 // If this is the parent node of all the functions, we want to see them
1810 // early, so all call points have actual SPIR-V functions to reference.
1811 // In all cases, still let the traverser visit the children for us.
1812 makeFunctions(node->getAsAggregate()->getSequence());
1813
John Kessenich6fccb3c2016-09-19 16:01:41 -06001814 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001815 // anything else gets there, so visit out of order, doing them all now.
1816 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1817
John Kessenich6a60c2f2016-12-08 21:01:59 -07001818 // 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 -06001819 // so do them manually.
1820 visitFunctions(node->getAsAggregate()->getSequence());
1821
1822 return false;
1823 }
1824
1825 return true;
1826 }
1827 case glslang::EOpLinkerObjects:
1828 {
1829 if (visit == glslang::EvPreVisit)
1830 linkageOnly = true;
1831 else
1832 linkageOnly = false;
1833
1834 return true;
1835 }
1836 case glslang::EOpComma:
1837 {
1838 // processing from left to right naturally leaves the right-most
1839 // lying around in the access chain
1840 glslang::TIntermSequence& glslangOperands = node->getSequence();
1841 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1842 glslangOperands[i]->traverse(this);
1843
1844 return false;
1845 }
1846 case glslang::EOpFunction:
1847 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001848 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001849 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001850 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001851 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001852 } else {
1853 handleFunctionEntry(node);
1854 }
1855 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001856 if (inEntryPoint)
1857 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001858 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001859 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001860 }
1861
1862 return true;
1863 case glslang::EOpParameters:
1864 // Parameters will have been consumed by EOpFunction processing, but not
1865 // the body, so we still visited the function node's children, making this
1866 // child redundant.
1867 return false;
1868 case glslang::EOpFunctionCall:
1869 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001870 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001871 if (node->isUserDefined())
1872 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001873 // 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 -07001874 if (result) {
1875 builder.clearAccessChain();
1876 builder.setAccessChainRValue(result);
1877 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001878 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001879
1880 return false;
1881 }
1882 case glslang::EOpConstructMat2x2:
1883 case glslang::EOpConstructMat2x3:
1884 case glslang::EOpConstructMat2x4:
1885 case glslang::EOpConstructMat3x2:
1886 case glslang::EOpConstructMat3x3:
1887 case glslang::EOpConstructMat3x4:
1888 case glslang::EOpConstructMat4x2:
1889 case glslang::EOpConstructMat4x3:
1890 case glslang::EOpConstructMat4x4:
1891 case glslang::EOpConstructDMat2x2:
1892 case glslang::EOpConstructDMat2x3:
1893 case glslang::EOpConstructDMat2x4:
1894 case glslang::EOpConstructDMat3x2:
1895 case glslang::EOpConstructDMat3x3:
1896 case glslang::EOpConstructDMat3x4:
1897 case glslang::EOpConstructDMat4x2:
1898 case glslang::EOpConstructDMat4x3:
1899 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001900 case glslang::EOpConstructIMat2x2:
1901 case glslang::EOpConstructIMat2x3:
1902 case glslang::EOpConstructIMat2x4:
1903 case glslang::EOpConstructIMat3x2:
1904 case glslang::EOpConstructIMat3x3:
1905 case glslang::EOpConstructIMat3x4:
1906 case glslang::EOpConstructIMat4x2:
1907 case glslang::EOpConstructIMat4x3:
1908 case glslang::EOpConstructIMat4x4:
1909 case glslang::EOpConstructUMat2x2:
1910 case glslang::EOpConstructUMat2x3:
1911 case glslang::EOpConstructUMat2x4:
1912 case glslang::EOpConstructUMat3x2:
1913 case glslang::EOpConstructUMat3x3:
1914 case glslang::EOpConstructUMat3x4:
1915 case glslang::EOpConstructUMat4x2:
1916 case glslang::EOpConstructUMat4x3:
1917 case glslang::EOpConstructUMat4x4:
1918 case glslang::EOpConstructBMat2x2:
1919 case glslang::EOpConstructBMat2x3:
1920 case glslang::EOpConstructBMat2x4:
1921 case glslang::EOpConstructBMat3x2:
1922 case glslang::EOpConstructBMat3x3:
1923 case glslang::EOpConstructBMat3x4:
1924 case glslang::EOpConstructBMat4x2:
1925 case glslang::EOpConstructBMat4x3:
1926 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001927 case glslang::EOpConstructF16Mat2x2:
1928 case glslang::EOpConstructF16Mat2x3:
1929 case glslang::EOpConstructF16Mat2x4:
1930 case glslang::EOpConstructF16Mat3x2:
1931 case glslang::EOpConstructF16Mat3x3:
1932 case glslang::EOpConstructF16Mat3x4:
1933 case glslang::EOpConstructF16Mat4x2:
1934 case glslang::EOpConstructF16Mat4x3:
1935 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06001936 isMatrix = true;
1937 // fall through
1938 case glslang::EOpConstructFloat:
1939 case glslang::EOpConstructVec2:
1940 case glslang::EOpConstructVec3:
1941 case glslang::EOpConstructVec4:
1942 case glslang::EOpConstructDouble:
1943 case glslang::EOpConstructDVec2:
1944 case glslang::EOpConstructDVec3:
1945 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001946 case glslang::EOpConstructFloat16:
1947 case glslang::EOpConstructF16Vec2:
1948 case glslang::EOpConstructF16Vec3:
1949 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001950 case glslang::EOpConstructBool:
1951 case glslang::EOpConstructBVec2:
1952 case glslang::EOpConstructBVec3:
1953 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07001954 case glslang::EOpConstructInt8:
1955 case glslang::EOpConstructI8Vec2:
1956 case glslang::EOpConstructI8Vec3:
1957 case glslang::EOpConstructI8Vec4:
1958 case glslang::EOpConstructUint8:
1959 case glslang::EOpConstructU8Vec2:
1960 case glslang::EOpConstructU8Vec3:
1961 case glslang::EOpConstructU8Vec4:
1962 case glslang::EOpConstructInt16:
1963 case glslang::EOpConstructI16Vec2:
1964 case glslang::EOpConstructI16Vec3:
1965 case glslang::EOpConstructI16Vec4:
1966 case glslang::EOpConstructUint16:
1967 case glslang::EOpConstructU16Vec2:
1968 case glslang::EOpConstructU16Vec3:
1969 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001970 case glslang::EOpConstructInt:
1971 case glslang::EOpConstructIVec2:
1972 case glslang::EOpConstructIVec3:
1973 case glslang::EOpConstructIVec4:
1974 case glslang::EOpConstructUint:
1975 case glslang::EOpConstructUVec2:
1976 case glslang::EOpConstructUVec3:
1977 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001978 case glslang::EOpConstructInt64:
1979 case glslang::EOpConstructI64Vec2:
1980 case glslang::EOpConstructI64Vec3:
1981 case glslang::EOpConstructI64Vec4:
1982 case glslang::EOpConstructUint64:
1983 case glslang::EOpConstructU64Vec2:
1984 case glslang::EOpConstructU64Vec3:
1985 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001986 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001987 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001988 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001989 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001990 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001991 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001992 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001993 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001994 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001995 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001996 std::vector<spv::Id> constituents;
1997 for (int c = 0; c < (int)arguments.size(); ++c)
1998 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001999 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07002000 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06002001 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07002002 else
John Kessenich8c8505c2016-07-26 12:50:38 -06002003 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06002004
2005 builder.clearAccessChain();
2006 builder.setAccessChainRValue(constructed);
2007
2008 return false;
2009 }
2010
2011 // These six are component-wise compares with component-wise results.
2012 // Forward on to createBinaryOperation(), requesting a vector result.
2013 case glslang::EOpLessThan:
2014 case glslang::EOpGreaterThan:
2015 case glslang::EOpLessThanEqual:
2016 case glslang::EOpGreaterThanEqual:
2017 case glslang::EOpVectorEqual:
2018 case glslang::EOpVectorNotEqual:
2019 {
2020 // Map the operation to a binary
2021 binOp = node->getOp();
2022 reduceComparison = false;
2023 switch (node->getOp()) {
2024 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
2025 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
2026 default: binOp = node->getOp(); break;
2027 }
2028
2029 break;
2030 }
2031 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06002032 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002033 binOp = glslang::EOpMul;
2034 break;
2035 case glslang::EOpOuterProduct:
2036 // two vectors multiplied to make a matrix
2037 binOp = glslang::EOpOuterProduct;
2038 break;
2039 case glslang::EOpDot:
2040 {
qining25262b32016-05-06 17:25:16 -04002041 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06002042 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06002043 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06002044 binOp = glslang::EOpMul;
2045 break;
2046 }
2047 case glslang::EOpMod:
2048 // when an aggregate, this is the floating-point mod built-in function,
2049 // which can be emitted by the one in createBinaryOperation()
2050 binOp = glslang::EOpMod;
2051 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002052 case glslang::EOpEmitVertex:
2053 case glslang::EOpEndPrimitive:
2054 case glslang::EOpBarrier:
2055 case glslang::EOpMemoryBarrier:
2056 case glslang::EOpMemoryBarrierAtomicCounter:
2057 case glslang::EOpMemoryBarrierBuffer:
2058 case glslang::EOpMemoryBarrierImage:
2059 case glslang::EOpMemoryBarrierShared:
2060 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07002061 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002062 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07002063 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06002064 case glslang::EOpWorkgroupMemoryBarrier:
2065 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07002066 case glslang::EOpSubgroupBarrier:
2067 case glslang::EOpSubgroupMemoryBarrier:
2068 case glslang::EOpSubgroupMemoryBarrierBuffer:
2069 case glslang::EOpSubgroupMemoryBarrierImage:
2070 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06002071 noReturnValue = true;
2072 // These all have 0 operands and will naturally finish up in the code below for 0 operands
2073 break;
2074
Jeff Bolz36831c92018-09-05 10:11:41 -05002075 case glslang::EOpAtomicStore:
2076 noReturnValue = true;
2077 // fallthrough
2078 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06002079 case glslang::EOpAtomicAdd:
2080 case glslang::EOpAtomicMin:
2081 case glslang::EOpAtomicMax:
2082 case glslang::EOpAtomicAnd:
2083 case glslang::EOpAtomicOr:
2084 case glslang::EOpAtomicXor:
2085 case glslang::EOpAtomicExchange:
2086 case glslang::EOpAtomicCompSwap:
2087 atomic = true;
2088 break;
2089
John Kessenich0d0c6d32017-07-23 16:08:26 -06002090 case glslang::EOpAtomicCounterAdd:
2091 case glslang::EOpAtomicCounterSubtract:
2092 case glslang::EOpAtomicCounterMin:
2093 case glslang::EOpAtomicCounterMax:
2094 case glslang::EOpAtomicCounterAnd:
2095 case glslang::EOpAtomicCounterOr:
2096 case glslang::EOpAtomicCounterXor:
2097 case glslang::EOpAtomicCounterExchange:
2098 case glslang::EOpAtomicCounterCompSwap:
2099 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
2100 builder.addCapability(spv::CapabilityAtomicStorageOps);
2101 atomic = true;
2102 break;
2103
John Kessenich140f3df2015-06-26 16:58:36 -06002104 default:
2105 break;
2106 }
2107
2108 //
2109 // See if it maps to a regular operation.
2110 //
John Kessenich140f3df2015-06-26 16:58:36 -06002111 if (binOp != glslang::EOpNull) {
2112 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
2113 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
2114 assert(left && right);
2115
2116 builder.clearAccessChain();
2117 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002118 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002119
2120 builder.clearAccessChain();
2121 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002122 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002123
John Kesseniche485c7a2017-05-31 18:50:53 -06002124 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06002125 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002126 TranslateNoContractionDecoration(node->getType().getQualifier()),
2127 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002128 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002129 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002130 left->getType().getBasicType(), reduceComparison);
2131
2132 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002133 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002134 builder.clearAccessChain();
2135 builder.setAccessChainRValue(result);
2136
2137 return false;
2138 }
2139
John Kessenich426394d2015-07-23 10:22:48 -06002140 //
2141 // Create the list of operands.
2142 //
John Kessenich140f3df2015-06-26 16:58:36 -06002143 glslang::TIntermSequence& glslangOperands = node->getSequence();
2144 std::vector<spv::Id> operands;
2145 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002146 // special case l-value operands; there are just a few
2147 bool lvalue = false;
2148 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002149 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002150 case glslang::EOpModf:
2151 if (arg == 1)
2152 lvalue = true;
2153 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002154 case glslang::EOpInterpolateAtSample:
2155 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002156#ifdef AMD_EXTENSIONS
2157 case glslang::EOpInterpolateAtVertex:
2158#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002159 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002160 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002161
2162 // Does it need a swizzle inversion? If so, evaluation is inverted;
2163 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002164 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002165 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2166 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2167 }
Rex Xu7a26c172015-12-08 17:12:09 +08002168 break;
Rex Xud4782c12015-09-06 16:30:11 +08002169 case glslang::EOpAtomicAdd:
2170 case glslang::EOpAtomicMin:
2171 case glslang::EOpAtomicMax:
2172 case glslang::EOpAtomicAnd:
2173 case glslang::EOpAtomicOr:
2174 case glslang::EOpAtomicXor:
2175 case glslang::EOpAtomicExchange:
2176 case glslang::EOpAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05002177 case glslang::EOpAtomicLoad:
2178 case glslang::EOpAtomicStore:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002179 case glslang::EOpAtomicCounterAdd:
2180 case glslang::EOpAtomicCounterSubtract:
2181 case glslang::EOpAtomicCounterMin:
2182 case glslang::EOpAtomicCounterMax:
2183 case glslang::EOpAtomicCounterAnd:
2184 case glslang::EOpAtomicCounterOr:
2185 case glslang::EOpAtomicCounterXor:
2186 case glslang::EOpAtomicCounterExchange:
2187 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002188 if (arg == 0)
2189 lvalue = true;
2190 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002191 case glslang::EOpAddCarry:
2192 case glslang::EOpSubBorrow:
2193 if (arg == 2)
2194 lvalue = true;
2195 break;
2196 case glslang::EOpUMulExtended:
2197 case glslang::EOpIMulExtended:
2198 if (arg >= 2)
2199 lvalue = true;
2200 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002201 default:
2202 break;
2203 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002204 builder.clearAccessChain();
2205 if (invertedType != spv::NoType && arg == 0)
2206 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2207 else
2208 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002209 if (lvalue)
2210 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002211 else {
2212 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002213 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002214 }
John Kessenich140f3df2015-06-26 16:58:36 -06002215 }
John Kessenich426394d2015-07-23 10:22:48 -06002216
John Kesseniche485c7a2017-05-31 18:50:53 -06002217 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002218 if (atomic) {
2219 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002220 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002221 } else {
2222 // Pass through to generic operations.
2223 switch (glslangOperands.size()) {
2224 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002225 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002226 break;
2227 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002228 {
2229 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002230 TranslateNoContractionDecoration(node->getType().getQualifier()),
2231 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002232 result = createUnaryOperation(
2233 node->getOp(), decorations,
2234 resultType(), operands.front(),
2235 glslangOperands[0]->getAsTyped()->getBasicType());
2236 }
John Kessenich426394d2015-07-23 10:22:48 -06002237 break;
2238 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002239 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002240 break;
2241 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002242 if (invertedType)
2243 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002244 }
2245
2246 if (noReturnValue)
2247 return false;
2248
2249 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002250 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002251 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002252 } else {
2253 builder.clearAccessChain();
2254 builder.setAccessChainRValue(result);
2255 return false;
2256 }
2257}
2258
John Kessenich433e9ff2017-01-26 20:31:11 -07002259// This path handles both if-then-else and ?:
2260// The if-then-else has a node type of void, while
2261// ?: has either a void or a non-void node type
2262//
2263// Leaving the result, when not void:
2264// GLSL only has r-values as the result of a :?, but
2265// if we have an l-value, that can be more efficient if it will
2266// become the base of a complex r-value expression, because the
2267// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002268bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2269{
John Kessenich4bee5312018-02-20 21:29:05 -07002270 // See if it simple and safe, or required, to execute both sides.
2271 // Crucially, side effects must be either semantically required or avoided,
2272 // and there are performance trade-offs.
2273 // Return true if required or a good idea (and safe) to execute both sides,
2274 // false otherwise.
2275 const auto bothSidesPolicy = [&]() -> bool {
2276 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002277 if (node->getTrueBlock() == nullptr ||
2278 node->getFalseBlock() == nullptr)
2279 return false;
2280
John Kessenich4bee5312018-02-20 21:29:05 -07002281 // required? (unless we write additional code to look for side effects
2282 // and make performance trade-offs if none are present)
2283 if (!node->getShortCircuit())
2284 return true;
2285
2286 // if not required to execute both, decide based on performance/practicality...
2287
2288 // see if OpSelect can handle it
2289 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2290 node->getBasicType() == glslang::EbtVoid)
2291 return false;
2292
John Kessenich433e9ff2017-01-26 20:31:11 -07002293 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2294 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2295
2296 // return true if a single operand to ? : is okay for OpSelect
2297 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002298 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002299 };
2300
2301 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2302 operandOkay(node->getFalseBlock()->getAsTyped());
2303 };
2304
John Kessenich4bee5312018-02-20 21:29:05 -07002305 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2306 // emit the condition before doing anything with selection
2307 node->getCondition()->traverse(this);
2308 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2309
2310 // Find a way of executing both sides and selecting the right result.
2311 const auto executeBothSides = [&]() -> void {
2312 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002313 node->getTrueBlock()->traverse(this);
2314 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2315 node->getFalseBlock()->traverse(this);
2316 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2317
John Kesseniche485c7a2017-05-31 18:50:53 -06002318 builder.setLine(node->getLoc().line);
2319
John Kessenich4bee5312018-02-20 21:29:05 -07002320 // done if void
2321 if (node->getBasicType() == glslang::EbtVoid)
2322 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002323
John Kessenich4bee5312018-02-20 21:29:05 -07002324 // emit code to select between trueValue and falseValue
2325
2326 // see if OpSelect can handle it
2327 if (node->getType().isScalar() || node->getType().isVector()) {
2328 // Emit OpSelect for this selection.
2329
2330 // smear condition to vector, if necessary (AST is always scalar)
2331 if (builder.isVector(trueValue))
2332 condition = builder.smearScalar(spv::NoPrecision, condition,
2333 builder.makeVectorType(builder.makeBoolType(),
2334 builder.getNumComponents(trueValue)));
2335
2336 // OpSelect
2337 result = builder.createTriOp(spv::OpSelect,
2338 convertGlslangToSpvType(node->getType()), condition,
2339 trueValue, falseValue);
2340
2341 builder.clearAccessChain();
2342 builder.setAccessChainRValue(result);
2343 } else {
2344 // We need control flow to select the result.
2345 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2346 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2347
2348 // Selection control:
2349 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2350
2351 // make an "if" based on the value created by the condition
2352 spv::Builder::If ifBuilder(condition, control, builder);
2353
2354 // emit the "then" statement
2355 builder.createStore(trueValue, result);
2356 ifBuilder.makeBeginElse();
2357 // emit the "else" statement
2358 builder.createStore(falseValue, result);
2359
2360 // finish off the control flow
2361 ifBuilder.makeEndIf();
2362
2363 builder.clearAccessChain();
2364 builder.setAccessChainLValue(result);
2365 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002366 };
2367
John Kessenich4bee5312018-02-20 21:29:05 -07002368 // Execute the one side needed, as per the condition
2369 const auto executeOneSide = [&]() {
2370 // Always emit control flow.
2371 if (node->getBasicType() != glslang::EbtVoid)
2372 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002373
John Kessenich4bee5312018-02-20 21:29:05 -07002374 // Selection control:
2375 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2376
2377 // make an "if" based on the value created by the condition
2378 spv::Builder::If ifBuilder(condition, control, builder);
2379
2380 // emit the "then" statement
2381 if (node->getTrueBlock() != nullptr) {
2382 node->getTrueBlock()->traverse(this);
2383 if (result != spv::NoResult)
2384 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2385 }
2386
2387 if (node->getFalseBlock() != nullptr) {
2388 ifBuilder.makeBeginElse();
2389 // emit the "else" statement
2390 node->getFalseBlock()->traverse(this);
2391 if (result != spv::NoResult)
2392 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2393 }
2394
2395 // finish off the control flow
2396 ifBuilder.makeEndIf();
2397
2398 if (result != spv::NoResult) {
2399 builder.clearAccessChain();
2400 builder.setAccessChainLValue(result);
2401 }
2402 };
2403
2404 // Try for OpSelect (or a requirement to execute both sides)
2405 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002406 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2407 if (node->getType().getQualifier().isSpecConstant())
2408 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002409 executeBothSides();
2410 } else
2411 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002412
2413 return false;
2414}
2415
2416bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2417{
2418 // emit and get the condition before doing anything with switch
2419 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002420 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002421
Rex Xu57e65922017-07-04 23:23:40 +08002422 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002423 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002424
John Kessenich140f3df2015-06-26 16:58:36 -06002425 // browse the children to sort out code segments
2426 int defaultSegment = -1;
2427 std::vector<TIntermNode*> codeSegments;
2428 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2429 std::vector<int> caseValues;
2430 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2431 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2432 TIntermNode* child = *c;
2433 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002434 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002435 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002436 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002437 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2438 } else
2439 codeSegments.push_back(child);
2440 }
2441
qining25262b32016-05-06 17:25:16 -04002442 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002443 // statements between the last case and the end of the switch statement
2444 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2445 (int)codeSegments.size() == defaultSegment)
2446 codeSegments.push_back(nullptr);
2447
2448 // make the switch statement
2449 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002450 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002451
2452 // emit all the code in the segments
2453 breakForLoop.push(false);
2454 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2455 builder.nextSwitchSegment(segmentBlocks, s);
2456 if (codeSegments[s])
2457 codeSegments[s]->traverse(this);
2458 else
2459 builder.addSwitchBreak();
2460 }
2461 breakForLoop.pop();
2462
2463 builder.endSwitch(segmentBlocks);
2464
2465 return false;
2466}
2467
2468void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2469{
2470 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002471 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002472
2473 builder.clearAccessChain();
2474 builder.setAccessChainRValue(constant);
2475}
2476
2477bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2478{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002479 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002480 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002481
2482 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002483 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2484 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002485
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002486 // Spec requires back edges to target header blocks, and every header block
2487 // must dominate its merge block. Make a header block first to ensure these
2488 // conditions are met. By definition, it will contain OpLoopMerge, followed
2489 // by a block-ending branch. But we don't want to put any other body/test
2490 // instructions in it, since the body/test may have arbitrary instructions,
2491 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002492 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002493 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002494 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002495 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002496 spv::Block& test = builder.makeNewBlock();
2497 builder.createBranch(&test);
2498
2499 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002500 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002501 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002502 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2503
2504 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002505 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002506 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002507 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002508 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002509 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002510
2511 builder.setBuildPoint(&blocks.continue_target);
2512 if (node->getTerminal())
2513 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002514 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002515 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002516 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002517 builder.createBranch(&blocks.body);
2518
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002519 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002520 builder.setBuildPoint(&blocks.body);
2521 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002522 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002523 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002524 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002525
2526 builder.setBuildPoint(&blocks.continue_target);
2527 if (node->getTerminal())
2528 node->getTerminal()->traverse(this);
2529 if (node->getTest()) {
2530 node->getTest()->traverse(this);
2531 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002532 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002533 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002534 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002535 // TODO: unless there was a break/return/discard instruction
2536 // somewhere in the body, this is an infinite loop, so we should
2537 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002538 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002539 }
John Kessenich140f3df2015-06-26 16:58:36 -06002540 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002541 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002542 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002543 return false;
2544}
2545
2546bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2547{
2548 if (node->getExpression())
2549 node->getExpression()->traverse(this);
2550
John Kesseniche485c7a2017-05-31 18:50:53 -06002551 builder.setLine(node->getLoc().line);
2552
John Kessenich140f3df2015-06-26 16:58:36 -06002553 switch (node->getFlowOp()) {
2554 case glslang::EOpKill:
2555 builder.makeDiscard();
2556 break;
2557 case glslang::EOpBreak:
2558 if (breakForLoop.top())
2559 builder.createLoopExit();
2560 else
2561 builder.addSwitchBreak();
2562 break;
2563 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002564 builder.createLoopContinue();
2565 break;
2566 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002567 if (node->getExpression()) {
2568 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2569 spv::Id returnId = accessChainLoad(glslangReturnType);
2570 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2571 builder.clearAccessChain();
2572 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2573 builder.setAccessChainLValue(copyId);
2574 multiTypeStore(glslangReturnType, returnId);
2575 returnId = builder.createLoad(copyId);
2576 }
2577 builder.makeReturn(false, returnId);
2578 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002579 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002580
2581 builder.clearAccessChain();
2582 break;
2583
2584 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002585 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002586 break;
2587 }
2588
2589 return false;
2590}
2591
2592spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2593{
qining25262b32016-05-06 17:25:16 -04002594 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002595 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002596 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002597 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002598 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002599 }
2600
2601 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002602 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002603 spv::Id spvType = convertGlslangToSpvType(node->getType());
2604
Rex Xucabbb782017-03-24 13:41:14 +08002605 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2606 node->getType().containsBasicType(glslang::EbtInt16) ||
2607 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002608 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002609 switch (storageClass) {
2610 case spv::StorageClassInput:
2611 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002612 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002613 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002614 break;
2615 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002616 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002617 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002618 break;
2619 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002620 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002621 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2622 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002623 else
2624 builder.addCapability(spv::CapabilityStorageUniform16);
2625 break;
2626 case spv::StorageClassStorageBuffer:
2627 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2628 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2629 break;
2630 default:
2631 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002632 }
2633 }
Rex Xuf89ad982017-04-07 23:22:33 +08002634
John Kessenich312dcfb2018-07-03 13:19:51 -06002635 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2636 node->getType().containsBasicType(glslang::EbtUint8);
2637 if (contains8BitType) {
2638 if (storageClass == spv::StorageClassPushConstant) {
2639 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2640 builder.addCapability(spv::CapabilityStoragePushConstant8);
2641 } else if (storageClass == spv::StorageClassUniform) {
2642 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2643 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
2644 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2645 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
2646 }
2647 }
2648
John Kessenich140f3df2015-06-26 16:58:36 -06002649 const char* name = node->getName().c_str();
2650 if (glslang::IsAnonymous(name))
2651 name = "";
2652
2653 return builder.createVariable(storageClass, spvType, name);
2654}
2655
2656// Return type Id of the sampled type.
2657spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2658{
2659 switch (sampler.type) {
2660 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002661#ifdef AMD_EXTENSIONS
2662 case glslang::EbtFloat16:
2663 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2664 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2665 return builder.makeFloatType(16);
2666#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002667 case glslang::EbtInt: return builder.makeIntType(32);
2668 case glslang::EbtUint: return builder.makeUintType(32);
2669 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002670 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002671 return builder.makeFloatType(32);
2672 }
2673}
2674
John Kessenich8c8505c2016-07-26 12:50:38 -06002675// If node is a swizzle operation, return the type that should be used if
2676// the swizzle base is first consumed by another operation, before the swizzle
2677// is applied.
2678spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2679{
John Kessenichecba76f2017-01-06 00:34:48 -07002680 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002681 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2682 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2683 else
2684 return spv::NoType;
2685}
2686
2687// When inverting a swizzle with a parent op, this function
2688// will apply the swizzle operation to a completed parent operation.
2689spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2690{
2691 std::vector<unsigned> swizzle;
2692 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2693 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2694}
2695
John Kessenich8c8505c2016-07-26 12:50:38 -06002696// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2697void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2698{
2699 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2700 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2701 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2702}
2703
John Kessenich3ac051e2015-12-20 11:29:16 -07002704// Convert from a glslang type to an SPV type, by calling into a
2705// recursive version of this function. This establishes the inherited
2706// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002707spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2708{
John Kessenichead86222018-03-28 18:01:20 -06002709 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002710}
2711
2712// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002713// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002714// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002715spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2716 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002717{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002718 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002719
2720 switch (type.getBasicType()) {
2721 case glslang::EbtVoid:
2722 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002723 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002724 break;
2725 case glslang::EbtFloat:
2726 spvType = builder.makeFloatType(32);
2727 break;
2728 case glslang::EbtDouble:
2729 spvType = builder.makeFloatType(64);
2730 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002731 case glslang::EbtFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002732 spvType = builder.makeFloatType(16);
2733 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002734 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002735 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2736 // a 32-bit int where non-0 means true.
2737 if (explicitLayout != glslang::ElpNone)
2738 spvType = builder.makeUintType(32);
2739 else
2740 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002741 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002742 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07002743 spvType = builder.makeIntType(8);
2744 break;
2745 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07002746 spvType = builder.makeUintType(8);
2747 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002748 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07002749 spvType = builder.makeIntType(16);
2750 break;
2751 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07002752 spvType = builder.makeUintType(16);
2753 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002754 case glslang::EbtInt:
2755 spvType = builder.makeIntType(32);
2756 break;
2757 case glslang::EbtUint:
2758 spvType = builder.makeUintType(32);
2759 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002760 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002761 spvType = builder.makeIntType(64);
2762 break;
2763 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002764 spvType = builder.makeUintType(64);
2765 break;
John Kessenich426394d2015-07-23 10:22:48 -06002766 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002767 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002768 spvType = builder.makeUintType(32);
2769 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002770 case glslang::EbtSampler:
2771 {
2772 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002773 if (sampler.sampler) {
2774 // pure sampler
2775 spvType = builder.makeSamplerType();
2776 } else {
2777 // an image is present, make its type
2778 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2779 sampler.image ? 2 : 1, TranslateImageFormat(type));
2780 if (sampler.combined) {
2781 // already has both image and sampler, make the combined type
2782 spvType = builder.makeSampledImageType(spvType);
2783 }
John Kessenich55e7d112015-11-15 21:33:39 -07002784 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002785 }
John Kessenich140f3df2015-06-26 16:58:36 -06002786 break;
2787 case glslang::EbtStruct:
2788 case glslang::EbtBlock:
2789 {
2790 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002791 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002792
2793 // Try to share structs for different layouts, but not yet for other
2794 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002795 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002796 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002797 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002798 break;
2799
2800 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002801 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002802 memberRemapper[glslangMembers].resize(glslangMembers->size());
2803 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002804 }
2805 break;
2806 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002807 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002808 break;
2809 }
2810
2811 if (type.isMatrix())
2812 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2813 else {
2814 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2815 if (type.getVectorSize() > 1)
2816 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2817 }
2818
2819 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002820 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2821
John Kessenichc9a80832015-09-12 12:17:44 -06002822 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002823 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002824 // We need to decorate array strides for types needing explicit layout, except blocks.
2825 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002826 // Use a dummy glslang type for querying internal strides of
2827 // arrays of arrays, but using just a one-dimensional array.
2828 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06002829 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
2830 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07002831
2832 // Will compute the higher-order strides here, rather than making a whole
2833 // pile of types and doing repetitive recursion on their contents.
2834 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2835 }
John Kessenichf8842e52016-01-04 19:22:56 -07002836
2837 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002838 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002839 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002840 if (stride > 0)
2841 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002842 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002843 }
2844 } else {
2845 // single-dimensional array, and don't yet have stride
2846
John Kessenichf8842e52016-01-04 19:22:56 -07002847 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002848 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2849 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002850 }
John Kessenich31ed4832015-09-09 17:51:38 -06002851
John Kessenichead86222018-03-28 18:01:20 -06002852 // Do the outer dimension, which might not be known for a runtime-sized array.
2853 // (Unsized arrays that survive through linking will be runtime-sized arrays)
2854 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07002855 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06002856 else {
2857 if (!lastBufferBlockMember) {
2858 builder.addExtension("SPV_EXT_descriptor_indexing");
2859 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
2860 }
John Kessenichead86222018-03-28 18:01:20 -06002861 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06002862 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002863 if (stride > 0)
2864 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002865 }
2866
2867 return spvType;
2868}
2869
John Kessenich0e737842017-03-24 18:38:16 -06002870// TODO: this functionality should exist at a higher level, in creating the AST
2871//
2872// Identify interface members that don't have their required extension turned on.
2873//
2874bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2875{
2876 auto& extensions = glslangIntermediate->getRequestedExtensions();
2877
Rex Xubcf291a2017-03-29 23:01:36 +08002878 if (member.getFieldName() == "gl_ViewportMask" &&
2879 extensions.find("GL_NV_viewport_array2") == extensions.end())
2880 return true;
2881 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2882 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2883 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002884 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2885 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2886 return true;
2887 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2888 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2889 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002890 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2891 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2892 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002893
2894 return false;
2895};
2896
John Kessenich6090df02016-06-30 21:18:02 -06002897// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2898// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2899// Mutually recursive with convertGlslangToSpvType().
2900spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2901 const glslang::TTypeList* glslangMembers,
2902 glslang::TLayoutPacking explicitLayout,
2903 const glslang::TQualifier& qualifier)
2904{
2905 // Create a vector of struct types for SPIR-V to consume
2906 std::vector<spv::Id> spvMembers;
2907 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 -06002908 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2909 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2910 if (glslangMember.hiddenMember()) {
2911 ++memberDelta;
2912 if (type.getBasicType() == glslang::EbtBlock)
2913 memberRemapper[glslangMembers][i] = -1;
2914 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002915 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002916 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002917 if (filterMember(glslangMember))
2918 continue;
2919 }
John Kessenich6090df02016-06-30 21:18:02 -06002920 // modify just this child's view of the qualifier
2921 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2922 InheritQualifiers(memberQualifier, qualifier);
2923
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002924 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002925 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002926 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002927
2928 // recurse
John Kessenichead86222018-03-28 18:01:20 -06002929 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
2930 i == (int)glslangMembers->size() - 1;
2931 spvMembers.push_back(
2932 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06002933 }
2934 }
2935
2936 // Make the SPIR-V type
2937 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002938 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002939 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2940
2941 // Decorate it
2942 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2943
2944 return spvType;
2945}
2946
2947void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2948 const glslang::TTypeList* glslangMembers,
2949 glslang::TLayoutPacking explicitLayout,
2950 const glslang::TQualifier& qualifier,
2951 spv::Id spvType)
2952{
2953 // Name and decorate the non-hidden members
2954 int offset = -1;
2955 int locationOffset = 0; // for use within the members of this struct
2956 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2957 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2958 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002959 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002960 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002961 if (filterMember(glslangMember))
2962 continue;
2963 }
John Kessenich6090df02016-06-30 21:18:02 -06002964
2965 // modify just this child's view of the qualifier
2966 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2967 InheritQualifiers(memberQualifier, qualifier);
2968
2969 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07002970 if (member < 0)
2971 continue;
2972
2973 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2974 builder.addMemberDecoration(spvType, member,
2975 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2976 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2977 // Add interpolation and auxiliary storage decorations only to
2978 // top-level members of Input and Output storage classes
2979 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2980 type.getQualifier().storage == glslang::EvqVaryingOut) {
2981 if (type.getBasicType() == glslang::EbtBlock ||
2982 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
2983 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2984 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002985 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002986 }
2987 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002988
John Kessenich5d610ee2018-03-07 18:05:55 -07002989 if (type.getBasicType() == glslang::EbtBlock &&
2990 qualifier.storage == glslang::EvqBuffer) {
2991 // Add memory decorations only to top-level members of shader storage block
2992 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05002993 TranslateMemoryDecoration(memberQualifier, memory, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich5d610ee2018-03-07 18:05:55 -07002994 for (unsigned int i = 0; i < memory.size(); ++i)
2995 builder.addMemberDecoration(spvType, member, memory[i]);
2996 }
John Kessenich6090df02016-06-30 21:18:02 -06002997
John Kessenich5d610ee2018-03-07 18:05:55 -07002998 // Location assignment was already completed correctly by the front end,
2999 // just track whether a member needs to be decorated.
3000 // Ignore member locations if the container is an array, as that's
3001 // ill-specified and decisions have been made to not allow this.
3002 if (! type.isArray() && memberQualifier.hasLocation())
3003 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06003004
John Kessenich5d610ee2018-03-07 18:05:55 -07003005 if (qualifier.hasLocation()) // track for upcoming inheritance
3006 locationOffset += glslangIntermediate->computeTypeLocationSize(
3007 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06003008
John Kessenich5d610ee2018-03-07 18:05:55 -07003009 // component, XFB, others
3010 if (glslangMember.getQualifier().hasComponent())
3011 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
3012 glslangMember.getQualifier().layoutComponent);
3013 if (glslangMember.getQualifier().hasXfbOffset())
3014 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
3015 glslangMember.getQualifier().layoutXfbOffset);
3016 else if (explicitLayout != glslang::ElpNone) {
3017 // figure out what to do with offset, which is accumulating
3018 int nextOffset;
3019 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
3020 if (offset >= 0)
3021 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
3022 offset = nextOffset;
3023 }
John Kessenich6090df02016-06-30 21:18:02 -06003024
John Kessenich5d610ee2018-03-07 18:05:55 -07003025 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
3026 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
3027 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06003028
John Kessenich5d610ee2018-03-07 18:05:55 -07003029 // built-in variable decorations
3030 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
3031 if (builtIn != spv::BuiltInMax)
3032 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08003033
John Kessenich5611c6d2018-04-05 11:25:02 -06003034 // nonuniform
3035 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
3036
John Kessenichead86222018-03-28 18:01:20 -06003037 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
3038 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
3039 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
3040 memberQualifier.semanticName);
3041 }
3042
chaoc771d89f2017-01-13 01:10:53 -08003043#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07003044 if (builtIn == spv::BuiltInLayer) {
3045 // SPV_NV_viewport_array2 extension
3046 if (glslangMember.getQualifier().layoutViewportRelative){
3047 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
3048 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
3049 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08003050 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003051 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
3052 builder.addMemberDecoration(spvType, member,
3053 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
3054 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
3055 builder.addCapability(spv::CapabilityShaderStereoViewNV);
3056 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08003057 }
John Kessenich5d610ee2018-03-07 18:05:55 -07003058 }
3059 if (glslangMember.getQualifier().layoutPassthrough) {
3060 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
3061 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
3062 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
3063 }
chaoc771d89f2017-01-13 01:10:53 -08003064#endif
John Kessenich6090df02016-06-30 21:18:02 -06003065 }
3066
3067 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07003068 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
3069 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06003070 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
3071 builder.addCapability(spv::CapabilityGeometryStreams);
3072 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
3073 }
John Kessenich6090df02016-06-30 21:18:02 -06003074}
3075
John Kessenich6c292d32016-02-15 20:58:50 -07003076// Turn the expression forming the array size into an id.
3077// This is not quite trivial, because of specialization constants.
3078// Sometimes, a raw constant is turned into an Id, and sometimes
3079// a specialization constant expression is.
3080spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
3081{
3082 // First, see if this is sized with a node, meaning a specialization constant:
3083 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
3084 if (specNode != nullptr) {
3085 builder.clearAccessChain();
3086 specNode->traverse(this);
3087 return accessChainLoad(specNode->getAsTyped()->getType());
3088 }
qining25262b32016-05-06 17:25:16 -04003089
John Kessenich6c292d32016-02-15 20:58:50 -07003090 // Otherwise, need a compile-time (front end) size, get it:
3091 int size = arraySizes.getDimSize(dim);
3092 assert(size > 0);
3093 return builder.makeUintConstant(size);
3094}
3095
John Kessenich103bef92016-02-08 21:38:15 -07003096// Wrap the builder's accessChainLoad to:
3097// - localize handling of RelaxedPrecision
3098// - use the SPIR-V inferred type instead of another conversion of the glslang type
3099// (avoids unnecessary work and possible type punning for structures)
3100// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07003101spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
3102{
John Kessenich103bef92016-02-08 21:38:15 -07003103 spv::Id nominalTypeId = builder.accessChainGetInferredType();
Jeff Bolz36831c92018-09-05 10:11:41 -05003104
3105 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3106 coherentFlags |= TranslateCoherent(type);
3107
John Kessenich5611c6d2018-04-05 11:25:02 -06003108 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
Jeff Bolz36831c92018-09-05 10:11:41 -05003109 TranslateNonUniformDecoration(type.getQualifier()),
3110 nominalTypeId,
3111 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerAvailableKHRMask),
3112 TranslateMemoryScope(coherentFlags));
John Kessenich103bef92016-02-08 21:38:15 -07003113
3114 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003115 if (type.getBasicType() == glslang::EbtBool) {
3116 if (builder.isScalarType(nominalTypeId)) {
3117 // Conversion for bool
3118 spv::Id boolType = builder.makeBoolType();
3119 if (nominalTypeId != boolType)
3120 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3121 } else if (builder.isVectorType(nominalTypeId)) {
3122 // Conversion for bvec
3123 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3124 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3125 if (nominalTypeId != bvecType)
3126 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3127 }
3128 }
John Kessenich103bef92016-02-08 21:38:15 -07003129
3130 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003131}
3132
Rex Xu27253232016-02-23 17:51:09 +08003133// Wrap the builder's accessChainStore to:
3134// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003135//
3136// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003137void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3138{
3139 // Need to convert to abstract types when necessary
3140 if (type.getBasicType() == glslang::EbtBool) {
3141 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3142
3143 if (builder.isScalarType(nominalTypeId)) {
3144 // Conversion for bool
3145 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003146 if (nominalTypeId != boolType) {
3147 // keep these outside arguments, for determinant order-of-evaluation
3148 spv::Id one = builder.makeUintConstant(1);
3149 spv::Id zero = builder.makeUintConstant(0);
3150 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3151 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003152 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003153 } else if (builder.isVectorType(nominalTypeId)) {
3154 // Conversion for bvec
3155 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3156 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003157 if (nominalTypeId != bvecType) {
3158 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003159 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3160 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3161 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003162 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003163 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3164 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003165 }
3166 }
3167
Jeff Bolz36831c92018-09-05 10:11:41 -05003168 spv::Builder::AccessChain::CoherentFlags coherentFlags = builder.getAccessChain().coherentFlags;
3169 coherentFlags |= TranslateCoherent(type);
3170
3171 builder.accessChainStore(rvalue,
3172 spv::MemoryAccessMask(TranslateMemoryAccess(coherentFlags) & ~spv::MemoryAccessMakePointerVisibleKHRMask),
3173 TranslateMemoryScope(coherentFlags));
Rex Xu27253232016-02-23 17:51:09 +08003174}
3175
John Kessenich4bf71552016-09-02 11:20:21 -06003176// For storing when types match at the glslang level, but not might match at the
3177// SPIR-V level.
3178//
3179// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003180// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003181// as in a member-decorated way.
3182//
3183// NOTE: This function can handle any store request; if it's not special it
3184// simplifies to a simple OpStore.
3185//
3186// Implicitly uses the existing builder.accessChain as the storage target.
3187void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3188{
John Kessenichb3e24e42016-09-11 12:33:43 -06003189 // we only do the complex path here if it's an aggregate
3190 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003191 accessChainStore(type, rValue);
3192 return;
3193 }
3194
John Kessenichb3e24e42016-09-11 12:33:43 -06003195 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003196 spv::Id rType = builder.getTypeId(rValue);
3197 spv::Id lValue = builder.accessChainGetLValue();
3198 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3199 if (lType == rType) {
3200 accessChainStore(type, rValue);
3201 return;
3202 }
3203
John Kessenichb3e24e42016-09-11 12:33:43 -06003204 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003205 // where the two types were the same type in GLSL. This requires member
3206 // by member copy, recursively.
3207
John Kessenichb3e24e42016-09-11 12:33:43 -06003208 // If an array, copy element by element.
3209 if (type.isArray()) {
3210 glslang::TType glslangElementType(type, 0);
3211 spv::Id elementRType = builder.getContainedTypeId(rType);
3212 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3213 // get the source member
3214 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003215
John Kessenichb3e24e42016-09-11 12:33:43 -06003216 // set up the target storage
3217 builder.clearAccessChain();
3218 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003219 builder.accessChainPush(builder.makeIntConstant(index), TranslateCoherent(type));
John Kessenich4bf71552016-09-02 11:20:21 -06003220
John Kessenichb3e24e42016-09-11 12:33:43 -06003221 // store the member
3222 multiTypeStore(glslangElementType, elementRValue);
3223 }
3224 } else {
3225 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003226
John Kessenichb3e24e42016-09-11 12:33:43 -06003227 // loop over structure members
3228 const glslang::TTypeList& members = *type.getStruct();
3229 for (int m = 0; m < (int)members.size(); ++m) {
3230 const glslang::TType& glslangMemberType = *members[m].type;
3231
3232 // get the source member
3233 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3234 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3235
3236 // set up the target storage
3237 builder.clearAccessChain();
3238 builder.setAccessChainLValue(lValue);
Jeff Bolz36831c92018-09-05 10:11:41 -05003239 builder.accessChainPush(builder.makeIntConstant(m), TranslateCoherent(type));
John Kessenichb3e24e42016-09-11 12:33:43 -06003240
3241 // store the member
3242 multiTypeStore(glslangMemberType, memberRValue);
3243 }
John Kessenich4bf71552016-09-02 11:20:21 -06003244 }
3245}
3246
John Kessenichf85e8062015-12-19 13:57:10 -07003247// Decide whether or not this type should be
3248// decorated with offsets and strides, and if so
3249// whether std140 or std430 rules should be applied.
3250glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003251{
John Kessenichf85e8062015-12-19 13:57:10 -07003252 // has to be a block
3253 if (type.getBasicType() != glslang::EbtBlock)
3254 return glslang::ElpNone;
3255
3256 // has to be a uniform or buffer block
3257 if (type.getQualifier().storage != glslang::EvqUniform &&
3258 type.getQualifier().storage != glslang::EvqBuffer)
3259 return glslang::ElpNone;
3260
3261 // return the layout to use
3262 switch (type.getQualifier().layoutPacking) {
3263 case glslang::ElpStd140:
3264 case glslang::ElpStd430:
3265 return type.getQualifier().layoutPacking;
3266 default:
3267 return glslang::ElpNone;
3268 }
John Kessenich31ed4832015-09-09 17:51:38 -06003269}
3270
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003271// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003272int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003273{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003274 int size;
John Kessenich49987892015-12-29 17:11:44 -07003275 int stride;
3276 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003277
3278 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003279}
3280
John Kessenich49987892015-12-29 17:11:44 -07003281// 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 -07003282// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003283int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003284{
John Kessenich49987892015-12-29 17:11:44 -07003285 glslang::TType elementType;
3286 elementType.shallowCopy(matrixType);
3287 elementType.clearArraySizes();
3288
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003289 int size;
John Kessenich49987892015-12-29 17:11:44 -07003290 int stride;
3291 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3292
3293 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003294}
3295
John Kessenich5e4b1242015-08-06 22:53:06 -06003296// Given a member type of a struct, realign the current offset for it, and compute
3297// the next (not yet aligned) offset for the next member, which will get aligned
3298// on the next call.
3299// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3300// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3301// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003302void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003303 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003304{
3305 // this will get a positive value when deemed necessary
3306 nextOffset = -1;
3307
John Kessenich5e4b1242015-08-06 22:53:06 -06003308 // override anything in currentOffset with user-set offset
3309 if (memberType.getQualifier().hasOffset())
3310 currentOffset = memberType.getQualifier().layoutOffset;
3311
3312 // It could be that current linker usage in glslang updated all the layoutOffset,
3313 // in which case the following code does not matter. But, that's not quite right
3314 // once cross-compilation unit GLSL validation is done, as the original user
3315 // settings are needed in layoutOffset, and then the following will come into play.
3316
John Kessenichf85e8062015-12-19 13:57:10 -07003317 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003318 if (! memberType.getQualifier().hasOffset())
3319 currentOffset = -1;
3320
3321 return;
3322 }
3323
John Kessenichf85e8062015-12-19 13:57:10 -07003324 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003325 if (currentOffset < 0)
3326 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003327
John Kessenich5e4b1242015-08-06 22:53:06 -06003328 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3329 // but possibly not yet correctly aligned.
3330
3331 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003332 int dummyStride;
3333 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003334
3335 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003336 // TODO: make this consistent in early phases of code:
3337 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3338 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3339 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kesseniche7df8e02018-08-22 17:12:46 -06003340 if (glslangIntermediate->usingHlslOffsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003341 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003342 int dummySize;
3343 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3344 if (componentAlignment <= 4)
3345 memberAlignment = componentAlignment;
3346 }
3347
3348 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003349 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003350
3351 // Bump up to vec4 if there is a bad straddle
3352 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3353 glslang::RoundToPow2(currentOffset, 16);
3354
John Kessenich5e4b1242015-08-06 22:53:06 -06003355 nextOffset = currentOffset + memberSize;
3356}
3357
David Netoa901ffe2016-06-08 14:11:40 +01003358void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003359{
David Netoa901ffe2016-06-08 14:11:40 +01003360 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3361 switch (glslangBuiltIn)
3362 {
3363 case glslang::EbvClipDistance:
3364 case glslang::EbvCullDistance:
3365 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003366#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003367 case glslang::EbvViewportMaskNV:
3368 case glslang::EbvSecondaryPositionNV:
3369 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003370 case glslang::EbvPositionPerViewNV:
3371 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08003372#endif
David Netoa901ffe2016-06-08 14:11:40 +01003373 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3374 // Alternately, we could just call this for any glslang built-in, since the
3375 // capability already guards against duplicates.
3376 TranslateBuiltInDecoration(glslangBuiltIn, false);
3377 break;
3378 default:
3379 // Capabilities were already generated when the struct was declared.
3380 break;
3381 }
John Kessenichebb50532016-05-16 19:22:05 -06003382}
3383
John Kessenich6fccb3c2016-09-19 16:01:41 -06003384bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003385{
John Kessenicheee9d532016-09-19 18:09:30 -06003386 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003387}
3388
John Kessenichd41993d2017-09-10 15:21:05 -06003389// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003390// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3391// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003392bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003393{
John Kessenich6a14f782017-12-04 02:48:10 -07003394 assert(qualifier == glslang::EvqIn ||
3395 qualifier == glslang::EvqOut ||
3396 qualifier == glslang::EvqInOut ||
3397 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003398 return qualifier != glslang::EvqConstReadOnly;
3399}
3400
3401// Is parameter pass-by-original?
3402bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3403 bool implicitThisParam)
3404{
3405 if (implicitThisParam) // implicit this
3406 return true;
3407 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003408 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003409 return paramType.containsOpaque() || // sampler, etc.
3410 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3411}
3412
John Kessenich140f3df2015-06-26 16:58:36 -06003413// Make all the functions, skeletally, without actually visiting their bodies.
3414void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3415{
Jeff Bolz36831c92018-09-05 10:11:41 -05003416 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type, bool useVulkanMemoryModel) {
John Kessenichfad62972017-07-18 02:35:46 -06003417 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3418 if (paramPrecision != spv::NoPrecision)
3419 decorations.push_back(paramPrecision);
Jeff Bolz36831c92018-09-05 10:11:41 -05003420 TranslateMemoryDecoration(type.getQualifier(), decorations, useVulkanMemoryModel);
John Kessenichfad62972017-07-18 02:35:46 -06003421 };
3422
John Kessenich140f3df2015-06-26 16:58:36 -06003423 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3424 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003425 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003426 continue;
3427
3428 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003429 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003430 //
qining25262b32016-05-06 17:25:16 -04003431 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003432 // function. What it is an address of varies:
3433 //
John Kessenich4bf71552016-09-02 11:20:21 -06003434 // - "in" parameters not marked as "const" can be written to without modifying the calling
3435 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003436 //
3437 // - "const in" parameters can just be the r-value, as no writes need occur.
3438 //
John Kessenich4bf71552016-09-02 11:20:21 -06003439 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3440 // 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 -06003441
3442 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003443 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003444 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3445
John Kessenichfad62972017-07-18 02:35:46 -06003446 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3447 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003448
John Kessenichfad62972017-07-18 02:35:46 -06003449 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003450 for (int p = 0; p < (int)parameters.size(); ++p) {
3451 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3452 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003453 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003454 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003455 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003456 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3457 else
John Kessenich4bf71552016-09-02 11:20:21 -06003458 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
Jeff Bolz36831c92018-09-05 10:11:41 -05003459 getParamDecorations(paramDecorations[p], paramType, glslangIntermediate->usingVulkanMemoryModel());
John Kessenich140f3df2015-06-26 16:58:36 -06003460 paramTypes.push_back(typeId);
3461 }
3462
3463 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003464 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3465 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003466 glslFunction->getName().c_str(), paramTypes,
3467 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003468 if (implicitThis)
3469 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003470
3471 // Track function to emit/call later
3472 functionMap[glslFunction->getName().c_str()] = function;
3473
3474 // Set the parameter id's
3475 for (int p = 0; p < (int)parameters.size(); ++p) {
3476 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3477 // give a name too
3478 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3479 }
3480 }
3481}
3482
3483// Process all the initializers, while skipping the functions and link objects
3484void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3485{
3486 builder.setBuildPoint(shaderEntry->getLastBlock());
3487 for (int i = 0; i < (int)initializers.size(); ++i) {
3488 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3489 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3490
3491 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003492 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003493 initializer->traverse(this);
3494 }
3495 }
3496}
3497
3498// Process all the functions, while skipping initializers.
3499void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3500{
3501 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3502 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003503 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003504 node->traverse(this);
3505 }
3506}
3507
3508void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3509{
qining25262b32016-05-06 17:25:16 -04003510 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003511 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003512 currentFunction = functionMap[node->getName().c_str()];
3513 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003514 builder.setBuildPoint(functionBlock);
3515}
3516
Rex Xu04db3f52015-09-16 11:44:02 +08003517void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003518{
Rex Xufc618912015-09-09 16:42:49 +08003519 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003520
3521 glslang::TSampler sampler = {};
3522 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003523#ifdef AMD_EXTENSIONS
3524 bool f16ShadowCompare = false;
3525#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003526 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003527 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3528 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003529#ifdef AMD_EXTENSIONS
3530 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3531#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003532 }
3533
John Kessenich140f3df2015-06-26 16:58:36 -06003534 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3535 builder.clearAccessChain();
3536 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003537
3538 // Special case l-value operands
3539 bool lvalue = false;
3540 switch (node.getOp()) {
3541 case glslang::EOpImageAtomicAdd:
3542 case glslang::EOpImageAtomicMin:
3543 case glslang::EOpImageAtomicMax:
3544 case glslang::EOpImageAtomicAnd:
3545 case glslang::EOpImageAtomicOr:
3546 case glslang::EOpImageAtomicXor:
3547 case glslang::EOpImageAtomicExchange:
3548 case glslang::EOpImageAtomicCompSwap:
Jeff Bolz36831c92018-09-05 10:11:41 -05003549 case glslang::EOpImageAtomicLoad:
3550 case glslang::EOpImageAtomicStore:
Rex Xufc618912015-09-09 16:42:49 +08003551 if (i == 0)
3552 lvalue = true;
3553 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003554 case glslang::EOpSparseImageLoad:
3555 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3556 lvalue = true;
3557 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003558#ifdef AMD_EXTENSIONS
3559 case glslang::EOpSparseTexture:
3560 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3561 lvalue = true;
3562 break;
3563 case glslang::EOpSparseTextureClamp:
3564 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3565 lvalue = true;
3566 break;
3567 case glslang::EOpSparseTextureLod:
3568 case glslang::EOpSparseTextureOffset:
3569 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3570 lvalue = true;
3571 break;
3572#else
Rex Xu48edadf2015-12-31 16:11:41 +08003573 case glslang::EOpSparseTexture:
3574 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3575 lvalue = true;
3576 break;
3577 case glslang::EOpSparseTextureClamp:
3578 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3579 lvalue = true;
3580 break;
3581 case glslang::EOpSparseTextureLod:
3582 case glslang::EOpSparseTextureOffset:
3583 if (i == 3)
3584 lvalue = true;
3585 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003586#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003587 case glslang::EOpSparseTextureFetch:
3588 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3589 lvalue = true;
3590 break;
3591 case glslang::EOpSparseTextureFetchOffset:
3592 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3593 lvalue = true;
3594 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003595#ifdef AMD_EXTENSIONS
3596 case glslang::EOpSparseTextureLodOffset:
3597 case glslang::EOpSparseTextureGrad:
3598 case glslang::EOpSparseTextureOffsetClamp:
3599 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3600 lvalue = true;
3601 break;
3602 case glslang::EOpSparseTextureGradOffset:
3603 case glslang::EOpSparseTextureGradClamp:
3604 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3605 lvalue = true;
3606 break;
3607 case glslang::EOpSparseTextureGradOffsetClamp:
3608 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3609 lvalue = true;
3610 break;
3611#else
Rex Xu48edadf2015-12-31 16:11:41 +08003612 case glslang::EOpSparseTextureLodOffset:
3613 case glslang::EOpSparseTextureGrad:
3614 case glslang::EOpSparseTextureOffsetClamp:
3615 if (i == 4)
3616 lvalue = true;
3617 break;
3618 case glslang::EOpSparseTextureGradOffset:
3619 case glslang::EOpSparseTextureGradClamp:
3620 if (i == 5)
3621 lvalue = true;
3622 break;
3623 case glslang::EOpSparseTextureGradOffsetClamp:
3624 if (i == 6)
3625 lvalue = true;
3626 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003627#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003628 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003629 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3630 lvalue = true;
3631 break;
3632 case glslang::EOpSparseTextureGatherOffset:
3633 case glslang::EOpSparseTextureGatherOffsets:
3634 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3635 lvalue = true;
3636 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003637#ifdef AMD_EXTENSIONS
3638 case glslang::EOpSparseTextureGatherLod:
3639 if (i == 3)
3640 lvalue = true;
3641 break;
3642 case glslang::EOpSparseTextureGatherLodOffset:
3643 case glslang::EOpSparseTextureGatherLodOffsets:
3644 if (i == 4)
3645 lvalue = true;
3646 break;
Rex Xu129799a2017-07-05 17:23:28 +08003647 case glslang::EOpSparseImageLoadLod:
3648 if (i == 3)
3649 lvalue = true;
3650 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003651#endif
Rex Xufc618912015-09-09 16:42:49 +08003652 default:
3653 break;
3654 }
3655
Rex Xu6b86d492015-09-16 17:48:22 +08003656 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003657 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003658 else
John Kessenich32cfd492016-02-02 12:37:46 -07003659 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003660 }
3661}
3662
John Kessenichfc51d282015-08-19 13:34:18 -06003663void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003664{
John Kessenichfc51d282015-08-19 13:34:18 -06003665 builder.clearAccessChain();
3666 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003667 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003668}
John Kessenich140f3df2015-06-26 16:58:36 -06003669
John Kessenichfc51d282015-08-19 13:34:18 -06003670spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3671{
John Kesseniche485c7a2017-05-31 18:50:53 -06003672 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003673 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003674
3675 builder.setLine(node->getLoc().line);
3676
John Kessenichfc51d282015-08-19 13:34:18 -06003677 // Process a GLSL texturing op (will be SPV image)
Jeff Bolz36831c92018-09-05 10:11:41 -05003678
3679 const glslang::TType &imageType = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType()
3680 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType();
3681 const glslang::TSampler sampler = imageType.getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003682#ifdef AMD_EXTENSIONS
3683 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3684 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3685 : false;
3686#endif
3687
John Kessenichfc51d282015-08-19 13:34:18 -06003688 std::vector<spv::Id> arguments;
3689 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003690 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003691 else
3692 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003693 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003694
3695 spv::Builder::TextureParameters params = { };
3696 params.sampler = arguments[0];
3697
Rex Xu04db3f52015-09-16 11:44:02 +08003698 glslang::TCrackedTextureOp cracked;
3699 node->crackTexture(sampler, cracked);
3700
amhagan05506bb2017-06-13 16:53:02 -04003701 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003702
John Kessenichfc51d282015-08-19 13:34:18 -06003703 // Check for queries
3704 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003705 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3706 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003707 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003708
John Kessenichfc51d282015-08-19 13:34:18 -06003709 switch (node->getOp()) {
3710 case glslang::EOpImageQuerySize:
3711 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003712 if (arguments.size() > 1) {
3713 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003714 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003715 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003716 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003717 case glslang::EOpImageQuerySamples:
3718 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003719 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003720 case glslang::EOpTextureQueryLod:
3721 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003722 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003723 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003724 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003725 case glslang::EOpSparseTexelsResident:
3726 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003727 default:
3728 assert(0);
3729 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003730 }
John Kessenich140f3df2015-06-26 16:58:36 -06003731 }
3732
LoopDawg4425f242018-02-18 11:40:01 -07003733 int components = node->getType().getVectorSize();
3734
3735 if (node->getOp() == glslang::EOpTextureFetch) {
3736 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3737 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3738 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3739 // here around e.g. which ones return scalars or other types.
3740 components = 4;
3741 }
3742
3743 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3744
3745 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3746
Rex Xufc618912015-09-09 16:42:49 +08003747 // Check for image functions other than queries
3748 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06003749 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06003750 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06003751 spv::IdImmediate image = { true, *(opIt++) };
3752 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07003753
3754 // Handle subpass operations
3755 // TODO: GLSL should change to have the "MS" only on the type rather than the
3756 // built-in function.
3757 if (cracked.subpass) {
3758 // add on the (0,0) coordinate
3759 spv::Id zero = builder.makeIntConstant(0);
3760 std::vector<spv::Id> comps;
3761 comps.push_back(zero);
3762 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06003763 spv::IdImmediate coord = { true,
3764 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
3765 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07003766 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003767 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3768 operands.push_back(imageOperands);
3769 spv::IdImmediate imageOperand = { true, *(opIt++) };
3770 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07003771 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003772 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3773 builder.setPrecision(result, precision);
3774 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003775 }
3776
John Kessenich149afc32018-08-14 13:31:43 -06003777 spv::IdImmediate coord = { true, *(opIt++) };
3778 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08003779#ifdef AMD_EXTENSIONS
3780 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3781#else
John Kessenich56bab042015-09-16 10:54:31 -06003782 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003783#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05003784 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
John Kessenich55e7d112015-11-15 21:33:39 -07003785 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05003786 mask = mask | spv::ImageOperandsSampleMask;
3787 }
Rex Xu129799a2017-07-05 17:23:28 +08003788#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05003789 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08003790 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3791 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
Jeff Bolz36831c92018-09-05 10:11:41 -05003792 mask = mask | spv::ImageOperandsLodMask;
John Kessenich55e7d112015-11-15 21:33:39 -07003793 }
Jeff Bolz36831c92018-09-05 10:11:41 -05003794#endif
3795 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
3796 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
3797 if (mask) {
3798 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
3799 operands.push_back(imageOperands);
3800 }
3801 if (mask & spv::ImageOperandsSampleMask) {
3802 spv::IdImmediate imageOperand = { true, *opIt++ };
3803 operands.push_back(imageOperand);
3804 }
3805#ifdef AMD_EXTENSIONS
3806 if (mask & spv::ImageOperandsLodMask) {
3807 spv::IdImmediate imageOperand = { true, *opIt++ };
3808 operands.push_back(imageOperand);
3809 }
3810#endif
3811 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
3812 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
3813 operands.push_back(imageOperand);
3814 }
3815
John Kessenich149afc32018-08-14 13:31:43 -06003816 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07003817 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003818
John Kessenich149afc32018-08-14 13:31:43 -06003819 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07003820 builder.setPrecision(result[0], precision);
3821
3822 // If needed, add a conversion constructor to the proper size.
3823 if (components != node->getType().getVectorSize())
3824 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3825
3826 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003827#ifdef AMD_EXTENSIONS
3828 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3829#else
John Kessenich56bab042015-09-16 10:54:31 -06003830 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003831#endif
Rex Xu129799a2017-07-05 17:23:28 +08003832
Jeff Bolz36831c92018-09-05 10:11:41 -05003833 // Push the texel value before the operands
3834#ifdef AMD_EXTENSIONS
3835 if (sampler.ms || cracked.lod) {
3836#else
3837 if (sampler.ms) {
3838#endif
John Kessenich149afc32018-08-14 13:31:43 -06003839 spv::IdImmediate texel = { true, *(opIt + 1) };
3840 operands.push_back(texel);
John Kessenich149afc32018-08-14 13:31:43 -06003841 } else {
3842 spv::IdImmediate texel = { true, *opIt };
3843 operands.push_back(texel);
3844 }
Jeff Bolz36831c92018-09-05 10:11:41 -05003845
3846 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
3847 if (sampler.ms) {
3848 mask = mask | spv::ImageOperandsSampleMask;
3849 }
3850#ifdef AMD_EXTENSIONS
3851 if (cracked.lod) {
3852 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3853 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3854 mask = mask | spv::ImageOperandsLodMask;
3855 }
3856#endif
3857 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
3858 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelVisibleKHRMask);
3859 if (mask) {
3860 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
3861 operands.push_back(imageOperands);
3862 }
3863 if (mask & spv::ImageOperandsSampleMask) {
3864 spv::IdImmediate imageOperand = { true, *opIt++ };
3865 operands.push_back(imageOperand);
3866 }
3867#ifdef AMD_EXTENSIONS
3868 if (mask & spv::ImageOperandsLodMask) {
3869 spv::IdImmediate imageOperand = { true, *opIt++ };
3870 operands.push_back(imageOperand);
3871 }
3872#endif
3873 if (mask & spv::ImageOperandsMakeTexelAvailableKHRMask) {
3874 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
3875 operands.push_back(imageOperand);
3876 }
3877
John Kessenich56bab042015-09-16 10:54:31 -06003878 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06003879 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07003880 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003881 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003882#ifdef AMD_EXTENSIONS
3883 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3884#else
Rex Xu5eafa472016-02-19 22:24:03 +08003885 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003886#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003887 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06003888 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08003889 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3890
Jeff Bolz36831c92018-09-05 10:11:41 -05003891 spv::ImageOperandsMask mask = spv::ImageOperandsMaskNone;
Rex Xu5eafa472016-02-19 22:24:03 +08003892 if (sampler.ms) {
Jeff Bolz36831c92018-09-05 10:11:41 -05003893 mask = mask | spv::ImageOperandsSampleMask;
3894 }
Rex Xu129799a2017-07-05 17:23:28 +08003895#ifdef AMD_EXTENSIONS
Jeff Bolz36831c92018-09-05 10:11:41 -05003896 if (cracked.lod) {
Rex Xu129799a2017-07-05 17:23:28 +08003897 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3898 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3899
Jeff Bolz36831c92018-09-05 10:11:41 -05003900 mask = mask | spv::ImageOperandsLodMask;
3901 }
3902#endif
3903 mask = mask | TranslateImageOperands(TranslateCoherent(imageType));
3904 mask = (spv::ImageOperandsMask)(mask & ~spv::ImageOperandsMakeTexelAvailableKHRMask);
3905 if (mask) {
3906 spv::IdImmediate imageOperands = { false, (unsigned int)mask };
John Kessenich149afc32018-08-14 13:31:43 -06003907 operands.push_back(imageOperands);
Jeff Bolz36831c92018-09-05 10:11:41 -05003908 }
3909 if (mask & spv::ImageOperandsSampleMask) {
John Kessenich149afc32018-08-14 13:31:43 -06003910 spv::IdImmediate imageOperand = { true, *opIt++ };
3911 operands.push_back(imageOperand);
Jeff Bolz36831c92018-09-05 10:11:41 -05003912 }
3913#ifdef AMD_EXTENSIONS
3914 if (mask & spv::ImageOperandsLodMask) {
3915 spv::IdImmediate imageOperand = { true, *opIt++ };
3916 operands.push_back(imageOperand);
3917 }
Rex Xu129799a2017-07-05 17:23:28 +08003918#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05003919 if (mask & spv::ImageOperandsMakeTexelVisibleKHRMask) {
3920 spv::IdImmediate imageOperand = { true, builder.makeUintConstant(TranslateMemoryScope(TranslateCoherent(imageType))) };
3921 operands.push_back(imageOperand);
Rex Xu5eafa472016-02-19 22:24:03 +08003922 }
3923
3924 // Create the return type that was a special structure
3925 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003926 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003927 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3928 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3929
3930 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3931
3932 // Decode the return type
3933 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3934 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003935 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003936 // Process image atomic operations
3937
3938 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3939 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06003940 // For non-MS, the sample value should be 0
3941 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
3942 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06003943
Jeff Bolz36831c92018-09-05 10:11:41 -05003944 spv::Id resultTypeId;
3945 // imageAtomicStore has a void return type so base the pointer type on
3946 // the type of the value operand.
3947 if (node->getOp() == glslang::EOpImageAtomicStore) {
3948 resultTypeId = builder.makePointer(spv::StorageClassImage, builder.getTypeId(operands[2].word));
3949 } else {
3950 resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
3951 }
John Kessenich56bab042015-09-16 10:54:31 -06003952 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003953
3954 std::vector<spv::Id> operands;
3955 operands.push_back(pointer);
3956 for (; opIt != arguments.end(); ++opIt)
3957 operands.push_back(*opIt);
3958
John Kessenich8c8505c2016-07-26 12:50:38 -06003959 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003960 }
3961 }
3962
amhagan05506bb2017-06-13 16:53:02 -04003963#ifdef AMD_EXTENSIONS
3964 // Check for fragment mask functions other than queries
3965 if (cracked.fragMask) {
3966 assert(sampler.ms);
3967
3968 auto opIt = arguments.begin();
3969 std::vector<spv::Id> operands;
3970
3971 // Extract the image if necessary
3972 if (builder.isSampledImage(params.sampler))
3973 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3974
3975 operands.push_back(params.sampler);
3976 ++opIt;
3977
3978 if (sampler.isSubpass()) {
3979 // add on the (0,0) coordinate
3980 spv::Id zero = builder.makeIntConstant(0);
3981 std::vector<spv::Id> comps;
3982 comps.push_back(zero);
3983 comps.push_back(zero);
3984 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3985 }
3986
3987 for (; opIt != arguments.end(); ++opIt)
3988 operands.push_back(*opIt);
3989
3990 spv::Op fragMaskOp = spv::OpNop;
3991 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3992 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3993 else if (node->getOp() == glslang::EOpFragmentFetch)
3994 fragMaskOp = spv::OpFragmentFetchAMD;
3995
3996 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3997 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3998 return builder.createOp(fragMaskOp, resultType(), operands);
3999 }
4000#endif
4001
Rex Xufc618912015-09-09 16:42:49 +08004002 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08004003 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08004004 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
4005
John Kessenichfc51d282015-08-19 13:34:18 -06004006 // check for bias argument
4007 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08004008#ifdef AMD_EXTENSIONS
4009 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
4010#else
Rex Xu71519fe2015-11-11 15:35:47 +08004011 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08004012#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004013 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08004014#ifdef AMD_EXTENSIONS
4015 if (cracked.gather)
4016 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08004017
4018 if (f16ShadowCompare)
4019 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004020#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004021 if (cracked.offset)
4022 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08004023#ifdef AMD_EXTENSIONS
4024 else if (cracked.offsets)
4025 ++nonBiasArgCount;
4026#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004027 if (cracked.grad)
4028 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08004029 if (cracked.lodClamp)
4030 ++nonBiasArgCount;
4031 if (sparse)
4032 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06004033
4034 if ((int)arguments.size() > nonBiasArgCount)
4035 bias = true;
4036 }
4037
John Kessenicha5c33d62016-06-02 23:45:21 -06004038 // See if the sampler param should really be just the SPV image part
4039 if (cracked.fetch) {
4040 // a fetch needs to have the image extracted first
4041 if (builder.isSampledImage(params.sampler))
4042 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
4043 }
4044
Rex Xu225e0fc2016-11-17 17:47:59 +08004045#ifdef AMD_EXTENSIONS
4046 if (cracked.gather) {
4047 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
4048 if (bias || cracked.lod ||
4049 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
4050 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08004051 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08004052 }
4053 }
4054#endif
4055
John Kessenichfc51d282015-08-19 13:34:18 -06004056 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07004057
John Kessenichfc51d282015-08-19 13:34:18 -06004058 params.coords = arguments[1];
4059 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07004060 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07004061
4062 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08004063#ifdef AMD_EXTENSIONS
4064 if (cubeCompare || f16ShadowCompare) {
4065#else
Rex Xu48edadf2015-12-31 16:11:41 +08004066 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08004067#endif
John Kessenichfc51d282015-08-19 13:34:18 -06004068 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08004069 ++extraArgs;
4070 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07004071 params.Dref = arguments[2];
4072 ++extraArgs;
4073 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06004074 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06004075 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06004076 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06004077 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06004078 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004079 dRefComp = builder.getNumComponents(params.coords) - 1;
4080 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06004081 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
4082 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004083
4084 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06004085 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004086 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06004087 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07004088 } else if (glslangIntermediate->getStage() != EShLangFragment) {
4089 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
4090 noImplicitLod = true;
4091 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004092
4093 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07004094 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06004095 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08004096 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004097 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004098
4099 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06004100 if (cracked.grad) {
4101 params.gradX = arguments[2 + extraArgs];
4102 params.gradY = arguments[3 + extraArgs];
4103 extraArgs += 2;
4104 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004105
4106 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07004107 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06004108 params.offset = arguments[2 + extraArgs];
4109 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004110 } else if (cracked.offsets) {
4111 params.offsets = arguments[2 + extraArgs];
4112 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06004113 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004114
4115 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08004116 if (cracked.lodClamp) {
4117 params.lodClamp = arguments[2 + extraArgs];
4118 ++extraArgs;
4119 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004120
4121 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08004122 if (sparse) {
4123 params.texelOut = arguments[2 + extraArgs];
4124 ++extraArgs;
4125 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06004126
John Kessenich76d4dfc2016-06-16 12:43:23 -06004127 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07004128 if (cracked.gather && ! sampler.shadow) {
4129 // default component is 0, if missing, otherwise an argument
4130 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06004131 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07004132 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08004133 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06004134 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08004135 }
4136
4137 // bias
4138 if (bias) {
4139 params.bias = arguments[2 + extraArgs];
4140 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07004141 }
John Kessenichfc51d282015-08-19 13:34:18 -06004142
John Kessenich65336482016-06-16 14:06:26 -06004143 // projective component (might not to move)
4144 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
4145 // are divided by the last component of P."
4146 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
4147 // unused components will appear after all used components."
4148 if (cracked.proj) {
4149 int projSourceComp = builder.getNumComponents(params.coords) - 1;
4150 int projTargetComp;
4151 switch (sampler.dim) {
4152 case glslang::Esd1D: projTargetComp = 1; break;
4153 case glslang::Esd2D: projTargetComp = 2; break;
4154 case glslang::EsdRect: projTargetComp = 2; break;
4155 default: projTargetComp = projSourceComp; break;
4156 }
4157 // copy the projective coordinate if we have to
4158 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07004159 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06004160 builder.getScalarTypeId(builder.getTypeId(params.coords)),
4161 projSourceComp);
4162 params.coords = builder.createCompositeInsert(projComp, params.coords,
4163 builder.getTypeId(params.coords), projTargetComp);
4164 }
4165 }
4166
Jeff Bolz36831c92018-09-05 10:11:41 -05004167 // nonprivate
4168 if (imageType.getQualifier().nonprivate) {
4169 params.nonprivate = true;
4170 }
4171
4172 // volatile
4173 if (imageType.getQualifier().volatil) {
4174 params.volatil = true;
4175 }
4176
St0fFa1184dd2018-04-09 21:08:14 +02004177 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07004178 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02004179 );
LoopDawg4425f242018-02-18 11:40:01 -07004180
4181 if (components != node->getType().getVectorSize())
4182 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
4183
4184 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06004185}
4186
4187spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
4188{
4189 // Grab the function's pointer from the previously created function
4190 spv::Function* function = functionMap[node->getName().c_str()];
4191 if (! function)
4192 return 0;
4193
4194 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4195 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4196
4197 // See comments in makeFunctions() for details about the semantics for parameter passing.
4198 //
4199 // These imply we need a four step process:
4200 // 1. Evaluate the arguments
4201 // 2. Allocate and make copies of in, out, and inout arguments
4202 // 3. Make the call
4203 // 4. Copy back the results
4204
John Kessenichd3ed90b2018-05-04 11:43:03 -06004205 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004206 std::vector<spv::Builder::AccessChain> lValues;
4207 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004208 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004209 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004210 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004211 // build l-value
4212 builder.clearAccessChain();
4213 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004214 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004215 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004216 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004217 // save l-value
4218 lValues.push_back(builder.getAccessChain());
4219 } else {
4220 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004221 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004222 }
4223 }
4224
4225 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4226 // copy the original into that space.
4227 //
4228 // Also, build up the list of actual arguments to pass in for the call
4229 int lValueCount = 0;
4230 int rValueCount = 0;
4231 std::vector<spv::Id> spvArgs;
4232 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4233 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004234 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004235 builder.setAccessChain(lValues[lValueCount]);
4236 arg = builder.accessChainGetLValue();
4237 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004238 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004239 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004240 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004241 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4242 // need to copy the input into output space
4243 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004244 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004245 builder.clearAccessChain();
4246 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004247 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004248 }
4249 ++lValueCount;
4250 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004251 // process r-value, which involves a copy for a type mismatch
4252 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4253 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4254 builder.clearAccessChain();
4255 builder.setAccessChainLValue(argCopy);
4256 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4257 arg = builder.createLoad(argCopy);
4258 } else
4259 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004260 ++rValueCount;
4261 }
4262 spvArgs.push_back(arg);
4263 }
4264
4265 // 3. Make the call.
4266 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004267 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004268
4269 // 4. Copy back out an "out" arguments.
4270 lValueCount = 0;
4271 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004272 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004273 ++lValueCount;
4274 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004275 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4276 spv::Id copy = builder.createLoad(spvArgs[a]);
4277 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004278 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004279 }
4280 ++lValueCount;
4281 }
4282 }
4283
4284 return result;
4285}
4286
4287// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004288spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004289 spv::Id typeId, spv::Id left, spv::Id right,
4290 glslang::TBasicType typeProxy, bool reduceComparison)
4291{
John Kessenich66011cb2018-03-06 16:12:04 -07004292 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4293 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004294 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004295
4296 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004297 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004298 bool comparison = false;
4299
4300 switch (op) {
4301 case glslang::EOpAdd:
4302 case glslang::EOpAddAssign:
4303 if (isFloat)
4304 binOp = spv::OpFAdd;
4305 else
4306 binOp = spv::OpIAdd;
4307 break;
4308 case glslang::EOpSub:
4309 case glslang::EOpSubAssign:
4310 if (isFloat)
4311 binOp = spv::OpFSub;
4312 else
4313 binOp = spv::OpISub;
4314 break;
4315 case glslang::EOpMul:
4316 case glslang::EOpMulAssign:
4317 if (isFloat)
4318 binOp = spv::OpFMul;
4319 else
4320 binOp = spv::OpIMul;
4321 break;
4322 case glslang::EOpVectorTimesScalar:
4323 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004324 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004325 if (builder.isVector(right))
4326 std::swap(left, right);
4327 assert(builder.isScalar(right));
4328 needMatchingVectors = false;
4329 binOp = spv::OpVectorTimesScalar;
4330 } else
4331 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004332 break;
4333 case glslang::EOpVectorTimesMatrix:
4334 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004335 binOp = spv::OpVectorTimesMatrix;
4336 break;
4337 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004338 binOp = spv::OpMatrixTimesVector;
4339 break;
4340 case glslang::EOpMatrixTimesScalar:
4341 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004342 binOp = spv::OpMatrixTimesScalar;
4343 break;
4344 case glslang::EOpMatrixTimesMatrix:
4345 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004346 binOp = spv::OpMatrixTimesMatrix;
4347 break;
4348 case glslang::EOpOuterProduct:
4349 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004350 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004351 break;
4352
4353 case glslang::EOpDiv:
4354 case glslang::EOpDivAssign:
4355 if (isFloat)
4356 binOp = spv::OpFDiv;
4357 else if (isUnsigned)
4358 binOp = spv::OpUDiv;
4359 else
4360 binOp = spv::OpSDiv;
4361 break;
4362 case glslang::EOpMod:
4363 case glslang::EOpModAssign:
4364 if (isFloat)
4365 binOp = spv::OpFMod;
4366 else if (isUnsigned)
4367 binOp = spv::OpUMod;
4368 else
4369 binOp = spv::OpSMod;
4370 break;
4371 case glslang::EOpRightShift:
4372 case glslang::EOpRightShiftAssign:
4373 if (isUnsigned)
4374 binOp = spv::OpShiftRightLogical;
4375 else
4376 binOp = spv::OpShiftRightArithmetic;
4377 break;
4378 case glslang::EOpLeftShift:
4379 case glslang::EOpLeftShiftAssign:
4380 binOp = spv::OpShiftLeftLogical;
4381 break;
4382 case glslang::EOpAnd:
4383 case glslang::EOpAndAssign:
4384 binOp = spv::OpBitwiseAnd;
4385 break;
4386 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004387 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004388 binOp = spv::OpLogicalAnd;
4389 break;
4390 case glslang::EOpInclusiveOr:
4391 case glslang::EOpInclusiveOrAssign:
4392 binOp = spv::OpBitwiseOr;
4393 break;
4394 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004395 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004396 binOp = spv::OpLogicalOr;
4397 break;
4398 case glslang::EOpExclusiveOr:
4399 case glslang::EOpExclusiveOrAssign:
4400 binOp = spv::OpBitwiseXor;
4401 break;
4402 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004403 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004404 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004405 break;
4406
4407 case glslang::EOpLessThan:
4408 case glslang::EOpGreaterThan:
4409 case glslang::EOpLessThanEqual:
4410 case glslang::EOpGreaterThanEqual:
4411 case glslang::EOpEqual:
4412 case glslang::EOpNotEqual:
4413 case glslang::EOpVectorEqual:
4414 case glslang::EOpVectorNotEqual:
4415 comparison = true;
4416 break;
4417 default:
4418 break;
4419 }
4420
John Kessenich7c1aa102015-10-15 13:29:11 -06004421 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004422 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004423 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004424 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004425 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004426
4427 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004428 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004429 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004430
qining25262b32016-05-06 17:25:16 -04004431 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004432 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004433 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004434 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004435 }
4436
4437 if (! comparison)
4438 return 0;
4439
John Kessenich7c1aa102015-10-15 13:29:11 -06004440 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004441
John Kessenich4583b612016-08-07 19:14:22 -06004442 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004443 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4444 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004445 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004446 return result;
4447 }
John Kessenich140f3df2015-06-26 16:58:36 -06004448
4449 switch (op) {
4450 case glslang::EOpLessThan:
4451 if (isFloat)
4452 binOp = spv::OpFOrdLessThan;
4453 else if (isUnsigned)
4454 binOp = spv::OpULessThan;
4455 else
4456 binOp = spv::OpSLessThan;
4457 break;
4458 case glslang::EOpGreaterThan:
4459 if (isFloat)
4460 binOp = spv::OpFOrdGreaterThan;
4461 else if (isUnsigned)
4462 binOp = spv::OpUGreaterThan;
4463 else
4464 binOp = spv::OpSGreaterThan;
4465 break;
4466 case glslang::EOpLessThanEqual:
4467 if (isFloat)
4468 binOp = spv::OpFOrdLessThanEqual;
4469 else if (isUnsigned)
4470 binOp = spv::OpULessThanEqual;
4471 else
4472 binOp = spv::OpSLessThanEqual;
4473 break;
4474 case glslang::EOpGreaterThanEqual:
4475 if (isFloat)
4476 binOp = spv::OpFOrdGreaterThanEqual;
4477 else if (isUnsigned)
4478 binOp = spv::OpUGreaterThanEqual;
4479 else
4480 binOp = spv::OpSGreaterThanEqual;
4481 break;
4482 case glslang::EOpEqual:
4483 case glslang::EOpVectorEqual:
4484 if (isFloat)
4485 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004486 else if (isBool)
4487 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004488 else
4489 binOp = spv::OpIEqual;
4490 break;
4491 case glslang::EOpNotEqual:
4492 case glslang::EOpVectorNotEqual:
4493 if (isFloat)
4494 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004495 else if (isBool)
4496 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004497 else
4498 binOp = spv::OpINotEqual;
4499 break;
4500 default:
4501 break;
4502 }
4503
qining25262b32016-05-06 17:25:16 -04004504 if (binOp != spv::OpNop) {
4505 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004506 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004507 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004508 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004509 }
John Kessenich140f3df2015-06-26 16:58:36 -06004510
4511 return 0;
4512}
4513
John Kessenich04bb8a02015-12-12 12:28:14 -07004514//
4515// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4516// These can be any of:
4517//
4518// matrix * scalar
4519// scalar * matrix
4520// matrix * matrix linear algebraic
4521// matrix * vector
4522// vector * matrix
4523// matrix * matrix componentwise
4524// matrix op matrix op in {+, -, /}
4525// matrix op scalar op in {+, -, /}
4526// scalar op matrix op in {+, -, /}
4527//
John Kessenichead86222018-03-28 18:01:20 -06004528spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4529 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004530{
4531 bool firstClass = true;
4532
4533 // First, handle first-class matrix operations (* and matrix/scalar)
4534 switch (op) {
4535 case spv::OpFDiv:
4536 if (builder.isMatrix(left) && builder.isScalar(right)) {
4537 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004538 spv::Id resultType = builder.getTypeId(right);
4539 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004540 op = spv::OpMatrixTimesScalar;
4541 } else
4542 firstClass = false;
4543 break;
4544 case spv::OpMatrixTimesScalar:
4545 if (builder.isMatrix(right))
4546 std::swap(left, right);
4547 assert(builder.isScalar(right));
4548 break;
4549 case spv::OpVectorTimesMatrix:
4550 assert(builder.isVector(left));
4551 assert(builder.isMatrix(right));
4552 break;
4553 case spv::OpMatrixTimesVector:
4554 assert(builder.isMatrix(left));
4555 assert(builder.isVector(right));
4556 break;
4557 case spv::OpMatrixTimesMatrix:
4558 assert(builder.isMatrix(left));
4559 assert(builder.isMatrix(right));
4560 break;
4561 default:
4562 firstClass = false;
4563 break;
4564 }
4565
qining25262b32016-05-06 17:25:16 -04004566 if (firstClass) {
4567 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004568 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004569 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004570 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004571 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004572
LoopDawg592860c2016-06-09 08:57:35 -06004573 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004574 // The result type of all of them is the same type as the (a) matrix operand.
4575 // The algorithm is to:
4576 // - break the matrix(es) into vectors
4577 // - smear any scalar to a vector
4578 // - do vector operations
4579 // - make a matrix out the vector results
4580 switch (op) {
4581 case spv::OpFAdd:
4582 case spv::OpFSub:
4583 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004584 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004585 case spv::OpFMul:
4586 {
4587 // one time set up...
4588 bool leftMat = builder.isMatrix(left);
4589 bool rightMat = builder.isMatrix(right);
4590 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4591 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4592 spv::Id scalarType = builder.getScalarTypeId(typeId);
4593 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4594 std::vector<spv::Id> results;
4595 spv::Id smearVec = spv::NoResult;
4596 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004597 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004598 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004599 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004600
4601 // do each vector op
4602 for (unsigned int c = 0; c < numCols; ++c) {
4603 std::vector<unsigned int> indexes;
4604 indexes.push_back(c);
4605 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4606 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004607 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004608 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004609 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004610 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004611 }
4612
4613 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004614 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004615 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004616 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004617 }
4618 default:
4619 assert(0);
4620 return spv::NoResult;
4621 }
4622}
4623
John Kessenichead86222018-03-28 18:01:20 -06004624spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4625 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004626{
4627 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004628 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004629 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004630 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4631 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004632
4633 switch (op) {
4634 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004635 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004636 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004637 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004638 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004639 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004640 unaryOp = spv::OpSNegate;
4641 break;
4642
4643 case glslang::EOpLogicalNot:
4644 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004645 unaryOp = spv::OpLogicalNot;
4646 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004647 case glslang::EOpBitwiseNot:
4648 unaryOp = spv::OpNot;
4649 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004650
John Kessenich140f3df2015-06-26 16:58:36 -06004651 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004652 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004653 break;
4654 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004655 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004656 break;
4657 case glslang::EOpTranspose:
4658 unaryOp = spv::OpTranspose;
4659 break;
4660
4661 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004662 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004663 break;
4664 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004665 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004666 break;
4667 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004668 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004669 break;
4670 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004671 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004672 break;
4673 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004674 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004675 break;
4676 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004677 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004678 break;
4679 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004680 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004681 break;
4682 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004683 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004684 break;
4685
4686 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004687 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004688 break;
4689 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004690 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004691 break;
4692 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004693 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004694 break;
4695 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004696 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004697 break;
4698 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004699 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004700 break;
4701 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004702 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004703 break;
4704
4705 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004706 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004707 break;
4708 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004709 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004710 break;
4711
4712 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004713 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004714 break;
4715 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004716 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004717 break;
4718 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004719 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004720 break;
4721 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004722 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004723 break;
4724 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004725 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004726 break;
4727 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004728 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004729 break;
4730
4731 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004732 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004733 break;
4734 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004735 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004736 break;
4737 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004738 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004739 break;
4740 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004741 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004742 break;
4743 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004744 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004745 break;
4746 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004747 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004748 break;
4749
4750 case glslang::EOpIsNan:
4751 unaryOp = spv::OpIsNan;
4752 break;
4753 case glslang::EOpIsInf:
4754 unaryOp = spv::OpIsInf;
4755 break;
LoopDawg592860c2016-06-09 08:57:35 -06004756 case glslang::EOpIsFinite:
4757 unaryOp = spv::OpIsFinite;
4758 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004759
Rex Xucbc426e2015-12-15 16:03:10 +08004760 case glslang::EOpFloatBitsToInt:
4761 case glslang::EOpFloatBitsToUint:
4762 case glslang::EOpIntBitsToFloat:
4763 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004764 case glslang::EOpDoubleBitsToInt64:
4765 case glslang::EOpDoubleBitsToUint64:
4766 case glslang::EOpInt64BitsToDouble:
4767 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004768 case glslang::EOpFloat16BitsToInt16:
4769 case glslang::EOpFloat16BitsToUint16:
4770 case glslang::EOpInt16BitsToFloat16:
4771 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08004772 unaryOp = spv::OpBitcast;
4773 break;
4774
John Kessenich140f3df2015-06-26 16:58:36 -06004775 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004776 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004777 break;
4778 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004779 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004780 break;
4781 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004782 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004783 break;
4784 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004785 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004786 break;
4787 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004788 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004789 break;
4790 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004791 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004792 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004793 case glslang::EOpPackSnorm4x8:
4794 libCall = spv::GLSLstd450PackSnorm4x8;
4795 break;
4796 case glslang::EOpUnpackSnorm4x8:
4797 libCall = spv::GLSLstd450UnpackSnorm4x8;
4798 break;
4799 case glslang::EOpPackUnorm4x8:
4800 libCall = spv::GLSLstd450PackUnorm4x8;
4801 break;
4802 case glslang::EOpUnpackUnorm4x8:
4803 libCall = spv::GLSLstd450UnpackUnorm4x8;
4804 break;
4805 case glslang::EOpPackDouble2x32:
4806 libCall = spv::GLSLstd450PackDouble2x32;
4807 break;
4808 case glslang::EOpUnpackDouble2x32:
4809 libCall = spv::GLSLstd450UnpackDouble2x32;
4810 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004811
Rex Xu8ff43de2016-04-22 16:51:45 +08004812 case glslang::EOpPackInt2x32:
4813 case glslang::EOpUnpackInt2x32:
4814 case glslang::EOpPackUint2x32:
4815 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07004816 case glslang::EOpPack16:
4817 case glslang::EOpPack32:
4818 case glslang::EOpPack64:
4819 case glslang::EOpUnpack32:
4820 case glslang::EOpUnpack16:
4821 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08004822 case glslang::EOpPackInt2x16:
4823 case glslang::EOpUnpackInt2x16:
4824 case glslang::EOpPackUint2x16:
4825 case glslang::EOpUnpackUint2x16:
4826 case glslang::EOpPackInt4x16:
4827 case glslang::EOpUnpackInt4x16:
4828 case glslang::EOpPackUint4x16:
4829 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004830 case glslang::EOpPackFloat2x16:
4831 case glslang::EOpUnpackFloat2x16:
4832 unaryOp = spv::OpBitcast;
4833 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004834
John Kessenich140f3df2015-06-26 16:58:36 -06004835 case glslang::EOpDPdx:
4836 unaryOp = spv::OpDPdx;
4837 break;
4838 case glslang::EOpDPdy:
4839 unaryOp = spv::OpDPdy;
4840 break;
4841 case glslang::EOpFwidth:
4842 unaryOp = spv::OpFwidth;
4843 break;
4844 case glslang::EOpDPdxFine:
4845 unaryOp = spv::OpDPdxFine;
4846 break;
4847 case glslang::EOpDPdyFine:
4848 unaryOp = spv::OpDPdyFine;
4849 break;
4850 case glslang::EOpFwidthFine:
4851 unaryOp = spv::OpFwidthFine;
4852 break;
4853 case glslang::EOpDPdxCoarse:
4854 unaryOp = spv::OpDPdxCoarse;
4855 break;
4856 case glslang::EOpDPdyCoarse:
4857 unaryOp = spv::OpDPdyCoarse;
4858 break;
4859 case glslang::EOpFwidthCoarse:
4860 unaryOp = spv::OpFwidthCoarse;
4861 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004862 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08004863#ifdef AMD_EXTENSIONS
4864 if (typeProxy == glslang::EbtFloat16)
4865 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
4866#endif
Rex Xu7a26c172015-12-08 17:12:09 +08004867 libCall = spv::GLSLstd450InterpolateAtCentroid;
4868 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004869 case glslang::EOpAny:
4870 unaryOp = spv::OpAny;
4871 break;
4872 case glslang::EOpAll:
4873 unaryOp = spv::OpAll;
4874 break;
4875
4876 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004877 if (isFloat)
4878 libCall = spv::GLSLstd450FAbs;
4879 else
4880 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004881 break;
4882 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004883 if (isFloat)
4884 libCall = spv::GLSLstd450FSign;
4885 else
4886 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004887 break;
4888
John Kessenichfc51d282015-08-19 13:34:18 -06004889 case glslang::EOpAtomicCounterIncrement:
4890 case glslang::EOpAtomicCounterDecrement:
4891 case glslang::EOpAtomicCounter:
4892 {
4893 // Handle all of the atomics in one place, in createAtomicOperation()
4894 std::vector<spv::Id> operands;
4895 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06004896 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004897 }
4898
John Kessenichfc51d282015-08-19 13:34:18 -06004899 case glslang::EOpBitFieldReverse:
4900 unaryOp = spv::OpBitReverse;
4901 break;
4902 case glslang::EOpBitCount:
4903 unaryOp = spv::OpBitCount;
4904 break;
4905 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004906 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004907 break;
4908 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004909 if (isUnsigned)
4910 libCall = spv::GLSLstd450FindUMsb;
4911 else
4912 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004913 break;
4914
Rex Xu574ab042016-04-14 16:53:07 +08004915 case glslang::EOpBallot:
4916 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004917 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004918 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004919 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004920#ifdef AMD_EXTENSIONS
4921 case glslang::EOpMinInvocations:
4922 case glslang::EOpMaxInvocations:
4923 case glslang::EOpAddInvocations:
4924 case glslang::EOpMinInvocationsNonUniform:
4925 case glslang::EOpMaxInvocationsNonUniform:
4926 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004927 case glslang::EOpMinInvocationsInclusiveScan:
4928 case glslang::EOpMaxInvocationsInclusiveScan:
4929 case glslang::EOpAddInvocationsInclusiveScan:
4930 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4931 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4932 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4933 case glslang::EOpMinInvocationsExclusiveScan:
4934 case glslang::EOpMaxInvocationsExclusiveScan:
4935 case glslang::EOpAddInvocationsExclusiveScan:
4936 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4937 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4938 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004939#endif
Rex Xu51596642016-09-21 18:56:12 +08004940 {
4941 std::vector<spv::Id> operands;
4942 operands.push_back(operand);
4943 return createInvocationsOperation(op, typeId, operands, typeProxy);
4944 }
John Kessenich66011cb2018-03-06 16:12:04 -07004945 case glslang::EOpSubgroupAll:
4946 case glslang::EOpSubgroupAny:
4947 case glslang::EOpSubgroupAllEqual:
4948 case glslang::EOpSubgroupBroadcastFirst:
4949 case glslang::EOpSubgroupBallot:
4950 case glslang::EOpSubgroupInverseBallot:
4951 case glslang::EOpSubgroupBallotBitCount:
4952 case glslang::EOpSubgroupBallotInclusiveBitCount:
4953 case glslang::EOpSubgroupBallotExclusiveBitCount:
4954 case glslang::EOpSubgroupBallotFindLSB:
4955 case glslang::EOpSubgroupBallotFindMSB:
4956 case glslang::EOpSubgroupAdd:
4957 case glslang::EOpSubgroupMul:
4958 case glslang::EOpSubgroupMin:
4959 case glslang::EOpSubgroupMax:
4960 case glslang::EOpSubgroupAnd:
4961 case glslang::EOpSubgroupOr:
4962 case glslang::EOpSubgroupXor:
4963 case glslang::EOpSubgroupInclusiveAdd:
4964 case glslang::EOpSubgroupInclusiveMul:
4965 case glslang::EOpSubgroupInclusiveMin:
4966 case glslang::EOpSubgroupInclusiveMax:
4967 case glslang::EOpSubgroupInclusiveAnd:
4968 case glslang::EOpSubgroupInclusiveOr:
4969 case glslang::EOpSubgroupInclusiveXor:
4970 case glslang::EOpSubgroupExclusiveAdd:
4971 case glslang::EOpSubgroupExclusiveMul:
4972 case glslang::EOpSubgroupExclusiveMin:
4973 case glslang::EOpSubgroupExclusiveMax:
4974 case glslang::EOpSubgroupExclusiveAnd:
4975 case glslang::EOpSubgroupExclusiveOr:
4976 case glslang::EOpSubgroupExclusiveXor:
4977 case glslang::EOpSubgroupQuadSwapHorizontal:
4978 case glslang::EOpSubgroupQuadSwapVertical:
4979 case glslang::EOpSubgroupQuadSwapDiagonal: {
4980 std::vector<spv::Id> operands;
4981 operands.push_back(operand);
4982 return createSubgroupOperation(op, typeId, operands, typeProxy);
4983 }
Rex Xu9d93a232016-05-05 12:30:44 +08004984#ifdef AMD_EXTENSIONS
4985 case glslang::EOpMbcnt:
4986 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4987 libCall = spv::MbcntAMD;
4988 break;
4989
4990 case glslang::EOpCubeFaceIndex:
4991 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4992 libCall = spv::CubeFaceIndexAMD;
4993 break;
4994
4995 case glslang::EOpCubeFaceCoord:
4996 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4997 libCall = spv::CubeFaceCoordAMD;
4998 break;
4999#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005000#ifdef NV_EXTENSIONS
5001 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005002 unaryOp = spv::OpGroupNonUniformPartitionNV;
5003 break;
5004#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005005 default:
5006 return 0;
5007 }
5008
5009 spv::Id id;
5010 if (libCall >= 0) {
5011 std::vector<spv::Id> args;
5012 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08005013 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08005014 } else {
John Kessenich91cef522016-05-05 16:45:40 -06005015 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08005016 }
John Kessenich140f3df2015-06-26 16:58:36 -06005017
John Kessenichead86222018-03-28 18:01:20 -06005018 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005019 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005020 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005021}
5022
John Kessenich7a53f762016-01-20 11:19:27 -07005023// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06005024spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
5025 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07005026{
5027 // Handle unary operations vector by vector.
5028 // The result type is the same type as the original type.
5029 // The algorithm is to:
5030 // - break the matrix into vectors
5031 // - apply the operation to each vector
5032 // - make a matrix out the vector results
5033
5034 // get the types sorted out
5035 int numCols = builder.getNumColumns(operand);
5036 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08005037 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
5038 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07005039 std::vector<spv::Id> results;
5040
5041 // do each vector op
5042 for (int c = 0; c < numCols; ++c) {
5043 std::vector<unsigned int> indexes;
5044 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08005045 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
5046 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06005047 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06005048 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005049 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07005050 }
5051
5052 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06005053 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005054 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005055 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07005056}
5057
John Kessenichad7645f2018-06-04 19:11:25 -06005058// For converting integers where both the bitwidth and the signedness could
5059// change, but only do the width change here. The caller is still responsible
5060// for the signedness conversion.
5061spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07005062{
John Kessenichad7645f2018-06-04 19:11:25 -06005063 // Get the result type width, based on the type to convert to.
5064 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005065 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06005066 case glslang::EOpConvInt16ToUint8:
5067 case glslang::EOpConvIntToUint8:
5068 case glslang::EOpConvInt64ToUint8:
5069 case glslang::EOpConvUint16ToInt8:
5070 case glslang::EOpConvUintToInt8:
5071 case glslang::EOpConvUint64ToInt8:
5072 width = 8;
5073 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005074 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06005075 case glslang::EOpConvIntToUint16:
5076 case glslang::EOpConvInt64ToUint16:
5077 case glslang::EOpConvUint8ToInt16:
5078 case glslang::EOpConvUintToInt16:
5079 case glslang::EOpConvUint64ToInt16:
5080 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07005081 break;
5082 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06005083 case glslang::EOpConvInt16ToUint:
5084 case glslang::EOpConvInt64ToUint:
5085 case glslang::EOpConvUint8ToInt:
5086 case glslang::EOpConvUint16ToInt:
5087 case glslang::EOpConvUint64ToInt:
5088 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07005089 break;
5090 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005091 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005092 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005093 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005094 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005095 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06005096 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07005097 break;
5098
5099 default:
5100 assert(false && "Default missing");
5101 break;
5102 }
5103
John Kessenichad7645f2018-06-04 19:11:25 -06005104 // Get the conversion operation and result type,
5105 // based on the target width, but the source type.
5106 spv::Id type = spv::NoType;
5107 spv::Op convOp = spv::OpNop;
5108 switch(op) {
5109 case glslang::EOpConvInt8ToUint16:
5110 case glslang::EOpConvInt8ToUint:
5111 case glslang::EOpConvInt8ToUint64:
5112 case glslang::EOpConvInt16ToUint8:
5113 case glslang::EOpConvInt16ToUint:
5114 case glslang::EOpConvInt16ToUint64:
5115 case glslang::EOpConvIntToUint8:
5116 case glslang::EOpConvIntToUint16:
5117 case glslang::EOpConvIntToUint64:
5118 case glslang::EOpConvInt64ToUint8:
5119 case glslang::EOpConvInt64ToUint16:
5120 case glslang::EOpConvInt64ToUint:
5121 convOp = spv::OpSConvert;
5122 type = builder.makeIntType(width);
5123 break;
5124 default:
5125 convOp = spv::OpUConvert;
5126 type = builder.makeUintType(width);
5127 break;
5128 }
5129
John Kessenich66011cb2018-03-06 16:12:04 -07005130 if (vectorSize > 0)
5131 type = builder.makeVectorType(type, vectorSize);
5132
John Kessenichad7645f2018-06-04 19:11:25 -06005133 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07005134}
5135
John Kessenichead86222018-03-28 18:01:20 -06005136spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
5137 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06005138{
5139 spv::Op convOp = spv::OpNop;
5140 spv::Id zero = 0;
5141 spv::Id one = 0;
5142
5143 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
5144
5145 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07005146 case glslang::EOpConvInt8ToBool:
5147 case glslang::EOpConvUint8ToBool:
5148 zero = builder.makeUint8Constant(0);
5149 zero = makeSmearedConstant(zero, vectorSize);
5150 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08005151 case glslang::EOpConvInt16ToBool:
5152 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07005153 zero = builder.makeUint16Constant(0);
5154 zero = makeSmearedConstant(zero, vectorSize);
5155 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5156 case glslang::EOpConvIntToBool:
5157 case glslang::EOpConvUintToBool:
5158 zero = builder.makeUintConstant(0);
5159 zero = makeSmearedConstant(zero, vectorSize);
5160 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5161 case glslang::EOpConvInt64ToBool:
5162 case glslang::EOpConvUint64ToBool:
5163 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005164 zero = makeSmearedConstant(zero, vectorSize);
5165 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
5166
5167 case glslang::EOpConvFloatToBool:
5168 zero = builder.makeFloatConstant(0.0F);
5169 zero = makeSmearedConstant(zero, vectorSize);
5170 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5171
5172 case glslang::EOpConvDoubleToBool:
5173 zero = builder.makeDoubleConstant(0.0);
5174 zero = makeSmearedConstant(zero, vectorSize);
5175 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
5176
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005177 case glslang::EOpConvFloat16ToBool:
5178 zero = builder.makeFloat16Constant(0.0F);
5179 zero = makeSmearedConstant(zero, vectorSize);
5180 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005181
John Kessenich140f3df2015-06-26 16:58:36 -06005182 case glslang::EOpConvBoolToFloat:
5183 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005184 zero = builder.makeFloatConstant(0.0F);
5185 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06005186 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005187
John Kessenich140f3df2015-06-26 16:58:36 -06005188 case glslang::EOpConvBoolToDouble:
5189 convOp = spv::OpSelect;
5190 zero = builder.makeDoubleConstant(0.0);
5191 one = builder.makeDoubleConstant(1.0);
5192 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005193
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005194 case glslang::EOpConvBoolToFloat16:
5195 convOp = spv::OpSelect;
5196 zero = builder.makeFloat16Constant(0.0F);
5197 one = builder.makeFloat16Constant(1.0F);
5198 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005199
5200 case glslang::EOpConvBoolToInt8:
5201 zero = builder.makeInt8Constant(0);
5202 one = builder.makeInt8Constant(1);
5203 convOp = spv::OpSelect;
5204 break;
5205
5206 case glslang::EOpConvBoolToUint8:
5207 zero = builder.makeUint8Constant(0);
5208 one = builder.makeUint8Constant(1);
5209 convOp = spv::OpSelect;
5210 break;
5211
5212 case glslang::EOpConvBoolToInt16:
5213 zero = builder.makeInt16Constant(0);
5214 one = builder.makeInt16Constant(1);
5215 convOp = spv::OpSelect;
5216 break;
5217
5218 case glslang::EOpConvBoolToUint16:
5219 zero = builder.makeUint16Constant(0);
5220 one = builder.makeUint16Constant(1);
5221 convOp = spv::OpSelect;
5222 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005223
John Kessenich140f3df2015-06-26 16:58:36 -06005224 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005225 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005226 if (op == glslang::EOpConvBoolToInt64)
5227 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005228 else
5229 zero = builder.makeIntConstant(0);
5230
5231 if (op == glslang::EOpConvBoolToInt64)
5232 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005233 else
5234 one = builder.makeIntConstant(1);
5235
John Kessenich140f3df2015-06-26 16:58:36 -06005236 convOp = spv::OpSelect;
5237 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005238
John Kessenich140f3df2015-06-26 16:58:36 -06005239 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005240 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005241 if (op == glslang::EOpConvBoolToUint64)
5242 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005243 else
5244 zero = builder.makeUintConstant(0);
5245
5246 if (op == glslang::EOpConvBoolToUint64)
5247 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005248 else
5249 one = builder.makeUintConstant(1);
5250
John Kessenich140f3df2015-06-26 16:58:36 -06005251 convOp = spv::OpSelect;
5252 break;
5253
John Kessenich66011cb2018-03-06 16:12:04 -07005254 case glslang::EOpConvInt8ToFloat16:
5255 case glslang::EOpConvInt8ToFloat:
5256 case glslang::EOpConvInt8ToDouble:
5257 case glslang::EOpConvInt16ToFloat16:
5258 case glslang::EOpConvInt16ToFloat:
5259 case glslang::EOpConvInt16ToDouble:
5260 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005261 case glslang::EOpConvIntToFloat:
5262 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005263 case glslang::EOpConvInt64ToFloat:
5264 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005265 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005266 convOp = spv::OpConvertSToF;
5267 break;
5268
John Kessenich66011cb2018-03-06 16:12:04 -07005269 case glslang::EOpConvUint8ToFloat16:
5270 case glslang::EOpConvUint8ToFloat:
5271 case glslang::EOpConvUint8ToDouble:
5272 case glslang::EOpConvUint16ToFloat16:
5273 case glslang::EOpConvUint16ToFloat:
5274 case glslang::EOpConvUint16ToDouble:
5275 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005276 case glslang::EOpConvUintToFloat:
5277 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005278 case glslang::EOpConvUint64ToFloat:
5279 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005280 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005281 convOp = spv::OpConvertUToF;
5282 break;
5283
5284 case glslang::EOpConvDoubleToFloat:
5285 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005286 case glslang::EOpConvDoubleToFloat16:
5287 case glslang::EOpConvFloat16ToDouble:
5288 case glslang::EOpConvFloatToFloat16:
5289 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005290 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005291 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005292 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005293 break;
5294
John Kessenich66011cb2018-03-06 16:12:04 -07005295 case glslang::EOpConvFloat16ToInt8:
5296 case glslang::EOpConvFloatToInt8:
5297 case glslang::EOpConvDoubleToInt8:
5298 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005299 case glslang::EOpConvFloatToInt16:
5300 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005301 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005302 case glslang::EOpConvFloatToInt:
5303 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005304 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005305 case glslang::EOpConvFloatToInt64:
5306 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005307 convOp = spv::OpConvertFToS;
5308 break;
5309
John Kessenich66011cb2018-03-06 16:12:04 -07005310 case glslang::EOpConvUint8ToInt8:
5311 case glslang::EOpConvInt8ToUint8:
5312 case glslang::EOpConvUint16ToInt16:
5313 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005314 case glslang::EOpConvUintToInt:
5315 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005316 case glslang::EOpConvUint64ToInt64:
5317 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005318 if (builder.isInSpecConstCodeGenMode()) {
5319 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005320 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5321 zero = builder.makeUint8Constant(0);
5322 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005323 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005324 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5325 zero = builder.makeUint64Constant(0);
5326 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005327 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005328 }
qining189b2032016-04-12 23:16:20 -04005329 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005330 // Use OpIAdd, instead of OpBitcast to do the conversion when
5331 // generating for OpSpecConstantOp instruction.
5332 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5333 }
5334 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005335 convOp = spv::OpBitcast;
5336 break;
5337
John Kessenich66011cb2018-03-06 16:12:04 -07005338 case glslang::EOpConvFloat16ToUint8:
5339 case glslang::EOpConvFloatToUint8:
5340 case glslang::EOpConvDoubleToUint8:
5341 case glslang::EOpConvFloat16ToUint16:
5342 case glslang::EOpConvFloatToUint16:
5343 case glslang::EOpConvDoubleToUint16:
5344 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005345 case glslang::EOpConvFloatToUint:
5346 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005347 case glslang::EOpConvFloatToUint64:
5348 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005349 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005350 convOp = spv::OpConvertFToU;
5351 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005352
John Kessenich66011cb2018-03-06 16:12:04 -07005353 case glslang::EOpConvInt8ToInt16:
5354 case glslang::EOpConvInt8ToInt:
5355 case glslang::EOpConvInt8ToInt64:
5356 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005357 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005358 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005359 case glslang::EOpConvIntToInt8:
5360 case glslang::EOpConvIntToInt16:
5361 case glslang::EOpConvIntToInt64:
5362 case glslang::EOpConvInt64ToInt8:
5363 case glslang::EOpConvInt64ToInt16:
5364 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005365 convOp = spv::OpSConvert;
5366 break;
5367
John Kessenich66011cb2018-03-06 16:12:04 -07005368 case glslang::EOpConvUint8ToUint16:
5369 case glslang::EOpConvUint8ToUint:
5370 case glslang::EOpConvUint8ToUint64:
5371 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005372 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005373 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005374 case glslang::EOpConvUintToUint8:
5375 case glslang::EOpConvUintToUint16:
5376 case glslang::EOpConvUintToUint64:
5377 case glslang::EOpConvUint64ToUint8:
5378 case glslang::EOpConvUint64ToUint16:
5379 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005380 convOp = spv::OpUConvert;
5381 break;
5382
John Kessenich66011cb2018-03-06 16:12:04 -07005383 case glslang::EOpConvInt8ToUint16:
5384 case glslang::EOpConvInt8ToUint:
5385 case glslang::EOpConvInt8ToUint64:
5386 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005387 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005388 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005389 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005390 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005391 case glslang::EOpConvIntToUint64:
5392 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005393 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005394 case glslang::EOpConvInt64ToUint:
5395 case glslang::EOpConvUint8ToInt16:
5396 case glslang::EOpConvUint8ToInt:
5397 case glslang::EOpConvUint8ToInt64:
5398 case glslang::EOpConvUint16ToInt8:
5399 case glslang::EOpConvUint16ToInt:
5400 case glslang::EOpConvUint16ToInt64:
5401 case glslang::EOpConvUintToInt8:
5402 case glslang::EOpConvUintToInt16:
5403 case glslang::EOpConvUintToInt64:
5404 case glslang::EOpConvUint64ToInt8:
5405 case glslang::EOpConvUint64ToInt16:
5406 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005407 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005408 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005409
5410 if (builder.isInSpecConstCodeGenMode()) {
5411 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005412 switch(op) {
5413 case glslang::EOpConvInt16ToUint8:
5414 case glslang::EOpConvIntToUint8:
5415 case glslang::EOpConvInt64ToUint8:
5416 case glslang::EOpConvUint16ToInt8:
5417 case glslang::EOpConvUintToInt8:
5418 case glslang::EOpConvUint64ToInt8:
5419 zero = builder.makeUint8Constant(0);
5420 break;
5421 case glslang::EOpConvInt8ToUint16:
5422 case glslang::EOpConvIntToUint16:
5423 case glslang::EOpConvInt64ToUint16:
5424 case glslang::EOpConvUint8ToInt16:
5425 case glslang::EOpConvUintToInt16:
5426 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005427 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005428 break;
5429 case glslang::EOpConvInt8ToUint:
5430 case glslang::EOpConvInt16ToUint:
5431 case glslang::EOpConvInt64ToUint:
5432 case glslang::EOpConvUint8ToInt:
5433 case glslang::EOpConvUint16ToInt:
5434 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005435 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005436 break;
5437 case glslang::EOpConvInt8ToUint64:
5438 case glslang::EOpConvInt16ToUint64:
5439 case glslang::EOpConvIntToUint64:
5440 case glslang::EOpConvUint8ToInt64:
5441 case glslang::EOpConvUint16ToInt64:
5442 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005443 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005444 break;
5445 default:
5446 assert(false && "Default missing");
5447 break;
5448 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005449 zero = makeSmearedConstant(zero, vectorSize);
5450 // Use OpIAdd, instead of OpBitcast to do the conversion when
5451 // generating for OpSpecConstantOp instruction.
5452 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5453 }
5454 // For normal run-time conversion instruction, use OpBitcast.
5455 convOp = spv::OpBitcast;
5456 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005457 default:
5458 break;
5459 }
5460
5461 spv::Id result = 0;
5462 if (convOp == spv::OpNop)
5463 return result;
5464
5465 if (convOp == spv::OpSelect) {
5466 zero = makeSmearedConstant(zero, vectorSize);
5467 one = makeSmearedConstant(one, vectorSize);
5468 result = builder.createTriOp(convOp, destType, operand, one, zero);
5469 } else
5470 result = builder.createUnaryOp(convOp, destType, operand);
5471
John Kessenichead86222018-03-28 18:01:20 -06005472 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005473 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005474 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005475}
5476
5477spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5478{
5479 if (vectorSize == 0)
5480 return constant;
5481
5482 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5483 std::vector<spv::Id> components;
5484 for (int c = 0; c < vectorSize; ++c)
5485 components.push_back(constant);
5486 return builder.makeCompositeConstant(vectorTypeId, components);
5487}
5488
John Kessenich426394d2015-07-23 10:22:48 -06005489// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005490spv::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 -06005491{
5492 spv::Op opCode = spv::OpNop;
5493
5494 switch (op) {
5495 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005496 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005497 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005498 opCode = spv::OpAtomicIAdd;
5499 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005500 case glslang::EOpAtomicCounterSubtract:
5501 opCode = spv::OpAtomicISub;
5502 break;
John Kessenich426394d2015-07-23 10:22:48 -06005503 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005504 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005505 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005506 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005507 break;
5508 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005509 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005510 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005511 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005512 break;
5513 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005514 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005515 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005516 opCode = spv::OpAtomicAnd;
5517 break;
5518 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005519 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005520 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005521 opCode = spv::OpAtomicOr;
5522 break;
5523 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005524 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005525 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005526 opCode = spv::OpAtomicXor;
5527 break;
5528 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005529 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005530 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005531 opCode = spv::OpAtomicExchange;
5532 break;
5533 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005534 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005535 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005536 opCode = spv::OpAtomicCompareExchange;
5537 break;
5538 case glslang::EOpAtomicCounterIncrement:
5539 opCode = spv::OpAtomicIIncrement;
5540 break;
5541 case glslang::EOpAtomicCounterDecrement:
5542 opCode = spv::OpAtomicIDecrement;
5543 break;
5544 case glslang::EOpAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05005545 case glslang::EOpImageAtomicLoad:
5546 case glslang::EOpAtomicLoad:
John Kessenich426394d2015-07-23 10:22:48 -06005547 opCode = spv::OpAtomicLoad;
5548 break;
Jeff Bolz36831c92018-09-05 10:11:41 -05005549 case glslang::EOpAtomicStore:
5550 case glslang::EOpImageAtomicStore:
5551 opCode = spv::OpAtomicStore;
5552 break;
John Kessenich426394d2015-07-23 10:22:48 -06005553 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005554 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005555 break;
5556 }
5557
Rex Xue8fe8b02017-09-26 15:42:56 +08005558 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5559 builder.addCapability(spv::CapabilityInt64Atomics);
5560
John Kessenich426394d2015-07-23 10:22:48 -06005561 // Sort out the operands
5562 // - mapping from glslang -> SPV
Jeff Bolz36831c92018-09-05 10:11:41 -05005563 // - there are extra SPV operands that are optional in glslang
John Kessenich3e60a6f2015-09-14 22:45:16 -06005564 // - compare-exchange swaps the value and comparator
5565 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005566 // - EOpAtomicCounterDecrement needs a post decrement
Jeff Bolz36831c92018-09-05 10:11:41 -05005567 spv::Id pointerId = 0, compareId = 0, valueId = 0;
5568 // scope defaults to Device in the old model, QueueFamilyKHR in the new model
5569 spv::Id scopeId;
5570 if (glslangIntermediate->usingVulkanMemoryModel()) {
5571 scopeId = builder.makeUintConstant(spv::ScopeQueueFamilyKHR);
5572 } else {
5573 scopeId = builder.makeUintConstant(spv::ScopeDevice);
5574 }
5575 // semantics default to relaxed
5576 spv::Id semanticsId = builder.makeUintConstant(spv::MemorySemanticsMaskNone);
5577 spv::Id semanticsId2 = semanticsId;
5578
5579 pointerId = operands[0];
5580 if (opCode == spv::OpAtomicIIncrement || opCode == spv::OpAtomicIDecrement) {
5581 // no additional operands
5582 } else if (opCode == spv::OpAtomicCompareExchange) {
5583 compareId = operands[1];
5584 valueId = operands[2];
5585 if (operands.size() > 3) {
5586 scopeId = operands[3];
5587 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[4]) | builder.getConstantScalar(operands[5]));
5588 semanticsId2 = builder.makeUintConstant(builder.getConstantScalar(operands[6]) | builder.getConstantScalar(operands[7]));
5589 }
5590 } else if (opCode == spv::OpAtomicLoad) {
5591 if (operands.size() > 1) {
5592 scopeId = operands[1];
5593 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]));
5594 }
5595 } else {
5596 // atomic store or RMW
5597 valueId = operands[1];
5598 if (operands.size() > 2) {
5599 scopeId = operands[2];
5600 semanticsId = builder.makeUintConstant(builder.getConstantScalar(operands[3]) | builder.getConstantScalar(operands[4]));
5601 }
Rex Xu04db3f52015-09-16 11:44:02 +08005602 }
John Kessenich426394d2015-07-23 10:22:48 -06005603
Jeff Bolz36831c92018-09-05 10:11:41 -05005604 // Check for capabilities
5605 unsigned semanticsImmediate = builder.getConstantScalar(semanticsId) | builder.getConstantScalar(semanticsId2);
5606 if (semanticsImmediate & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
5607 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
5608 }
John Kessenich426394d2015-07-23 10:22:48 -06005609
Jeff Bolz36831c92018-09-05 10:11:41 -05005610 if (glslangIntermediate->usingVulkanMemoryModel() && builder.getConstantScalar(scopeId) == spv::ScopeDevice) {
5611 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
5612 }
John Kessenich48d6e792017-10-06 21:21:48 -06005613
Jeff Bolz36831c92018-09-05 10:11:41 -05005614 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5615 spvAtomicOperands.push_back(pointerId);
5616 spvAtomicOperands.push_back(scopeId);
5617 spvAtomicOperands.push_back(semanticsId);
5618 if (opCode == spv::OpAtomicCompareExchange) {
5619 spvAtomicOperands.push_back(semanticsId2);
5620 spvAtomicOperands.push_back(valueId);
5621 spvAtomicOperands.push_back(compareId);
5622 } else if (opCode != spv::OpAtomicLoad && opCode != spv::OpAtomicIIncrement && opCode != spv::OpAtomicIDecrement) {
5623 spvAtomicOperands.push_back(valueId);
5624 }
John Kessenich48d6e792017-10-06 21:21:48 -06005625
Jeff Bolz36831c92018-09-05 10:11:41 -05005626 if (opCode == spv::OpAtomicStore) {
5627 builder.createNoResultOp(opCode, spvAtomicOperands);
5628 return 0;
5629 } else {
5630 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5631
5632 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5633 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5634 if (op == glslang::EOpAtomicCounterDecrement)
5635 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5636
5637 return resultId;
5638 }
John Kessenich426394d2015-07-23 10:22:48 -06005639}
5640
John Kessenich91cef522016-05-05 16:45:40 -06005641// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005642spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005643{
Corentin Walleze7061422018-08-08 15:20:15 +02005644#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07005645 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5646 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02005647#endif
Rex Xu9d93a232016-05-05 12:30:44 +08005648
Rex Xu51596642016-09-21 18:56:12 +08005649 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06005650 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005651 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5652
chaocf200da82016-12-20 12:44:35 -08005653 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5654 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005655 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5656 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005657 } else if (op == glslang::EOpAnyInvocation ||
5658 op == glslang::EOpAllInvocations ||
5659 op == glslang::EOpAllInvocationsEqual) {
5660 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5661 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005662 } else {
5663 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005664#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005665 if (op == glslang::EOpMinInvocationsNonUniform ||
5666 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005667 op == glslang::EOpAddInvocationsNonUniform ||
5668 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5669 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5670 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5671 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5672 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5673 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005674 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005675#endif
Rex Xu51596642016-09-21 18:56:12 +08005676
Rex Xu9d93a232016-05-05 12:30:44 +08005677#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005678 switch (op) {
5679 case glslang::EOpMinInvocations:
5680 case glslang::EOpMaxInvocations:
5681 case glslang::EOpAddInvocations:
5682 case glslang::EOpMinInvocationsNonUniform:
5683 case glslang::EOpMaxInvocationsNonUniform:
5684 case glslang::EOpAddInvocationsNonUniform:
5685 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08005686 break;
5687 case glslang::EOpMinInvocationsInclusiveScan:
5688 case glslang::EOpMaxInvocationsInclusiveScan:
5689 case glslang::EOpAddInvocationsInclusiveScan:
5690 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5691 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5692 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5693 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005694 break;
5695 case glslang::EOpMinInvocationsExclusiveScan:
5696 case glslang::EOpMaxInvocationsExclusiveScan:
5697 case glslang::EOpAddInvocationsExclusiveScan:
5698 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5699 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5700 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5701 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005702 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005703 default:
5704 break;
Rex Xu430ef402016-10-14 17:22:23 +08005705 }
John Kessenich149afc32018-08-14 13:31:43 -06005706 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5707 spvGroupOperands.push_back(scope);
5708 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06005709 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06005710 spvGroupOperands.push_back(groupOp);
5711 }
Rex Xu9d93a232016-05-05 12:30:44 +08005712#endif
Rex Xu51596642016-09-21 18:56:12 +08005713 }
5714
John Kessenich149afc32018-08-14 13:31:43 -06005715 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
5716 spv::IdImmediate op = { true, *opIt };
5717 spvGroupOperands.push_back(op);
5718 }
John Kessenich91cef522016-05-05 16:45:40 -06005719
5720 switch (op) {
5721 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005722 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005723 break;
John Kessenich91cef522016-05-05 16:45:40 -06005724 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005725 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005726 break;
John Kessenich91cef522016-05-05 16:45:40 -06005727 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005728 opCode = spv::OpSubgroupAllEqualKHR;
5729 break;
Rex Xu51596642016-09-21 18:56:12 +08005730 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005731 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005732 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005733 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005734 break;
5735 case glslang::EOpReadFirstInvocation:
5736 opCode = spv::OpSubgroupFirstInvocationKHR;
5737 break;
5738 case glslang::EOpBallot:
5739 {
5740 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5741 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5742 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5743 //
5744 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5745 //
5746 spv::Id uintType = builder.makeUintType(32);
5747 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5748 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5749
5750 std::vector<spv::Id> components;
5751 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5752 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5753
5754 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5755 return builder.createUnaryOp(spv::OpBitcast, typeId,
5756 builder.createCompositeConstruct(uvec2Type, components));
5757 }
5758
Rex Xu9d93a232016-05-05 12:30:44 +08005759#ifdef AMD_EXTENSIONS
5760 case glslang::EOpMinInvocations:
5761 case glslang::EOpMaxInvocations:
5762 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005763 case glslang::EOpMinInvocationsInclusiveScan:
5764 case glslang::EOpMaxInvocationsInclusiveScan:
5765 case glslang::EOpAddInvocationsInclusiveScan:
5766 case glslang::EOpMinInvocationsExclusiveScan:
5767 case glslang::EOpMaxInvocationsExclusiveScan:
5768 case glslang::EOpAddInvocationsExclusiveScan:
5769 if (op == glslang::EOpMinInvocations ||
5770 op == glslang::EOpMinInvocationsInclusiveScan ||
5771 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005772 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005773 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005774 else {
5775 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005776 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005777 else
Rex Xu51596642016-09-21 18:56:12 +08005778 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005779 }
Rex Xu430ef402016-10-14 17:22:23 +08005780 } else if (op == glslang::EOpMaxInvocations ||
5781 op == glslang::EOpMaxInvocationsInclusiveScan ||
5782 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005783 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005784 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005785 else {
5786 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005787 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005788 else
Rex Xu51596642016-09-21 18:56:12 +08005789 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005790 }
5791 } else {
5792 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005793 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005794 else
Rex Xu51596642016-09-21 18:56:12 +08005795 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005796 }
5797
Rex Xu2bbbe062016-08-23 15:41:05 +08005798 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005799 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005800
5801 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005802 case glslang::EOpMinInvocationsNonUniform:
5803 case glslang::EOpMaxInvocationsNonUniform:
5804 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005805 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5806 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5807 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5808 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5809 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5810 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5811 if (op == glslang::EOpMinInvocationsNonUniform ||
5812 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5813 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005814 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005815 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005816 else {
5817 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005818 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005819 else
Rex Xu51596642016-09-21 18:56:12 +08005820 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005821 }
5822 }
Rex Xu430ef402016-10-14 17:22:23 +08005823 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5824 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5825 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005826 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005827 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005828 else {
5829 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005830 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005831 else
Rex Xu51596642016-09-21 18:56:12 +08005832 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005833 }
5834 }
5835 else {
5836 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005837 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005838 else
Rex Xu51596642016-09-21 18:56:12 +08005839 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005840 }
5841
Rex Xu2bbbe062016-08-23 15:41:05 +08005842 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005843 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005844
5845 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005846#endif
John Kessenich91cef522016-05-05 16:45:40 -06005847 default:
5848 logger->missingFunctionality("invocation operation");
5849 return spv::NoResult;
5850 }
Rex Xu51596642016-09-21 18:56:12 +08005851
5852 assert(opCode != spv::OpNop);
5853 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005854}
5855
Rex Xu2bbbe062016-08-23 15:41:05 +08005856// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06005857spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
5858 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005859{
Rex Xub7072052016-09-26 15:53:40 +08005860#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005861 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5862 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005863 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005864 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005865 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5866 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5867 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005868#else
5869 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5870 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005871 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5872 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005873#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005874
5875 // Handle group invocation operations scalar by scalar.
5876 // The result type is the same type as the original type.
5877 // The algorithm is to:
5878 // - break the vector into scalars
5879 // - apply the operation to each scalar
5880 // - make a vector out the scalar results
5881
5882 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005883 int numComponents = builder.getNumComponents(operands[0]);
5884 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005885 std::vector<spv::Id> results;
5886
5887 // do each scalar op
5888 for (int comp = 0; comp < numComponents; ++comp) {
5889 std::vector<unsigned int> indexes;
5890 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06005891 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
5892 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005893 if (op == spv::OpSubgroupReadInvocationKHR) {
5894 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06005895 spv::IdImmediate operand = { true, operands[1] };
5896 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08005897 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06005898 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5899 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08005900 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06005901 spv::IdImmediate operand = { true, operands[1] };
5902 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08005903 } else {
John Kessenich149afc32018-08-14 13:31:43 -06005904 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5905 spvGroupOperands.push_back(scope);
John Kessenichd122a722018-09-18 03:43:30 -06005906 spv::IdImmediate groupOp = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06005907 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08005908 spvGroupOperands.push_back(scalar);
5909 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005910
Rex Xub7072052016-09-26 15:53:40 +08005911 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005912 }
5913
5914 // put the pieces together
5915 return builder.createCompositeConstruct(typeId, results);
5916}
Rex Xu2bbbe062016-08-23 15:41:05 +08005917
John Kessenich66011cb2018-03-06 16:12:04 -07005918// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06005919spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
5920 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07005921{
5922 // Add the required capabilities.
5923 switch (op) {
5924 case glslang::EOpSubgroupElect:
5925 builder.addCapability(spv::CapabilityGroupNonUniform);
5926 break;
5927 case glslang::EOpSubgroupAll:
5928 case glslang::EOpSubgroupAny:
5929 case glslang::EOpSubgroupAllEqual:
5930 builder.addCapability(spv::CapabilityGroupNonUniform);
5931 builder.addCapability(spv::CapabilityGroupNonUniformVote);
5932 break;
5933 case glslang::EOpSubgroupBroadcast:
5934 case glslang::EOpSubgroupBroadcastFirst:
5935 case glslang::EOpSubgroupBallot:
5936 case glslang::EOpSubgroupInverseBallot:
5937 case glslang::EOpSubgroupBallotBitExtract:
5938 case glslang::EOpSubgroupBallotBitCount:
5939 case glslang::EOpSubgroupBallotInclusiveBitCount:
5940 case glslang::EOpSubgroupBallotExclusiveBitCount:
5941 case glslang::EOpSubgroupBallotFindLSB:
5942 case glslang::EOpSubgroupBallotFindMSB:
5943 builder.addCapability(spv::CapabilityGroupNonUniform);
5944 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
5945 break;
5946 case glslang::EOpSubgroupShuffle:
5947 case glslang::EOpSubgroupShuffleXor:
5948 builder.addCapability(spv::CapabilityGroupNonUniform);
5949 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
5950 break;
5951 case glslang::EOpSubgroupShuffleUp:
5952 case glslang::EOpSubgroupShuffleDown:
5953 builder.addCapability(spv::CapabilityGroupNonUniform);
5954 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
5955 break;
5956 case glslang::EOpSubgroupAdd:
5957 case glslang::EOpSubgroupMul:
5958 case glslang::EOpSubgroupMin:
5959 case glslang::EOpSubgroupMax:
5960 case glslang::EOpSubgroupAnd:
5961 case glslang::EOpSubgroupOr:
5962 case glslang::EOpSubgroupXor:
5963 case glslang::EOpSubgroupInclusiveAdd:
5964 case glslang::EOpSubgroupInclusiveMul:
5965 case glslang::EOpSubgroupInclusiveMin:
5966 case glslang::EOpSubgroupInclusiveMax:
5967 case glslang::EOpSubgroupInclusiveAnd:
5968 case glslang::EOpSubgroupInclusiveOr:
5969 case glslang::EOpSubgroupInclusiveXor:
5970 case glslang::EOpSubgroupExclusiveAdd:
5971 case glslang::EOpSubgroupExclusiveMul:
5972 case glslang::EOpSubgroupExclusiveMin:
5973 case glslang::EOpSubgroupExclusiveMax:
5974 case glslang::EOpSubgroupExclusiveAnd:
5975 case glslang::EOpSubgroupExclusiveOr:
5976 case glslang::EOpSubgroupExclusiveXor:
5977 builder.addCapability(spv::CapabilityGroupNonUniform);
5978 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
5979 break;
5980 case glslang::EOpSubgroupClusteredAdd:
5981 case glslang::EOpSubgroupClusteredMul:
5982 case glslang::EOpSubgroupClusteredMin:
5983 case glslang::EOpSubgroupClusteredMax:
5984 case glslang::EOpSubgroupClusteredAnd:
5985 case glslang::EOpSubgroupClusteredOr:
5986 case glslang::EOpSubgroupClusteredXor:
5987 builder.addCapability(spv::CapabilityGroupNonUniform);
5988 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
5989 break;
5990 case glslang::EOpSubgroupQuadBroadcast:
5991 case glslang::EOpSubgroupQuadSwapHorizontal:
5992 case glslang::EOpSubgroupQuadSwapVertical:
5993 case glslang::EOpSubgroupQuadSwapDiagonal:
5994 builder.addCapability(spv::CapabilityGroupNonUniform);
5995 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
5996 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005997#ifdef NV_EXTENSIONS
5998 case glslang::EOpSubgroupPartitionedAdd:
5999 case glslang::EOpSubgroupPartitionedMul:
6000 case glslang::EOpSubgroupPartitionedMin:
6001 case glslang::EOpSubgroupPartitionedMax:
6002 case glslang::EOpSubgroupPartitionedAnd:
6003 case glslang::EOpSubgroupPartitionedOr:
6004 case glslang::EOpSubgroupPartitionedXor:
6005 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6006 case glslang::EOpSubgroupPartitionedInclusiveMul:
6007 case glslang::EOpSubgroupPartitionedInclusiveMin:
6008 case glslang::EOpSubgroupPartitionedInclusiveMax:
6009 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6010 case glslang::EOpSubgroupPartitionedInclusiveOr:
6011 case glslang::EOpSubgroupPartitionedInclusiveXor:
6012 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6013 case glslang::EOpSubgroupPartitionedExclusiveMul:
6014 case glslang::EOpSubgroupPartitionedExclusiveMin:
6015 case glslang::EOpSubgroupPartitionedExclusiveMax:
6016 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6017 case glslang::EOpSubgroupPartitionedExclusiveOr:
6018 case glslang::EOpSubgroupPartitionedExclusiveXor:
6019 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
6020 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
6021 break;
6022#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006023 default: assert(0 && "Unhandled subgroup operation!");
6024 }
6025
6026 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
6027 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
6028 const bool isBool = typeProxy == glslang::EbtBool;
6029
6030 spv::Op opCode = spv::OpNop;
6031
6032 // Figure out which opcode to use.
6033 switch (op) {
6034 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
6035 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
6036 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
6037 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
6038 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
6039 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
6040 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
6041 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
6042 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
6043 case glslang::EOpSubgroupBallotBitCount:
6044 case glslang::EOpSubgroupBallotInclusiveBitCount:
6045 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
6046 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
6047 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
6048 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
6049 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
6050 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
6051 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
6052 case glslang::EOpSubgroupAdd:
6053 case glslang::EOpSubgroupInclusiveAdd:
6054 case glslang::EOpSubgroupExclusiveAdd:
6055 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006056#ifdef NV_EXTENSIONS
6057 case glslang::EOpSubgroupPartitionedAdd:
6058 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6059 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6060#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006061 if (isFloat) {
6062 opCode = spv::OpGroupNonUniformFAdd;
6063 } else {
6064 opCode = spv::OpGroupNonUniformIAdd;
6065 }
6066 break;
6067 case glslang::EOpSubgroupMul:
6068 case glslang::EOpSubgroupInclusiveMul:
6069 case glslang::EOpSubgroupExclusiveMul:
6070 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006071#ifdef NV_EXTENSIONS
6072 case glslang::EOpSubgroupPartitionedMul:
6073 case glslang::EOpSubgroupPartitionedInclusiveMul:
6074 case glslang::EOpSubgroupPartitionedExclusiveMul:
6075#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006076 if (isFloat) {
6077 opCode = spv::OpGroupNonUniformFMul;
6078 } else {
6079 opCode = spv::OpGroupNonUniformIMul;
6080 }
6081 break;
6082 case glslang::EOpSubgroupMin:
6083 case glslang::EOpSubgroupInclusiveMin:
6084 case glslang::EOpSubgroupExclusiveMin:
6085 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006086#ifdef NV_EXTENSIONS
6087 case glslang::EOpSubgroupPartitionedMin:
6088 case glslang::EOpSubgroupPartitionedInclusiveMin:
6089 case glslang::EOpSubgroupPartitionedExclusiveMin:
6090#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006091 if (isFloat) {
6092 opCode = spv::OpGroupNonUniformFMin;
6093 } else if (isUnsigned) {
6094 opCode = spv::OpGroupNonUniformUMin;
6095 } else {
6096 opCode = spv::OpGroupNonUniformSMin;
6097 }
6098 break;
6099 case glslang::EOpSubgroupMax:
6100 case glslang::EOpSubgroupInclusiveMax:
6101 case glslang::EOpSubgroupExclusiveMax:
6102 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006103#ifdef NV_EXTENSIONS
6104 case glslang::EOpSubgroupPartitionedMax:
6105 case glslang::EOpSubgroupPartitionedInclusiveMax:
6106 case glslang::EOpSubgroupPartitionedExclusiveMax:
6107#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006108 if (isFloat) {
6109 opCode = spv::OpGroupNonUniformFMax;
6110 } else if (isUnsigned) {
6111 opCode = spv::OpGroupNonUniformUMax;
6112 } else {
6113 opCode = spv::OpGroupNonUniformSMax;
6114 }
6115 break;
6116 case glslang::EOpSubgroupAnd:
6117 case glslang::EOpSubgroupInclusiveAnd:
6118 case glslang::EOpSubgroupExclusiveAnd:
6119 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006120#ifdef NV_EXTENSIONS
6121 case glslang::EOpSubgroupPartitionedAnd:
6122 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6123 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6124#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006125 if (isBool) {
6126 opCode = spv::OpGroupNonUniformLogicalAnd;
6127 } else {
6128 opCode = spv::OpGroupNonUniformBitwiseAnd;
6129 }
6130 break;
6131 case glslang::EOpSubgroupOr:
6132 case glslang::EOpSubgroupInclusiveOr:
6133 case glslang::EOpSubgroupExclusiveOr:
6134 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006135#ifdef NV_EXTENSIONS
6136 case glslang::EOpSubgroupPartitionedOr:
6137 case glslang::EOpSubgroupPartitionedInclusiveOr:
6138 case glslang::EOpSubgroupPartitionedExclusiveOr:
6139#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006140 if (isBool) {
6141 opCode = spv::OpGroupNonUniformLogicalOr;
6142 } else {
6143 opCode = spv::OpGroupNonUniformBitwiseOr;
6144 }
6145 break;
6146 case glslang::EOpSubgroupXor:
6147 case glslang::EOpSubgroupInclusiveXor:
6148 case glslang::EOpSubgroupExclusiveXor:
6149 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006150#ifdef NV_EXTENSIONS
6151 case glslang::EOpSubgroupPartitionedXor:
6152 case glslang::EOpSubgroupPartitionedInclusiveXor:
6153 case glslang::EOpSubgroupPartitionedExclusiveXor:
6154#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006155 if (isBool) {
6156 opCode = spv::OpGroupNonUniformLogicalXor;
6157 } else {
6158 opCode = spv::OpGroupNonUniformBitwiseXor;
6159 }
6160 break;
6161 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
6162 case glslang::EOpSubgroupQuadSwapHorizontal:
6163 case glslang::EOpSubgroupQuadSwapVertical:
6164 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
6165 default: assert(0 && "Unhandled subgroup operation!");
6166 }
6167
John Kessenich149afc32018-08-14 13:31:43 -06006168 // get the right Group Operation
6169 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07006170 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06006171 default:
6172 break;
John Kessenich66011cb2018-03-06 16:12:04 -07006173 case glslang::EOpSubgroupBallotBitCount:
6174 case glslang::EOpSubgroupAdd:
6175 case glslang::EOpSubgroupMul:
6176 case glslang::EOpSubgroupMin:
6177 case glslang::EOpSubgroupMax:
6178 case glslang::EOpSubgroupAnd:
6179 case glslang::EOpSubgroupOr:
6180 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06006181 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006182 break;
6183 case glslang::EOpSubgroupBallotInclusiveBitCount:
6184 case glslang::EOpSubgroupInclusiveAdd:
6185 case glslang::EOpSubgroupInclusiveMul:
6186 case glslang::EOpSubgroupInclusiveMin:
6187 case glslang::EOpSubgroupInclusiveMax:
6188 case glslang::EOpSubgroupInclusiveAnd:
6189 case glslang::EOpSubgroupInclusiveOr:
6190 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006191 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006192 break;
6193 case glslang::EOpSubgroupBallotExclusiveBitCount:
6194 case glslang::EOpSubgroupExclusiveAdd:
6195 case glslang::EOpSubgroupExclusiveMul:
6196 case glslang::EOpSubgroupExclusiveMin:
6197 case glslang::EOpSubgroupExclusiveMax:
6198 case glslang::EOpSubgroupExclusiveAnd:
6199 case glslang::EOpSubgroupExclusiveOr:
6200 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006201 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07006202 break;
6203 case glslang::EOpSubgroupClusteredAdd:
6204 case glslang::EOpSubgroupClusteredMul:
6205 case glslang::EOpSubgroupClusteredMin:
6206 case glslang::EOpSubgroupClusteredMax:
6207 case glslang::EOpSubgroupClusteredAnd:
6208 case glslang::EOpSubgroupClusteredOr:
6209 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06006210 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07006211 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006212#ifdef NV_EXTENSIONS
6213 case glslang::EOpSubgroupPartitionedAdd:
6214 case glslang::EOpSubgroupPartitionedMul:
6215 case glslang::EOpSubgroupPartitionedMin:
6216 case glslang::EOpSubgroupPartitionedMax:
6217 case glslang::EOpSubgroupPartitionedAnd:
6218 case glslang::EOpSubgroupPartitionedOr:
6219 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06006220 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006221 break;
6222 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6223 case glslang::EOpSubgroupPartitionedInclusiveMul:
6224 case glslang::EOpSubgroupPartitionedInclusiveMin:
6225 case glslang::EOpSubgroupPartitionedInclusiveMax:
6226 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6227 case glslang::EOpSubgroupPartitionedInclusiveOr:
6228 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006229 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006230 break;
6231 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6232 case glslang::EOpSubgroupPartitionedExclusiveMul:
6233 case glslang::EOpSubgroupPartitionedExclusiveMin:
6234 case glslang::EOpSubgroupPartitionedExclusiveMax:
6235 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6236 case glslang::EOpSubgroupPartitionedExclusiveOr:
6237 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06006238 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006239 break;
6240#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006241 }
6242
John Kessenich149afc32018-08-14 13:31:43 -06006243 // build the instruction
6244 std::vector<spv::IdImmediate> spvGroupOperands;
6245
6246 // Every operation begins with the Execution Scope operand.
6247 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6248 spvGroupOperands.push_back(executionScope);
6249
6250 // Next, for all operations that use a Group Operation, push that as an operand.
6251 if (groupOperation != spv::GroupOperationMax) {
John Kessenichd122a722018-09-18 03:43:30 -06006252 spv::IdImmediate groupOperand = { false, (unsigned)groupOperation };
John Kessenich149afc32018-08-14 13:31:43 -06006253 spvGroupOperands.push_back(groupOperand);
6254 }
6255
John Kessenich66011cb2018-03-06 16:12:04 -07006256 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006257 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6258 spv::IdImmediate operand = { true, *opIt };
6259 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006260 }
6261
6262 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006263 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006264 switch (op) {
6265 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006266 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6267 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6268 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6269 }
6270 if (directionId != spv::NoResult) {
6271 spv::IdImmediate direction = { true, directionId };
6272 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006273 }
6274
6275 return builder.createOp(opCode, typeId, spvGroupOperands);
6276}
6277
John Kessenich5e4b1242015-08-06 22:53:06 -06006278spv::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 -06006279{
John Kessenich66011cb2018-03-06 16:12:04 -07006280 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6281 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006282
John Kessenich140f3df2015-06-26 16:58:36 -06006283 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006284 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006285 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006286 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006287 spv::Id typeId0 = 0;
6288 if (consumedOperands > 0)
6289 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006290 spv::Id typeId1 = 0;
6291 if (consumedOperands > 1)
6292 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006293 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006294
6295 switch (op) {
6296 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006297 if (isFloat)
6298 libCall = spv::GLSLstd450FMin;
6299 else if (isUnsigned)
6300 libCall = spv::GLSLstd450UMin;
6301 else
6302 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006303 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006304 break;
6305 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006306 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006307 break;
6308 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006309 if (isFloat)
6310 libCall = spv::GLSLstd450FMax;
6311 else if (isUnsigned)
6312 libCall = spv::GLSLstd450UMax;
6313 else
6314 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006315 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006316 break;
6317 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006318 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006319 break;
6320 case glslang::EOpDot:
6321 opCode = spv::OpDot;
6322 break;
6323 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006324 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006325 break;
6326
6327 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006328 if (isFloat)
6329 libCall = spv::GLSLstd450FClamp;
6330 else if (isUnsigned)
6331 libCall = spv::GLSLstd450UClamp;
6332 else
6333 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006334 builder.promoteScalar(precision, operands.front(), operands[1]);
6335 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006336 break;
6337 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006338 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6339 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006340 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006341 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006342 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006343 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006344 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006345 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006346 break;
6347 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006348 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006349 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006350 break;
6351 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006352 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006353 builder.promoteScalar(precision, operands[0], operands[2]);
6354 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006355 break;
6356
6357 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006358 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006359 break;
6360 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006361 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006362 break;
6363 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006364 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006365 break;
6366 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006367 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006368 break;
6369 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006370 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006371 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006372 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006373#ifdef AMD_EXTENSIONS
6374 if (typeProxy == glslang::EbtFloat16)
6375 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6376#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006377 libCall = spv::GLSLstd450InterpolateAtSample;
6378 break;
6379 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006380#ifdef AMD_EXTENSIONS
6381 if (typeProxy == glslang::EbtFloat16)
6382 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6383#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006384 libCall = spv::GLSLstd450InterpolateAtOffset;
6385 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006386 case glslang::EOpAddCarry:
6387 opCode = spv::OpIAddCarry;
6388 typeId = builder.makeStructResultType(typeId0, typeId0);
6389 consumedOperands = 2;
6390 break;
6391 case glslang::EOpSubBorrow:
6392 opCode = spv::OpISubBorrow;
6393 typeId = builder.makeStructResultType(typeId0, typeId0);
6394 consumedOperands = 2;
6395 break;
6396 case glslang::EOpUMulExtended:
6397 opCode = spv::OpUMulExtended;
6398 typeId = builder.makeStructResultType(typeId0, typeId0);
6399 consumedOperands = 2;
6400 break;
6401 case glslang::EOpIMulExtended:
6402 opCode = spv::OpSMulExtended;
6403 typeId = builder.makeStructResultType(typeId0, typeId0);
6404 consumedOperands = 2;
6405 break;
6406 case glslang::EOpBitfieldExtract:
6407 if (isUnsigned)
6408 opCode = spv::OpBitFieldUExtract;
6409 else
6410 opCode = spv::OpBitFieldSExtract;
6411 break;
6412 case glslang::EOpBitfieldInsert:
6413 opCode = spv::OpBitFieldInsert;
6414 break;
6415
6416 case glslang::EOpFma:
6417 libCall = spv::GLSLstd450Fma;
6418 break;
6419 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006420 {
6421 libCall = spv::GLSLstd450FrexpStruct;
6422 assert(builder.isPointerType(typeId1));
6423 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006424 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006425#ifdef AMD_EXTENSIONS
6426 if (width == 16)
6427 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6428 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6429#endif
Rex Xu470026f2017-03-29 17:12:40 +08006430 if (builder.getNumComponents(operands[0]) == 1)
6431 frexpIntType = builder.makeIntegerType(width, true);
6432 else
6433 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6434 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6435 consumedOperands = 1;
6436 }
John Kessenich55e7d112015-11-15 21:33:39 -07006437 break;
6438 case glslang::EOpLdexp:
6439 libCall = spv::GLSLstd450Ldexp;
6440 break;
6441
Rex Xu574ab042016-04-14 16:53:07 +08006442 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006443 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006444
John Kessenich66011cb2018-03-06 16:12:04 -07006445 case glslang::EOpSubgroupBroadcast:
6446 case glslang::EOpSubgroupBallotBitExtract:
6447 case glslang::EOpSubgroupShuffle:
6448 case glslang::EOpSubgroupShuffleXor:
6449 case glslang::EOpSubgroupShuffleUp:
6450 case glslang::EOpSubgroupShuffleDown:
6451 case glslang::EOpSubgroupClusteredAdd:
6452 case glslang::EOpSubgroupClusteredMul:
6453 case glslang::EOpSubgroupClusteredMin:
6454 case glslang::EOpSubgroupClusteredMax:
6455 case glslang::EOpSubgroupClusteredAnd:
6456 case glslang::EOpSubgroupClusteredOr:
6457 case glslang::EOpSubgroupClusteredXor:
6458 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006459#ifdef NV_EXTENSIONS
6460 case glslang::EOpSubgroupPartitionedAdd:
6461 case glslang::EOpSubgroupPartitionedMul:
6462 case glslang::EOpSubgroupPartitionedMin:
6463 case glslang::EOpSubgroupPartitionedMax:
6464 case glslang::EOpSubgroupPartitionedAnd:
6465 case glslang::EOpSubgroupPartitionedOr:
6466 case glslang::EOpSubgroupPartitionedXor:
6467 case glslang::EOpSubgroupPartitionedInclusiveAdd:
6468 case glslang::EOpSubgroupPartitionedInclusiveMul:
6469 case glslang::EOpSubgroupPartitionedInclusiveMin:
6470 case glslang::EOpSubgroupPartitionedInclusiveMax:
6471 case glslang::EOpSubgroupPartitionedInclusiveAnd:
6472 case glslang::EOpSubgroupPartitionedInclusiveOr:
6473 case glslang::EOpSubgroupPartitionedInclusiveXor:
6474 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6475 case glslang::EOpSubgroupPartitionedExclusiveMul:
6476 case glslang::EOpSubgroupPartitionedExclusiveMin:
6477 case glslang::EOpSubgroupPartitionedExclusiveMax:
6478 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6479 case glslang::EOpSubgroupPartitionedExclusiveOr:
6480 case glslang::EOpSubgroupPartitionedExclusiveXor:
6481#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006482 return createSubgroupOperation(op, typeId, operands, typeProxy);
6483
Rex Xu9d93a232016-05-05 12:30:44 +08006484#ifdef AMD_EXTENSIONS
6485 case glslang::EOpSwizzleInvocations:
6486 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6487 libCall = spv::SwizzleInvocationsAMD;
6488 break;
6489 case glslang::EOpSwizzleInvocationsMasked:
6490 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6491 libCall = spv::SwizzleInvocationsMaskedAMD;
6492 break;
6493 case glslang::EOpWriteInvocation:
6494 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6495 libCall = spv::WriteInvocationAMD;
6496 break;
6497
6498 case glslang::EOpMin3:
6499 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6500 if (isFloat)
6501 libCall = spv::FMin3AMD;
6502 else {
6503 if (isUnsigned)
6504 libCall = spv::UMin3AMD;
6505 else
6506 libCall = spv::SMin3AMD;
6507 }
6508 break;
6509 case glslang::EOpMax3:
6510 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6511 if (isFloat)
6512 libCall = spv::FMax3AMD;
6513 else {
6514 if (isUnsigned)
6515 libCall = spv::UMax3AMD;
6516 else
6517 libCall = spv::SMax3AMD;
6518 }
6519 break;
6520 case glslang::EOpMid3:
6521 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6522 if (isFloat)
6523 libCall = spv::FMid3AMD;
6524 else {
6525 if (isUnsigned)
6526 libCall = spv::UMid3AMD;
6527 else
6528 libCall = spv::SMid3AMD;
6529 }
6530 break;
6531
6532 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006533 if (typeProxy == glslang::EbtFloat16)
6534 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08006535 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6536 libCall = spv::InterpolateAtVertexAMD;
6537 break;
6538#endif
Jeff Bolz36831c92018-09-05 10:11:41 -05006539 case glslang::EOpBarrier:
6540 {
6541 // This is for the extended controlBarrier function, with four operands.
6542 // The unextended barrier() goes through createNoArgOperation.
6543 assert(operands.size() == 4);
6544 unsigned int executionScope = builder.getConstantScalar(operands[0]);
6545 unsigned int memoryScope = builder.getConstantScalar(operands[1]);
6546 unsigned int semantics = builder.getConstantScalar(operands[2]) | builder.getConstantScalar(operands[3]);
6547 builder.createControlBarrier((spv::Scope)executionScope, (spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6548 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6549 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6550 }
6551 if (glslangIntermediate->usingVulkanMemoryModel() && (executionScope == spv::ScopeDevice || memoryScope == spv::ScopeDevice)) {
6552 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6553 }
6554 return 0;
6555 }
6556 break;
6557 case glslang::EOpMemoryBarrier:
6558 {
6559 // This is for the extended memoryBarrier function, with three operands.
6560 // The unextended memoryBarrier() goes through createNoArgOperation.
6561 assert(operands.size() == 3);
6562 unsigned int memoryScope = builder.getConstantScalar(operands[0]);
6563 unsigned int semantics = builder.getConstantScalar(operands[1]) | builder.getConstantScalar(operands[2]);
6564 builder.createMemoryBarrier((spv::Scope)memoryScope, (spv::MemorySemanticsMask)semantics);
6565 if (semantics & (spv::MemorySemanticsMakeAvailableKHRMask | spv::MemorySemanticsMakeVisibleKHRMask | spv::MemorySemanticsOutputMemoryKHRMask)) {
6566 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6567 }
6568 if (glslangIntermediate->usingVulkanMemoryModel() && memoryScope == spv::ScopeDevice) {
6569 builder.addCapability(spv::CapabilityVulkanMemoryModelDeviceScopeKHR);
6570 }
6571 return 0;
6572 }
6573 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006574 default:
6575 return 0;
6576 }
6577
6578 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006579 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006580 // Use an extended instruction from the standard library.
6581 // Construct the call arguments, without modifying the original operands vector.
6582 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6583 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006584 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006585 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006586 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006587 case 0:
6588 // should all be handled by visitAggregate and createNoArgOperation
6589 assert(0);
6590 return 0;
6591 case 1:
6592 // should all be handled by createUnaryOperation
6593 assert(0);
6594 return 0;
6595 case 2:
6596 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6597 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006598 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006599 // anything 3 or over doesn't have l-value operands, so all should be consumed
6600 assert(consumedOperands == operands.size());
6601 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006602 break;
6603 }
6604 }
6605
John Kessenich55e7d112015-11-15 21:33:39 -07006606 // Decode the return types that were structures
6607 switch (op) {
6608 case glslang::EOpAddCarry:
6609 case glslang::EOpSubBorrow:
6610 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6611 id = builder.createCompositeExtract(id, typeId0, 0);
6612 break;
6613 case glslang::EOpUMulExtended:
6614 case glslang::EOpIMulExtended:
6615 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6616 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6617 break;
6618 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006619 {
6620 assert(operands.size() == 2);
6621 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6622 // "exp" is floating-point type (from HLSL intrinsic)
6623 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6624 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6625 builder.createStore(member1, operands[1]);
6626 } else
6627 // "exp" is integer type (from GLSL built-in function)
6628 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6629 id = builder.createCompositeExtract(id, typeId0, 0);
6630 }
John Kessenich55e7d112015-11-15 21:33:39 -07006631 break;
6632 default:
6633 break;
6634 }
6635
John Kessenich32cfd492016-02-02 12:37:46 -07006636 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006637}
6638
Rex Xu9d93a232016-05-05 12:30:44 +08006639// Intrinsics with no arguments (or no return value, and no precision).
6640spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006641{
Jeff Bolz36831c92018-09-05 10:11:41 -05006642 // GLSL memory barriers use queuefamily scope in new model, device scope in old model
6643 spv::Scope memoryBarrierScope = glslangIntermediate->usingVulkanMemoryModel() ? spv::ScopeQueueFamilyKHR : spv::ScopeDevice;
John Kessenich140f3df2015-06-26 16:58:36 -06006644
6645 switch (op) {
6646 case glslang::EOpEmitVertex:
6647 builder.createNoResultOp(spv::OpEmitVertex);
6648 return 0;
6649 case glslang::EOpEndPrimitive:
6650 builder.createNoResultOp(spv::OpEndPrimitive);
6651 return 0;
6652 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006653 if (glslangIntermediate->getStage() == EShLangTessControl) {
Jeff Bolz36831c92018-09-05 10:11:41 -05006654 if (glslangIntermediate->usingVulkanMemoryModel()) {
6655 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6656 spv::MemorySemanticsOutputMemoryKHRMask |
6657 spv::MemorySemanticsAcquireReleaseMask);
6658 builder.addCapability(spv::CapabilityVulkanMemoryModelKHR);
6659 } else {
6660 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6661 }
John Kessenich82979362017-12-11 04:02:24 -07006662 } else {
6663 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6664 spv::MemorySemanticsWorkgroupMemoryMask |
6665 spv::MemorySemanticsAcquireReleaseMask);
6666 }
John Kessenich140f3df2015-06-26 16:58:36 -06006667 return 0;
6668 case glslang::EOpMemoryBarrier:
Jeff Bolz36831c92018-09-05 10:11:41 -05006669 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAllMemory |
6670 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006671 return 0;
6672 case glslang::EOpMemoryBarrierAtomicCounter:
Jeff Bolz36831c92018-09-05 10:11:41 -05006673 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsAtomicCounterMemoryMask |
6674 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006675 return 0;
6676 case glslang::EOpMemoryBarrierBuffer:
Jeff Bolz36831c92018-09-05 10:11:41 -05006677 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsUniformMemoryMask |
6678 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006679 return 0;
6680 case glslang::EOpMemoryBarrierImage:
Jeff Bolz36831c92018-09-05 10:11:41 -05006681 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsImageMemoryMask |
6682 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006683 return 0;
6684 case glslang::EOpMemoryBarrierShared:
Jeff Bolz36831c92018-09-05 10:11:41 -05006685 builder.createMemoryBarrier(memoryBarrierScope, spv::MemorySemanticsWorkgroupMemoryMask |
6686 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006687 return 0;
6688 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006689 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
6690 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006691 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06006692 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006693 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07006694 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07006695 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006696 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07006697 case glslang::EOpDeviceMemoryBarrier:
6698 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6699 spv::MemorySemanticsImageMemoryMask |
6700 spv::MemorySemanticsAcquireReleaseMask);
6701 return 0;
6702 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
6703 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6704 spv::MemorySemanticsImageMemoryMask |
6705 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006706 return 0;
6707 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07006708 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6709 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006710 return 0;
6711 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006712 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6713 spv::MemorySemanticsWorkgroupMemoryMask |
6714 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006715 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07006716 case glslang::EOpSubgroupBarrier:
6717 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6718 spv::MemorySemanticsAcquireReleaseMask);
6719 return spv::NoResult;
6720 case glslang::EOpSubgroupMemoryBarrier:
6721 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6722 spv::MemorySemanticsAcquireReleaseMask);
6723 return spv::NoResult;
6724 case glslang::EOpSubgroupMemoryBarrierBuffer:
6725 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
6726 spv::MemorySemanticsAcquireReleaseMask);
6727 return spv::NoResult;
6728 case glslang::EOpSubgroupMemoryBarrierImage:
6729 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
6730 spv::MemorySemanticsAcquireReleaseMask);
6731 return spv::NoResult;
6732 case glslang::EOpSubgroupMemoryBarrierShared:
6733 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6734 spv::MemorySemanticsAcquireReleaseMask);
6735 return spv::NoResult;
6736 case glslang::EOpSubgroupElect: {
6737 std::vector<spv::Id> operands;
6738 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
6739 }
Rex Xu9d93a232016-05-05 12:30:44 +08006740#ifdef AMD_EXTENSIONS
6741 case glslang::EOpTime:
6742 {
6743 std::vector<spv::Id> args; // Dummy arguments
6744 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
6745 return builder.setPrecision(id, precision);
6746 }
6747#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006748 default:
Lei Zhang17535f72016-05-04 15:55:59 -04006749 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06006750 return 0;
6751 }
6752}
6753
6754spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
6755{
John Kessenich2f273362015-07-18 22:34:27 -06006756 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06006757 spv::Id id;
6758 if (symbolValues.end() != iter) {
6759 id = iter->second;
6760 return id;
6761 }
6762
6763 // it was not found, create it
6764 id = createSpvVariable(symbol);
6765 symbolValues[symbol->getId()] = id;
6766
Rex Xuc884b4a2016-06-29 15:03:44 +08006767 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006768 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
6769 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
6770 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07006771 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07006772 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06006773 if (symbol->getQualifier().hasIndex())
6774 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
6775 if (symbol->getQualifier().hasComponent())
6776 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06006777 // atomic counters use this:
6778 if (symbol->getQualifier().hasOffset())
6779 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006780 }
6781
scygan2c864272016-05-18 18:09:17 +02006782 if (symbol->getQualifier().hasLocation())
6783 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07006784 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07006785 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07006786 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06006787 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07006788 }
John Kessenich140f3df2015-06-26 16:58:36 -06006789 if (symbol->getQualifier().hasSet())
6790 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07006791 else if (IsDescriptorResource(symbol->getType())) {
6792 // default to 0
6793 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
6794 }
John Kessenich140f3df2015-06-26 16:58:36 -06006795 if (symbol->getQualifier().hasBinding())
6796 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07006797 if (symbol->getQualifier().hasAttachment())
6798 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06006799 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07006800 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06006801 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06006802 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07006803 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06006804 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07006805 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
6806 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
6807 builder.addDecoration(id, spv::DecorationXfbStride, stride);
6808 }
6809 if (symbol->getQualifier().hasXfbOffset())
6810 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006811 }
6812
Rex Xu1da878f2016-02-21 20:59:01 +08006813 if (symbol->getType().isImage()) {
6814 std::vector<spv::Decoration> memory;
Jeff Bolz36831c92018-09-05 10:11:41 -05006815 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory, glslangIntermediate->usingVulkanMemoryModel());
Rex Xu1da878f2016-02-21 20:59:01 +08006816 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07006817 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08006818 }
6819
John Kessenich140f3df2015-06-26 16:58:36 -06006820 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06006821 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06006822 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07006823 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06006824
John Kessenich5611c6d2018-04-05 11:25:02 -06006825 // nonuniform
6826 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
6827
John Kessenichecba76f2017-01-06 00:34:48 -07006828#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08006829 if (builtIn == spv::BuiltInSampleMask) {
6830 spv::Decoration decoration;
6831 // GL_NV_sample_mask_override_coverage extension
6832 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08006833 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08006834 else
6835 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07006836 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08006837 if (decoration != spv::DecorationMax) {
6838 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
6839 }
6840 }
chaoc771d89f2017-01-13 01:10:53 -08006841 else if (builtIn == spv::BuiltInLayer) {
6842 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06006843 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006844 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08006845 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
6846 builder.addExtension(spv::E_SPV_NV_viewport_array2);
6847 }
John Kessenichb41bff62017-08-11 13:07:17 -06006848 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006849 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
6850 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08006851 builder.addCapability(spv::CapabilityShaderStereoViewNV);
6852 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
6853 }
6854 }
6855
chaoc6e5acae2016-12-20 13:28:52 -08006856 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006857 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08006858 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08006859 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
6860 }
chaoc0ad6a4e2016-12-19 16:29:34 -08006861#endif
6862
John Kessenich5d610ee2018-03-07 18:05:55 -07006863 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
6864 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
6865 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
6866 symbol->getType().getQualifier().semanticName);
6867 }
6868
John Kessenich140f3df2015-06-26 16:58:36 -06006869 return id;
6870}
6871
John Kessenich55e7d112015-11-15 21:33:39 -07006872// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07006873// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07006874//
6875// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
6876//
6877// Recursively walk the nodes. The nodes form a tree whose leaves are
6878// regular constants, which themselves are trees that createSpvConstant()
6879// recursively walks. So, this function walks the "top" of the tree:
6880// - emit specialization constant-building instructions for specConstant
6881// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04006882spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07006883{
John Kessenich7cc0e282016-03-20 00:46:02 -06006884 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07006885
qining4f4bb812016-04-03 23:55:17 -04006886 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07006887 if (! node.getQualifier().specConstant) {
6888 // hand off to the non-spec-constant path
6889 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
6890 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04006891 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07006892 nextConst, false);
6893 }
6894
6895 // We now know we have a specialization constant to build
6896
John Kessenichd94c0032016-05-30 19:29:40 -06006897 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04006898 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
6899 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
6900 std::vector<spv::Id> dimConstId;
6901 for (int dim = 0; dim < 3; ++dim) {
6902 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
6903 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07006904 if (specConst) {
6905 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
6906 glslangIntermediate->getLocalSizeSpecId(dim));
6907 }
qining4f4bb812016-04-03 23:55:17 -04006908 }
6909 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
6910 }
6911
6912 // An AST node labelled as specialization constant should be a symbol node.
6913 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
6914 if (auto* sn = node.getAsSymbolNode()) {
6915 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04006916 // Traverse the constant constructor sub tree like generating normal run-time instructions.
6917 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
6918 // will set the builder into spec constant op instruction generating mode.
6919 sub_tree->traverse(this);
6920 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04006921 } else if (auto* const_union_array = &sn->getConstArray()){
6922 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01006923 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
6924 builder.addName(id, sn->getName().c_str());
6925 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07006926 }
6927 }
qining4f4bb812016-04-03 23:55:17 -04006928
6929 // Neither a front-end constant node, nor a specialization constant node with constant union array or
6930 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04006931 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04006932 exit(1);
6933 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07006934}
6935
John Kessenich140f3df2015-06-26 16:58:36 -06006936// Use 'consts' as the flattened glslang source of scalar constants to recursively
6937// build the aggregate SPIR-V constant.
6938//
6939// If there are not enough elements present in 'consts', 0 will be substituted;
6940// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
6941//
qining08408382016-03-21 09:51:37 -04006942spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06006943{
6944 // vector of constants for SPIR-V
6945 std::vector<spv::Id> spvConsts;
6946
6947 // Type is used for struct and array constants
6948 spv::Id typeId = convertGlslangToSpvType(glslangType);
6949
6950 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006951 glslang::TType elementType(glslangType, 0);
6952 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04006953 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006954 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006955 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06006956 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04006957 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006958 } else if (glslangType.getStruct()) {
6959 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
6960 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04006961 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06006962 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06006963 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
6964 bool zero = nextConst >= consts.size();
6965 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006966 case glslang::EbtInt8:
6967 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
6968 break;
6969 case glslang::EbtUint8:
6970 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
6971 break;
6972 case glslang::EbtInt16:
6973 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
6974 break;
6975 case glslang::EbtUint16:
6976 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
6977 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006978 case glslang::EbtInt:
6979 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
6980 break;
6981 case glslang::EbtUint:
6982 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
6983 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006984 case glslang::EbtInt64:
6985 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
6986 break;
6987 case glslang::EbtUint64:
6988 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
6989 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006990 case glslang::EbtFloat:
6991 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6992 break;
6993 case glslang::EbtDouble:
6994 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
6995 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006996 case glslang::EbtFloat16:
6997 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6998 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006999 case glslang::EbtBool:
7000 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
7001 break;
7002 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007003 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007004 break;
7005 }
7006 ++nextConst;
7007 }
7008 } else {
7009 // we have a non-aggregate (scalar) constant
7010 bool zero = nextConst >= consts.size();
7011 spv::Id scalar = 0;
7012 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07007013 case glslang::EbtInt8:
7014 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
7015 break;
7016 case glslang::EbtUint8:
7017 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
7018 break;
7019 case glslang::EbtInt16:
7020 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
7021 break;
7022 case glslang::EbtUint16:
7023 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
7024 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007025 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07007026 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007027 break;
7028 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07007029 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007030 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08007031 case glslang::EbtInt64:
7032 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
7033 break;
7034 case glslang::EbtUint64:
7035 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
7036 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007037 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07007038 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007039 break;
7040 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07007041 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007042 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08007043 case glslang::EbtFloat16:
7044 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
7045 break;
John Kessenich140f3df2015-06-26 16:58:36 -06007046 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07007047 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06007048 break;
7049 default:
John Kessenich55e7d112015-11-15 21:33:39 -07007050 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06007051 break;
7052 }
7053 ++nextConst;
7054 return scalar;
7055 }
7056
7057 return builder.makeCompositeConstant(typeId, spvConsts);
7058}
7059
John Kessenich7c1aa102015-10-15 13:29:11 -06007060// Return true if the node is a constant or symbol whose reading has no
7061// non-trivial observable cost or effect.
7062bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
7063{
7064 // don't know what this is
7065 if (node == nullptr)
7066 return false;
7067
7068 // a constant is safe
7069 if (node->getAsConstantUnion() != nullptr)
7070 return true;
7071
7072 // not a symbol means non-trivial
7073 if (node->getAsSymbolNode() == nullptr)
7074 return false;
7075
7076 // a symbol, depends on what's being read
7077 switch (node->getType().getQualifier().storage) {
7078 case glslang::EvqTemporary:
7079 case glslang::EvqGlobal:
7080 case glslang::EvqIn:
7081 case glslang::EvqInOut:
7082 case glslang::EvqConst:
7083 case glslang::EvqConstReadOnly:
7084 case glslang::EvqUniform:
7085 return true;
7086 default:
7087 return false;
7088 }
qining25262b32016-05-06 17:25:16 -04007089}
John Kessenich7c1aa102015-10-15 13:29:11 -06007090
7091// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06007092// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06007093// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06007094// Return true if trivial.
7095bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
7096{
7097 if (node == nullptr)
7098 return false;
7099
John Kessenich84cc15f2017-05-24 16:44:47 -06007100 // count non scalars as trivial, as well as anything coming from HLSL
7101 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06007102 return true;
7103
John Kessenich7c1aa102015-10-15 13:29:11 -06007104 // symbols and constants are trivial
7105 if (isTrivialLeaf(node))
7106 return true;
7107
7108 // otherwise, it needs to be a simple operation or one or two leaf nodes
7109
7110 // not a simple operation
7111 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
7112 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
7113 if (binaryNode == nullptr && unaryNode == nullptr)
7114 return false;
7115
7116 // not on leaf nodes
7117 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
7118 return false;
7119
7120 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
7121 return false;
7122 }
7123
7124 switch (node->getAsOperator()->getOp()) {
7125 case glslang::EOpLogicalNot:
7126 case glslang::EOpConvIntToBool:
7127 case glslang::EOpConvUintToBool:
7128 case glslang::EOpConvFloatToBool:
7129 case glslang::EOpConvDoubleToBool:
7130 case glslang::EOpEqual:
7131 case glslang::EOpNotEqual:
7132 case glslang::EOpLessThan:
7133 case glslang::EOpGreaterThan:
7134 case glslang::EOpLessThanEqual:
7135 case glslang::EOpGreaterThanEqual:
7136 case glslang::EOpIndexDirect:
7137 case glslang::EOpIndexDirectStruct:
7138 case glslang::EOpLogicalXor:
7139 case glslang::EOpAny:
7140 case glslang::EOpAll:
7141 return true;
7142 default:
7143 return false;
7144 }
7145}
7146
7147// Emit short-circuiting code, where 'right' is never evaluated unless
7148// the left side is true (for &&) or false (for ||).
7149spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
7150{
7151 spv::Id boolTypeId = builder.makeBoolType();
7152
7153 // emit left operand
7154 builder.clearAccessChain();
7155 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007156 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007157
7158 // Operands to accumulate OpPhi operands
7159 std::vector<spv::Id> phiOperands;
7160 // accumulate left operand's phi information
7161 phiOperands.push_back(leftId);
7162 phiOperands.push_back(builder.getBuildPoint()->getId());
7163
7164 // Make the two kinds of operation symmetric with a "!"
7165 // || => emit "if (! left) result = right"
7166 // && => emit "if ( left) result = right"
7167 //
7168 // TODO: this runtime "not" for || could be avoided by adding functionality
7169 // to 'builder' to have an "else" without an "then"
7170 if (op == glslang::EOpLogicalOr)
7171 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
7172
7173 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08007174 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06007175
7176 // emit right operand as the "then" part of the "if"
7177 builder.clearAccessChain();
7178 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08007179 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06007180
7181 // accumulate left operand's phi information
7182 phiOperands.push_back(rightId);
7183 phiOperands.push_back(builder.getBuildPoint()->getId());
7184
7185 // finish the "if"
7186 ifBuilder.makeEndIf();
7187
7188 // phi together the two results
7189 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
7190}
7191
Frank Henigman541f7bb2018-01-16 00:18:26 -05007192#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08007193// Return type Id of the imported set of extended instructions corresponds to the name.
7194// Import this set if it has not been imported yet.
7195spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
7196{
7197 if (extBuiltinMap.find(name) != extBuiltinMap.end())
7198 return extBuiltinMap[name];
7199 else {
Rex Xu51596642016-09-21 18:56:12 +08007200 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08007201 spv::Id extBuiltins = builder.import(name);
7202 extBuiltinMap[name] = extBuiltins;
7203 return extBuiltins;
7204 }
7205}
Frank Henigman541f7bb2018-01-16 00:18:26 -05007206#endif
Rex Xu9d93a232016-05-05 12:30:44 +08007207
John Kessenich140f3df2015-06-26 16:58:36 -06007208}; // end anonymous namespace
7209
7210namespace glslang {
7211
John Kessenich68d78fd2015-07-12 19:28:10 -06007212void GetSpirvVersion(std::string& version)
7213{
John Kessenich9e55f632015-07-15 10:03:39 -06007214 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06007215 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07007216 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06007217 version = buf;
7218}
7219
John Kessenicha372a3e2017-11-02 22:32:14 -06007220// For low-order part of the generator's magic number. Bump up
7221// when there is a change in the style (e.g., if SSA form changes,
7222// or a different instruction sequence to do something gets used).
7223int GetSpirvGeneratorVersion()
7224{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07007225 // return 1; // start
7226 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07007227 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07007228 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07007229 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06007230 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
7231 // versions 4 and 6 each generate OpArrayLength as it has long been done
7232 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06007233}
7234
John Kessenich140f3df2015-06-26 16:58:36 -06007235// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007236void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06007237{
7238 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06007239 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007240 if (out.fail())
7241 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06007242 for (int i = 0; i < (int)spirv.size(); ++i) {
7243 unsigned int word = spirv[i];
7244 out.write((const char*)&word, 4);
7245 }
7246 out.close();
7247}
7248
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007249// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08007250void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007251{
7252 std::ofstream out;
7253 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07007254 if (out.fail())
7255 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07007256 out << "\t// " <<
John Kessenich4e11b612018-08-30 16:56:59 -06007257 GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
John Kessenichc6c80a62018-03-05 22:23:17 -07007258 std::endl;
Flavio15017db2017-02-15 14:29:33 -08007259 if (varName != nullptr) {
7260 out << "\t #pragma once" << std::endl;
7261 out << "const uint32_t " << varName << "[] = {" << std::endl;
7262 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007263 const int WORDS_PER_LINE = 8;
7264 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
7265 out << "\t";
7266 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
7267 const unsigned int word = spirv[i + j];
7268 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
7269 if (i + j + 1 < (int)spirv.size()) {
7270 out << ",";
7271 }
7272 }
7273 out << std::endl;
7274 }
Flavio15017db2017-02-15 14:29:33 -08007275 if (varName != nullptr) {
7276 out << "};";
7277 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05007278 out.close();
7279}
7280
John Kessenich140f3df2015-06-26 16:58:36 -06007281//
7282// Set up the glslang traversal
7283//
John Kessenich4e11b612018-08-30 16:56:59 -06007284void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007285{
Lei Zhang17535f72016-05-04 15:55:59 -04007286 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007287 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007288}
7289
John Kessenich4e11b612018-08-30 16:56:59 -06007290void GlslangToSpv(const TIntermediate& intermediate, std::vector<unsigned int>& spirv,
John Kessenich121853f2017-05-31 17:11:16 -06007291 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007292{
John Kessenich140f3df2015-06-26 16:58:36 -06007293 TIntermNode* root = intermediate.getTreeRoot();
7294
7295 if (root == 0)
7296 return;
7297
John Kessenich4e11b612018-08-30 16:56:59 -06007298 SpvOptions defaultOptions;
John Kessenich121853f2017-05-31 17:11:16 -06007299 if (options == nullptr)
7300 options = &defaultOptions;
7301
John Kessenich4e11b612018-08-30 16:56:59 -06007302 GetThreadPoolAllocator().push();
John Kessenich140f3df2015-06-26 16:58:36 -06007303
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007304 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007305 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007306 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007307 it.dumpSpv(spirv);
7308
GregFfb03a552018-03-29 11:49:14 -06007309#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007310 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7311 // eg. forward and remove memory writes of opaque types.
John Kessenich717c80a2018-08-23 15:17:10 -06007312 if ((intermediate.getSource() == EShSourceHlsl || options->optimizeSize) && !options->disableOptimizer)
John Kesseniche7df8e02018-08-22 17:12:46 -06007313 SpirvToolsLegalize(intermediate, spirv, logger, options);
John Kessenich717c80a2018-08-23 15:17:10 -06007314
John Kessenich4e11b612018-08-30 16:56:59 -06007315 if (options->validate)
7316 SpirvToolsValidate(intermediate, spirv, logger);
7317
John Kessenich717c80a2018-08-23 15:17:10 -06007318 if (options->disassemble)
John Kessenich4e11b612018-08-30 16:56:59 -06007319 SpirvToolsDisassemble(std::cout, spirv);
John Kessenich717c80a2018-08-23 15:17:10 -06007320
GregFcd1f1692017-09-21 18:40:22 -06007321#endif
7322
John Kessenich4e11b612018-08-30 16:56:59 -06007323 GetThreadPoolAllocator().pop();
John Kessenich140f3df2015-06-26 16:58:36 -06007324}
7325
7326}; // end namespace glslang