blob: 315546db0650e1aaf92b72aee988370a11fd4ebb [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
GregFfb03a552018-03-29 11:49:14 -060057#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -060058 #include "spirv-tools/optimizer.hpp"
59 #include "message.h"
GregFcd1f1692017-09-21 18:40:22 -060060#endif
61
GregFfb03a552018-03-29 11:49:14 -060062#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -060063using namespace spvtools;
64#endif
65
John Kessenich140f3df2015-06-26 16:58:36 -060066// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020067#include "../glslang/MachineIndependent/localintermediate.h"
68#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060069#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050070#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060071
John Kessenich140f3df2015-06-26 16:58:36 -060072#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050073#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040074#include <list>
75#include <map>
76#include <stack>
77#include <string>
78#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060079
80namespace {
81
qining4c912612016-04-01 10:35:16 -040082namespace {
83class SpecConstantOpModeGuard {
84public:
85 SpecConstantOpModeGuard(spv::Builder* builder)
86 : builder_(builder) {
87 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040088 }
89 ~SpecConstantOpModeGuard() {
90 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
91 : builder_->setToNormalCodeGenMode();
92 }
qining40887662016-04-03 22:20:42 -040093 void turnOnSpecConstantOpMode() {
94 builder_->setToSpecConstCodeGenMode();
95 }
qining4c912612016-04-01 10:35:16 -040096
97private:
98 spv::Builder* builder_;
99 bool previous_flag_;
100};
John Kessenichead86222018-03-28 18:01:20 -0600101
102struct OpDecorations {
103 spv::Decoration precision;
104 spv::Decoration noContraction;
John Kessenich5611c6d2018-04-05 11:25:02 -0600105 spv::Decoration nonUniform;
John Kessenichead86222018-03-28 18:01:20 -0600106};
107
108} // namespace
qining4c912612016-04-01 10:35:16 -0400109
John Kessenich140f3df2015-06-26 16:58:36 -0600110//
111// The main holder of information for translating glslang to SPIR-V.
112//
113// Derives from the AST walking base class.
114//
115class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
116public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700117 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
118 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700119 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600120
121 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
122 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
123 void visitConstantUnion(glslang::TIntermConstantUnion*);
124 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
125 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
126 void visitSymbol(glslang::TIntermSymbol* symbol);
127 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
128 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
129 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
130
John Kessenichfca82622016-11-26 13:23:20 -0700131 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700132 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600133
134protected:
John Kessenich5d610ee2018-03-07 18:05:55 -0700135 TGlslangToSpvTraverser(TGlslangToSpvTraverser&);
136 TGlslangToSpvTraverser& operator=(TGlslangToSpvTraverser&);
137
Rex Xu17ff3432016-10-14 17:41:45 +0800138 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800139 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
John Kessenich5611c6d2018-04-05 11:25:02 -0600140 spv::Decoration TranslateNonUniformDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100141 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700142 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700143 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
144 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenicha2858d92018-01-31 08:11:18 -0700145 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, unsigned int& dependencyLength) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600146 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich5611c6d2018-04-05 11:25:02 -0600147 void addIndirectionIndexCapabilities(const glslang::TType& baseType, const glslang::TType& indexType);
John Kessenich140f3df2015-06-26 16:58:36 -0600148 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
149 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600150 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
151 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
152 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600153 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenichead86222018-03-28 18:01:20 -0600154 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&,
155 bool lastBufferBlockMember);
John Kessenich0e737842017-03-24 18:38:16 -0600156 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600157 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
158 glslang::TLayoutPacking, const glslang::TQualifier&);
159 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
160 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700161 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700162 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800163 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600164 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700165 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700166 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
167 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich5d610ee2018-03-07 18:05:55 -0700168 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset,
169 int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100170 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600171
John Kessenich6fccb3c2016-09-19 16:01:41 -0600172 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd3ed90b2018-05-04 11:43:03 -0600173 bool writableParam(glslang::TStorageQualifier) const;
John Kessenichd41993d2017-09-10 15:21:05 -0600174 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600175 void makeFunctions(const glslang::TIntermSequence&);
176 void makeGlobalInitializers(const glslang::TIntermSequence&);
177 void visitFunctions(const glslang::TIntermSequence&);
178 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800179 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600180 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
181 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600182 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
183
John Kessenichead86222018-03-28 18:01:20 -0600184 spv::Id createBinaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right,
185 glslang::TBasicType typeProxy, bool reduceComparison = true);
186 spv::Id createBinaryMatrixOperation(spv::Op, OpDecorations&, spv::Id typeId, spv::Id left, spv::Id right);
187 spv::Id createUnaryOperation(glslang::TOperator op, OpDecorations&, spv::Id typeId, spv::Id operand,
188 glslang::TBasicType typeProxy);
189 spv::Id createUnaryMatrixOperation(spv::Op op, OpDecorations&, spv::Id typeId, spv::Id operand,
190 glslang::TBasicType typeProxy);
191 spv::Id createConversion(glslang::TOperator op, OpDecorations&, spv::Id destTypeId, spv::Id operand,
192 glslang::TBasicType typeProxy);
John Kessenichad7645f2018-06-04 19:11:25 -0600193 spv::Id createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize);
John Kessenich140f3df2015-06-26 16:58:36 -0600194 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800195 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 +0800196 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800197 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich66011cb2018-03-06 16:12:04 -0700198 spv::Id createSubgroupOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600199 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 +0800200 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600201 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
qining08408382016-03-21 09:51:37 -0400202 spv::Id createSpvConstant(const glslang::TIntermTyped&);
203 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600204 bool isTrivialLeaf(const glslang::TIntermTyped* node);
205 bool isTrivial(const glslang::TIntermTyped* node);
206 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500207#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800208 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500209#endif
John Kessenich66011cb2018-03-06 16:12:04 -0700210 void addPre13Extension(const char* ext)
211 {
212 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
213 builder.addExtension(ext);
214 }
John Kessenich140f3df2015-06-26 16:58:36 -0600215
John Kessenich121853f2017-05-31 17:11:16 -0600216 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600217 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600218 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700219 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600220 int sequenceDepth;
221
Lei Zhang17535f72016-05-04 15:55:59 -0400222 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400223
John Kessenich140f3df2015-06-26 16:58:36 -0600224 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
225 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700226 bool inEntryPoint;
227 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700228 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 -0700229 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600230 const glslang::TIntermediate* glslangIntermediate;
231 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800232 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600233
John Kessenich2f273362015-07-18 22:34:27 -0600234 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600235 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600236 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700237 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich5d610ee2018-03-07 18:05:55 -0700238 // for mapping glslang block indices to spv indices (e.g., due to hidden members):
239 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper;
John Kessenich140f3df2015-06-26 16:58:36 -0600240 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich5d610ee2018-03-07 18:05:55 -0700241 std::unordered_map<std::string, const glslang::TIntermSymbol*> counterOriginator;
John Kessenich140f3df2015-06-26 16:58:36 -0600242};
243
244//
245// Helper functions for translating glslang representations to SPIR-V enumerants.
246//
247
248// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700249spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600250{
John Kessenich66e2faf2016-03-12 18:34:36 -0700251 switch (source) {
252 case glslang::EShSourceGlsl:
253 switch (profile) {
254 case ENoProfile:
255 case ECoreProfile:
256 case ECompatibilityProfile:
257 return spv::SourceLanguageGLSL;
258 case EEsProfile:
259 return spv::SourceLanguageESSL;
260 default:
261 return spv::SourceLanguageUnknown;
262 }
263 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600264 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600265 default:
266 return spv::SourceLanguageUnknown;
267 }
268}
269
270// Translate glslang language (stage) to SPIR-V execution model.
271spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
272{
273 switch (stage) {
274 case EShLangVertex: return spv::ExecutionModelVertex;
275 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
276 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
277 case EShLangGeometry: return spv::ExecutionModelGeometry;
278 case EShLangFragment: return spv::ExecutionModelFragment;
279 case EShLangCompute: return spv::ExecutionModelGLCompute;
280 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700281 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600282 return spv::ExecutionModelFragment;
283 }
284}
285
John Kessenich140f3df2015-06-26 16:58:36 -0600286// Translate glslang sampler type to SPIR-V dimensionality.
287spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
288{
289 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700290 case glslang::Esd1D: return spv::Dim1D;
291 case glslang::Esd2D: return spv::Dim2D;
292 case glslang::Esd3D: return spv::Dim3D;
293 case glslang::EsdCube: return spv::DimCube;
294 case glslang::EsdRect: return spv::DimRect;
295 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700296 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600297 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700298 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600299 return spv::Dim2D;
300 }
301}
302
John Kessenichf6640762016-08-01 19:44:00 -0600303// Translate glslang precision to SPIR-V precision decorations.
304spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600305{
John Kessenichf6640762016-08-01 19:44:00 -0600306 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700307 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600308 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600309 default:
310 return spv::NoPrecision;
311 }
312}
313
John Kessenichf6640762016-08-01 19:44:00 -0600314// Translate glslang type to SPIR-V precision decorations.
315spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
316{
317 return TranslatePrecisionDecoration(type.getQualifier().precision);
318}
319
John Kessenich140f3df2015-06-26 16:58:36 -0600320// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600321spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600322{
323 if (type.getBasicType() == glslang::EbtBlock) {
324 switch (type.getQualifier().storage) {
325 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600326 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600327 case glslang::EvqVaryingIn: return spv::DecorationBlock;
328 case glslang::EvqVaryingOut: return spv::DecorationBlock;
329 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700330 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600331 break;
332 }
333 }
334
John Kessenich4016e382016-07-15 11:53:56 -0600335 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600336}
337
Rex Xu1da878f2016-02-21 20:59:01 +0800338// Translate glslang type to SPIR-V memory decorations.
339void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
340{
341 if (qualifier.coherent)
342 memory.push_back(spv::DecorationCoherent);
John Kessenich14b85d32018-06-04 15:36:03 -0600343 if (qualifier.volatil) {
Rex Xu1da878f2016-02-21 20:59:01 +0800344 memory.push_back(spv::DecorationVolatile);
John Kessenich14b85d32018-06-04 15:36:03 -0600345 memory.push_back(spv::DecorationCoherent);
346 }
Rex Xu1da878f2016-02-21 20:59:01 +0800347 if (qualifier.restrict)
348 memory.push_back(spv::DecorationRestrict);
349 if (qualifier.readonly)
350 memory.push_back(spv::DecorationNonWritable);
351 if (qualifier.writeonly)
352 memory.push_back(spv::DecorationNonReadable);
353}
354
John Kessenich140f3df2015-06-26 16:58:36 -0600355// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700356spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600357{
358 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700359 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600360 case glslang::ElmRowMajor:
361 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700362 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600363 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700364 default:
365 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600366 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600367 }
368 } else {
369 switch (type.getBasicType()) {
370 default:
John Kessenich4016e382016-07-15 11:53:56 -0600371 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600372 break;
373 case glslang::EbtBlock:
374 switch (type.getQualifier().storage) {
375 case glslang::EvqUniform:
376 case glslang::EvqBuffer:
377 switch (type.getQualifier().layoutPacking) {
378 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600379 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
380 default:
John Kessenich4016e382016-07-15 11:53:56 -0600381 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600382 }
383 case glslang::EvqVaryingIn:
384 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700385 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600386 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600387 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700388 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600389 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600390 }
391 }
392 }
393}
394
395// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600396// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700397// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800398spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600399{
Rex Xubbceed72016-05-21 09:40:44 +0800400 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700401 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600402 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800403 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700404 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700405 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600406 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800407#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800408 else if (qualifier.explicitInterp) {
409 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800410 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800411 }
Rex Xu9d93a232016-05-05 12:30:44 +0800412#endif
Rex Xubbceed72016-05-21 09:40:44 +0800413 else
John Kessenich4016e382016-07-15 11:53:56 -0600414 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800415}
416
417// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600418// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800419// should be applied.
420spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
421{
422 if (qualifier.patch)
423 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700424 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600425 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700426 else if (qualifier.sample) {
427 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600428 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700429 } else
John Kessenich4016e382016-07-15 11:53:56 -0600430 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600431}
432
John Kessenich92187592016-02-01 13:45:25 -0700433// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700434spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600435{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700436 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600437 return spv::DecorationInvariant;
438 else
John Kessenich4016e382016-07-15 11:53:56 -0600439 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600440}
441
qining9220dbb2016-05-04 17:34:38 -0400442// If glslang type is noContraction, return SPIR-V NoContraction decoration.
443spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
444{
445 if (qualifier.noContraction)
446 return spv::DecorationNoContraction;
447 else
John Kessenich4016e382016-07-15 11:53:56 -0600448 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400449}
450
John Kessenich5611c6d2018-04-05 11:25:02 -0600451// If glslang type is nonUniform, return SPIR-V NonUniform decoration.
452spv::Decoration TGlslangToSpvTraverser::TranslateNonUniformDecoration(const glslang::TQualifier& qualifier)
453{
454 if (qualifier.isNonUniform()) {
455 builder.addExtension("SPV_EXT_descriptor_indexing");
456 builder.addCapability(spv::CapabilityShaderNonUniformEXT);
457 return spv::DecorationNonUniformEXT;
458 } else
459 return spv::DecorationMax;
460}
461
David Netoa901ffe2016-06-08 14:11:40 +0100462// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
463// associated capabilities when required. For some built-in variables, a capability
464// is generated only when using the variable in an executable instruction, but not when
465// just declaring a struct member variable with it. This is true for PointSize,
466// ClipDistance, and CullDistance.
467spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600468{
469 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700470 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600471 // Defer adding the capability until the built-in is actually used.
472 if (! memberDeclaration) {
473 switch (glslangIntermediate->getStage()) {
474 case EShLangGeometry:
475 builder.addCapability(spv::CapabilityGeometryPointSize);
476 break;
477 case EShLangTessControl:
478 case EShLangTessEvaluation:
479 builder.addCapability(spv::CapabilityTessellationPointSize);
480 break;
481 default:
482 break;
483 }
John Kessenich92187592016-02-01 13:45:25 -0700484 }
485 return spv::BuiltInPointSize;
486
John Kessenichebb50532016-05-16 19:22:05 -0600487 // These *Distance capabilities logically belong here, but if the member is declared and
488 // then never used, consumers of SPIR-V prefer the capability not be declared.
489 // They are now generated when used, rather than here when declared.
490 // Potentially, the specification should be more clear what the minimum
491 // use needed is to trigger the capability.
492 //
John Kessenich92187592016-02-01 13:45:25 -0700493 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100494 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800495 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700496 return spv::BuiltInClipDistance;
497
498 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100499 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800500 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700501 return spv::BuiltInCullDistance;
502
503 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600504 builder.addCapability(spv::CapabilityMultiViewport);
505 if (glslangIntermediate->getStage() == EShLangVertex ||
506 glslangIntermediate->getStage() == EShLangTessControl ||
507 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800508
John Kessenichba6a3c22017-09-13 13:22:50 -0600509 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
510 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800511 }
John Kessenich92187592016-02-01 13:45:25 -0700512 return spv::BuiltInViewportIndex;
513
John Kessenich5e801132016-02-15 11:09:46 -0700514 case glslang::EbvSampleId:
515 builder.addCapability(spv::CapabilitySampleRateShading);
516 return spv::BuiltInSampleId;
517
518 case glslang::EbvSamplePosition:
519 builder.addCapability(spv::CapabilitySampleRateShading);
520 return spv::BuiltInSamplePosition;
521
522 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700523 return spv::BuiltInSampleMask;
524
John Kessenich78a45572016-07-08 14:05:15 -0600525 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600526 builder.addCapability(spv::CapabilityGeometry);
527 if (glslangIntermediate->getStage() == EShLangVertex ||
528 glslangIntermediate->getStage() == EShLangTessControl ||
529 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800530
John Kessenichba6a3c22017-09-13 13:22:50 -0600531 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
532 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800533 }
John Kessenich78a45572016-07-08 14:05:15 -0600534 return spv::BuiltInLayer;
535
John Kessenich140f3df2015-06-26 16:58:36 -0600536 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600537 case glslang::EbvVertexId: return spv::BuiltInVertexId;
538 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700539 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
540 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800541
John Kessenichda581a22015-10-14 14:10:30 -0600542 case glslang::EbvBaseVertex:
John Kessenich66011cb2018-03-06 16:12:04 -0700543 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800544 builder.addCapability(spv::CapabilityDrawParameters);
545 return spv::BuiltInBaseVertex;
546
John Kessenichda581a22015-10-14 14:10:30 -0600547 case glslang::EbvBaseInstance:
John Kessenich66011cb2018-03-06 16:12:04 -0700548 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800549 builder.addCapability(spv::CapabilityDrawParameters);
550 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200551
John Kessenichda581a22015-10-14 14:10:30 -0600552 case glslang::EbvDrawId:
John Kessenich66011cb2018-03-06 16:12:04 -0700553 addPre13Extension(spv::E_SPV_KHR_shader_draw_parameters);
Rex Xuf3b27472016-07-22 18:15:31 +0800554 builder.addCapability(spv::CapabilityDrawParameters);
555 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200556
557 case glslang::EbvPrimitiveId:
558 if (glslangIntermediate->getStage() == EShLangFragment)
559 builder.addCapability(spv::CapabilityGeometry);
560 return spv::BuiltInPrimitiveId;
561
Rex Xu37cdcee2017-06-29 17:46:34 +0800562 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800563 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
564 builder.addCapability(spv::CapabilityStencilExportEXT);
565 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800566
John Kessenich140f3df2015-06-26 16:58:36 -0600567 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600568 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
569 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
570 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
571 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
572 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
573 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
574 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600575 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
576 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
577 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
578 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
579 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
580 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
581 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
582 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800583
Rex Xu574ab042016-04-14 16:53:07 +0800584 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800585 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800586 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
587 return spv::BuiltInSubgroupSize;
588
Rex Xu574ab042016-04-14 16:53:07 +0800589 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800590 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800591 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
592 return spv::BuiltInSubgroupLocalInvocationId;
593
Rex Xu574ab042016-04-14 16:53:07 +0800594 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800595 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
596 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
597 return spv::BuiltInSubgroupEqMaskKHR;
598
Rex Xu574ab042016-04-14 16:53:07 +0800599 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800600 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
601 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
602 return spv::BuiltInSubgroupGeMaskKHR;
603
Rex Xu574ab042016-04-14 16:53:07 +0800604 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800605 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
606 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
607 return spv::BuiltInSubgroupGtMaskKHR;
608
Rex Xu574ab042016-04-14 16:53:07 +0800609 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800610 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
611 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
612 return spv::BuiltInSubgroupLeMaskKHR;
613
Rex Xu574ab042016-04-14 16:53:07 +0800614 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800615 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
616 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
617 return spv::BuiltInSubgroupLtMaskKHR;
618
John Kessenich66011cb2018-03-06 16:12:04 -0700619 case glslang::EbvNumSubgroups:
620 builder.addCapability(spv::CapabilityGroupNonUniform);
621 return spv::BuiltInNumSubgroups;
622
623 case glslang::EbvSubgroupID:
624 builder.addCapability(spv::CapabilityGroupNonUniform);
625 return spv::BuiltInSubgroupId;
626
627 case glslang::EbvSubgroupSize2:
628 builder.addCapability(spv::CapabilityGroupNonUniform);
629 return spv::BuiltInSubgroupSize;
630
631 case glslang::EbvSubgroupInvocation2:
632 builder.addCapability(spv::CapabilityGroupNonUniform);
633 return spv::BuiltInSubgroupLocalInvocationId;
634
635 case glslang::EbvSubgroupEqMask2:
636 builder.addCapability(spv::CapabilityGroupNonUniform);
637 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
638 return spv::BuiltInSubgroupEqMask;
639
640 case glslang::EbvSubgroupGeMask2:
641 builder.addCapability(spv::CapabilityGroupNonUniform);
642 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
643 return spv::BuiltInSubgroupGeMask;
644
645 case glslang::EbvSubgroupGtMask2:
646 builder.addCapability(spv::CapabilityGroupNonUniform);
647 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
648 return spv::BuiltInSubgroupGtMask;
649
650 case glslang::EbvSubgroupLeMask2:
651 builder.addCapability(spv::CapabilityGroupNonUniform);
652 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
653 return spv::BuiltInSubgroupLeMask;
654
655 case glslang::EbvSubgroupLtMask2:
656 builder.addCapability(spv::CapabilityGroupNonUniform);
657 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
658 return spv::BuiltInSubgroupLtMask;
Rex Xu9d93a232016-05-05 12:30:44 +0800659#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800660 case glslang::EbvBaryCoordNoPersp:
661 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
662 return spv::BuiltInBaryCoordNoPerspAMD;
663
664 case glslang::EbvBaryCoordNoPerspCentroid:
665 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
666 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
667
668 case glslang::EbvBaryCoordNoPerspSample:
669 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
670 return spv::BuiltInBaryCoordNoPerspSampleAMD;
671
672 case glslang::EbvBaryCoordSmooth:
673 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
674 return spv::BuiltInBaryCoordSmoothAMD;
675
676 case glslang::EbvBaryCoordSmoothCentroid:
677 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
678 return spv::BuiltInBaryCoordSmoothCentroidAMD;
679
680 case glslang::EbvBaryCoordSmoothSample:
681 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
682 return spv::BuiltInBaryCoordSmoothSampleAMD;
683
684 case glslang::EbvBaryCoordPullModel:
685 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
686 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800687#endif
chaoc771d89f2017-01-13 01:10:53 -0800688
John Kessenich6c8aaac2017-02-27 01:20:51 -0700689 case glslang::EbvDeviceIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700690 addPre13Extension(spv::E_SPV_KHR_device_group);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700691 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700692 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700693
694 case glslang::EbvViewIndex:
John Kessenich66011cb2018-03-06 16:12:04 -0700695 addPre13Extension(spv::E_SPV_KHR_multiview);
John Kessenich6c8aaac2017-02-27 01:20:51 -0700696 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700697 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700698
chaoc771d89f2017-01-13 01:10:53 -0800699#ifdef NV_EXTENSIONS
700 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800701 if (!memberDeclaration) {
702 builder.addExtension(spv::E_SPV_NV_viewport_array2);
703 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
704 }
chaoc771d89f2017-01-13 01:10:53 -0800705 return spv::BuiltInViewportMaskNV;
706 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800707 if (!memberDeclaration) {
708 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
709 builder.addCapability(spv::CapabilityShaderStereoViewNV);
710 }
chaoc771d89f2017-01-13 01:10:53 -0800711 return spv::BuiltInSecondaryPositionNV;
712 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800713 if (!memberDeclaration) {
714 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
715 builder.addCapability(spv::CapabilityShaderStereoViewNV);
716 }
chaoc771d89f2017-01-13 01:10:53 -0800717 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800718 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800719 if (!memberDeclaration) {
720 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
721 builder.addCapability(spv::CapabilityPerViewAttributesNV);
722 }
chaocdf3956c2017-02-14 14:52:34 -0800723 return spv::BuiltInPositionPerViewNV;
724 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800725 if (!memberDeclaration) {
726 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
727 builder.addCapability(spv::CapabilityPerViewAttributesNV);
728 }
chaocdf3956c2017-02-14 14:52:34 -0800729 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700730 case glslang::EbvFragFullyCoveredNV:
731 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
732 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
733 return spv::BuiltInFullyCoveredEXT;
chaoc771d89f2017-01-13 01:10:53 -0800734#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800735 default:
736 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600737 }
738}
739
Rex Xufc618912015-09-09 16:42:49 +0800740// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700741spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800742{
743 assert(type.getBasicType() == glslang::EbtSampler);
744
John Kessenich5d0fa972016-02-15 11:57:00 -0700745 // Check for capabilities
746 switch (type.getQualifier().layoutFormat) {
747 case glslang::ElfRg32f:
748 case glslang::ElfRg16f:
749 case glslang::ElfR11fG11fB10f:
750 case glslang::ElfR16f:
751 case glslang::ElfRgba16:
752 case glslang::ElfRgb10A2:
753 case glslang::ElfRg16:
754 case glslang::ElfRg8:
755 case glslang::ElfR16:
756 case glslang::ElfR8:
757 case glslang::ElfRgba16Snorm:
758 case glslang::ElfRg16Snorm:
759 case glslang::ElfRg8Snorm:
760 case glslang::ElfR16Snorm:
761 case glslang::ElfR8Snorm:
762
763 case glslang::ElfRg32i:
764 case glslang::ElfRg16i:
765 case glslang::ElfRg8i:
766 case glslang::ElfR16i:
767 case glslang::ElfR8i:
768
769 case glslang::ElfRgb10a2ui:
770 case glslang::ElfRg32ui:
771 case glslang::ElfRg16ui:
772 case glslang::ElfRg8ui:
773 case glslang::ElfR16ui:
774 case glslang::ElfR8ui:
775 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
776 break;
777
778 default:
779 break;
780 }
781
782 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800783 switch (type.getQualifier().layoutFormat) {
784 case glslang::ElfNone: return spv::ImageFormatUnknown;
785 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
786 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
787 case glslang::ElfR32f: return spv::ImageFormatR32f;
788 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
789 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
790 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
791 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
792 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
793 case glslang::ElfR16f: return spv::ImageFormatR16f;
794 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
795 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
796 case glslang::ElfRg16: return spv::ImageFormatRg16;
797 case glslang::ElfRg8: return spv::ImageFormatRg8;
798 case glslang::ElfR16: return spv::ImageFormatR16;
799 case glslang::ElfR8: return spv::ImageFormatR8;
800 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
801 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
802 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
803 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
804 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
805 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
806 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
807 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
808 case glslang::ElfR32i: return spv::ImageFormatR32i;
809 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
810 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
811 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
812 case glslang::ElfR16i: return spv::ImageFormatR16i;
813 case glslang::ElfR8i: return spv::ImageFormatR8i;
814 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
815 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
816 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
817 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
818 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
819 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
820 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
821 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
822 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
823 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600824 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800825 }
826}
827
John Kesseniche18fd202018-01-30 11:01:39 -0700828spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +0800829{
John Kesseniche18fd202018-01-30 11:01:39 -0700830 if (selectionNode.getFlatten())
831 return spv::SelectionControlFlattenMask;
832 if (selectionNode.getDontFlatten())
833 return spv::SelectionControlDontFlattenMask;
834 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +0800835}
836
John Kesseniche18fd202018-01-30 11:01:39 -0700837spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -0600838{
John Kesseniche18fd202018-01-30 11:01:39 -0700839 if (switchNode.getFlatten())
840 return spv::SelectionControlFlattenMask;
841 if (switchNode.getDontFlatten())
842 return spv::SelectionControlDontFlattenMask;
843 return spv::SelectionControlMaskNone;
844}
845
John Kessenicha2858d92018-01-31 08:11:18 -0700846// return a non-0 dependency if the dependency argument must be set
847spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
848 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -0700849{
850 spv::LoopControlMask control = spv::LoopControlMaskNone;
851
852 if (loopNode.getDontUnroll())
853 control = control | spv::LoopControlDontUnrollMask;
854 if (loopNode.getUnroll())
855 control = control | spv::LoopControlUnrollMask;
LoopDawg4425f242018-02-18 11:40:01 -0700856 if (unsigned(loopNode.getLoopDependency()) == glslang::TIntermLoop::dependencyInfinite)
John Kessenicha2858d92018-01-31 08:11:18 -0700857 control = control | spv::LoopControlDependencyInfiniteMask;
858 else if (loopNode.getLoopDependency() > 0) {
859 control = control | spv::LoopControlDependencyLengthMask;
860 dependencyLength = loopNode.getLoopDependency();
861 }
John Kesseniche18fd202018-01-30 11:01:39 -0700862
863 return control;
steve-lunargf1709e72017-05-02 20:14:50 -0600864}
865
John Kessenicha5c5fb62017-05-05 05:09:58 -0600866// Translate glslang type to SPIR-V storage class.
867spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
868{
869 if (type.getQualifier().isPipeInput())
870 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600871 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600872 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600873
874 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
875 type.getQualifier().storage == glslang::EvqUniform) {
876 if (type.getBasicType() == glslang::EbtAtomicUint)
877 return spv::StorageClassAtomicCounter;
878 if (type.containsOpaque())
879 return spv::StorageClassUniformConstant;
880 }
881
882 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenich66011cb2018-03-06 16:12:04 -0700883 addPre13Extension(spv::E_SPV_KHR_storage_buffer_storage_class);
John Kessenicha5c5fb62017-05-05 05:09:58 -0600884 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600885 }
886
887 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600888 if (type.getQualifier().layoutPushConstant)
889 return spv::StorageClassPushConstant;
890 if (type.getBasicType() == glslang::EbtBlock)
891 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600892 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600893 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600894
895 switch (type.getQualifier().storage) {
896 case glslang::EvqShared: return spv::StorageClassWorkgroup;
897 case glslang::EvqGlobal: return spv::StorageClassPrivate;
898 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
899 case glslang::EvqTemporary: return spv::StorageClassFunction;
900 default:
901 assert(0);
902 break;
903 }
904
905 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600906}
907
John Kessenich5611c6d2018-04-05 11:25:02 -0600908// Add capabilities pertaining to how an array is indexed.
909void TGlslangToSpvTraverser::addIndirectionIndexCapabilities(const glslang::TType& baseType,
910 const glslang::TType& indexType)
911{
912 if (indexType.getQualifier().isNonUniform()) {
913 // deal with an asserted non-uniform index
Jeff Bolzc140b962018-07-12 16:51:18 -0500914 // SPV_EXT_descriptor_indexing already added in TranslateNonUniformDecoration
John Kessenich5611c6d2018-04-05 11:25:02 -0600915 if (baseType.getBasicType() == glslang::EbtSampler) {
916 if (baseType.getQualifier().hasAttachment())
917 builder.addCapability(spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT);
918 else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer)
919 builder.addCapability(spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT);
920 else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer)
921 builder.addCapability(spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT);
922 else if (baseType.isImage())
923 builder.addCapability(spv::CapabilityStorageImageArrayNonUniformIndexingEXT);
924 else if (baseType.isTexture())
925 builder.addCapability(spv::CapabilitySampledImageArrayNonUniformIndexingEXT);
926 } else if (baseType.getBasicType() == glslang::EbtBlock) {
927 if (baseType.getQualifier().storage == glslang::EvqBuffer)
928 builder.addCapability(spv::CapabilityStorageBufferArrayNonUniformIndexingEXT);
929 else if (baseType.getQualifier().storage == glslang::EvqUniform)
930 builder.addCapability(spv::CapabilityUniformBufferArrayNonUniformIndexingEXT);
931 }
932 } else {
933 // assume a dynamically uniform index
934 if (baseType.getBasicType() == glslang::EbtSampler) {
Jeff Bolzc140b962018-07-12 16:51:18 -0500935 if (baseType.getQualifier().hasAttachment()) {
936 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -0600937 builder.addCapability(spv::CapabilityInputAttachmentArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -0500938 } else if (baseType.isImage() && baseType.getSampler().dim == glslang::EsdBuffer) {
939 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -0600940 builder.addCapability(spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -0500941 } else if (baseType.isTexture() && baseType.getSampler().dim == glslang::EsdBuffer) {
942 builder.addExtension("SPV_EXT_descriptor_indexing");
John Kessenich5611c6d2018-04-05 11:25:02 -0600943 builder.addCapability(spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT);
Jeff Bolzc140b962018-07-12 16:51:18 -0500944 }
John Kessenich5611c6d2018-04-05 11:25:02 -0600945 }
946 }
947}
948
qining25262b32016-05-06 17:25:16 -0400949// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700950// descriptor set.
951bool IsDescriptorResource(const glslang::TType& type)
952{
John Kessenichf7497e22016-03-08 21:36:22 -0700953 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700954 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700955 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700956
957 // non block...
958 // basically samplerXXX/subpass/sampler/texture are all included
959 // if they are the global-scope-class, not the function parameter
960 // (or local, if they ever exist) class.
961 if (type.getBasicType() == glslang::EbtSampler)
962 return type.getQualifier().isUniformOrBuffer();
963
964 // None of the above.
965 return false;
966}
967
John Kesseniche0b6cad2015-12-24 10:30:13 -0700968void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
969{
970 if (child.layoutMatrix == glslang::ElmNone)
971 child.layoutMatrix = parent.layoutMatrix;
972
973 if (parent.invariant)
974 child.invariant = true;
975 if (parent.nopersp)
976 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800977#ifdef AMD_EXTENSIONS
978 if (parent.explicitInterp)
979 child.explicitInterp = true;
980#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700981 if (parent.flat)
982 child.flat = true;
983 if (parent.centroid)
984 child.centroid = true;
985 if (parent.patch)
986 child.patch = true;
987 if (parent.sample)
988 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800989 if (parent.coherent)
990 child.coherent = true;
991 if (parent.volatil)
992 child.volatil = true;
993 if (parent.restrict)
994 child.restrict = true;
995 if (parent.readonly)
996 child.readonly = true;
997 if (parent.writeonly)
998 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700999}
1000
John Kessenichf2b7f332016-09-01 17:05:23 -06001001bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001002{
John Kessenich7b9fa252016-01-21 18:56:57 -07001003 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -06001004 // - struct members might inherit from a struct declaration
1005 // (note that non-block structs don't explicitly inherit,
1006 // only implicitly, meaning no decoration involved)
1007 // - affect decorations on the struct members
1008 // (note smooth does not, and expecting something like volatile
1009 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001010 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -06001011 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -07001012}
1013
John Kessenich140f3df2015-06-26 16:58:36 -06001014//
1015// Implement the TGlslangToSpvTraverser class.
1016//
1017
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001018TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -06001019 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
1020 : TIntermTraverser(true, false, true),
1021 options(options),
1022 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -06001023 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -07001024 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -07001025 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -06001026 glslangIntermediate(glslangIntermediate)
1027{
1028 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
1029
1030 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -06001031 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
1032 glslangIntermediate->getVersion());
1033
John Kessenich121853f2017-05-31 17:11:16 -06001034 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -06001035 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -06001036 builder.setSourceFile(glslangIntermediate->getSourceFile());
1037
1038 // Set the source shader's text. If for SPV version 1.0, include
1039 // a preamble in comments stating the OpModuleProcessed instructions.
1040 // Otherwise, emit those as actual instructions.
1041 std::string text;
1042 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
1043 for (int p = 0; p < (int)processes.size(); ++p) {
1044 if (glslangIntermediate->getSpv().spv < 0x00010100) {
1045 text.append("// OpModuleProcessed ");
1046 text.append(processes[p]);
1047 text.append("\n");
1048 } else
1049 builder.addModuleProcessed(processes[p]);
1050 }
1051 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
1052 text.append("#line 1\n");
1053 text.append(glslangIntermediate->getSourceText());
1054 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -06001055 }
John Kessenich140f3df2015-06-26 16:58:36 -06001056 stdBuiltins = builder.import("GLSL.std.450");
1057 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -06001058 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
1059 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -06001060
1061 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -06001062 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
1063 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -06001064 builder.addSourceExtension(it->c_str());
1065
1066 // Add the top-level modes for this shader.
1067
John Kessenich92187592016-02-01 13:45:25 -07001068 if (glslangIntermediate->getXfbMode()) {
1069 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001070 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -07001071 }
John Kessenich140f3df2015-06-26 16:58:36 -06001072
1073 unsigned int mode;
1074 switch (glslangIntermediate->getStage()) {
1075 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -06001076 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001077 break;
1078
steve-lunarge7412492017-03-23 11:56:07 -06001079 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -06001080 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -06001081 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -06001082
steve-lunarge7412492017-03-23 11:56:07 -06001083 glslang::TLayoutGeometry primitive;
1084
1085 if (glslangIntermediate->getStage() == EShLangTessControl) {
1086 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1087 primitive = glslangIntermediate->getOutputPrimitive();
1088 } else {
1089 primitive = glslangIntermediate->getInputPrimitive();
1090 }
1091
1092 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -07001093 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
1094 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
1095 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -06001096 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001097 }
John Kessenich4016e382016-07-15 11:53:56 -06001098 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001099 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1100
John Kesseniche6903322015-10-13 16:29:02 -06001101 switch (glslangIntermediate->getVertexSpacing()) {
1102 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
1103 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
1104 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -06001105 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001106 }
John Kessenich4016e382016-07-15 11:53:56 -06001107 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001108 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1109
1110 switch (glslangIntermediate->getVertexOrder()) {
1111 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
1112 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -06001113 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001114 }
John Kessenich4016e382016-07-15 11:53:56 -06001115 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001116 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1117
1118 if (glslangIntermediate->getPointMode())
1119 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001120 break;
1121
1122 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001123 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001124 switch (glslangIntermediate->getInputPrimitive()) {
1125 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1126 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1127 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001128 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001129 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001130 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001131 }
John Kessenich4016e382016-07-15 11:53:56 -06001132 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001133 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001134
John Kessenich140f3df2015-06-26 16:58:36 -06001135 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1136
1137 switch (glslangIntermediate->getOutputPrimitive()) {
1138 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1139 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1140 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001141 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001142 }
John Kessenich4016e382016-07-15 11:53:56 -06001143 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001144 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1145 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1146 break;
1147
1148 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001149 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001150 if (glslangIntermediate->getPixelCenterInteger())
1151 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001152
John Kessenich140f3df2015-06-26 16:58:36 -06001153 if (glslangIntermediate->getOriginUpperLeft())
1154 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001155 else
1156 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001157
1158 if (glslangIntermediate->getEarlyFragmentTests())
1159 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1160
chaocc1204522017-06-30 17:14:30 -07001161 if (glslangIntermediate->getPostDepthCoverage()) {
1162 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1163 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1164 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1165 }
1166
John Kesseniche6903322015-10-13 16:29:02 -06001167 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001168 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1169 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001170 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001171 }
John Kessenich4016e382016-07-15 11:53:56 -06001172 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001173 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1174
1175 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1176 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001177 break;
1178
1179 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001180 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001181 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1182 glslangIntermediate->getLocalSize(1),
1183 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001184 break;
1185
1186 default:
1187 break;
1188 }
John Kessenich140f3df2015-06-26 16:58:36 -06001189}
1190
John Kessenichfca82622016-11-26 13:23:20 -07001191// Finish creating SPV, after the traversal is complete.
1192void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001193{
John Kessenichf04c51b2018-08-03 15:56:12 -06001194 // Finish the entry point function
John Kessenich517fe7a2016-11-26 13:31:47 -07001195 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001196 builder.setBuildPoint(shaderEntry->getLastBlock());
1197 builder.leaveFunction();
1198 }
1199
John Kessenich7ba63412015-12-20 17:37:07 -07001200 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001201 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1202 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001203
John Kessenichf04c51b2018-08-03 15:56:12 -06001204 // Add capabilities, extensions, remove unneeded decorations, etc.,
1205 // based on the resulting SPIR-V.
1206 builder.postProcess();
John Kessenich7ba63412015-12-20 17:37:07 -07001207}
1208
John Kessenichfca82622016-11-26 13:23:20 -07001209// Write the SPV into 'out'.
1210void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001211{
John Kessenichfca82622016-11-26 13:23:20 -07001212 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001213}
1214
1215//
1216// Implement the traversal functions.
1217//
1218// Return true from interior nodes to have the external traversal
1219// continue on to children. Return false if children were
1220// already processed.
1221//
1222
1223//
qining25262b32016-05-06 17:25:16 -04001224// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001225// - uniform/input reads
1226// - output writes
1227// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1228// - something simple that degenerates into the last bullet
1229//
1230void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1231{
qining75d1d802016-04-06 14:42:01 -04001232 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1233 if (symbol->getType().getQualifier().isSpecConstant())
1234 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1235
John Kessenich140f3df2015-06-26 16:58:36 -06001236 // getSymbolId() will set up all the IO decorations on the first call.
1237 // Formal function parameters were mapped during makeFunctions().
1238 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001239
1240 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1241 if (builder.isPointer(id)) {
1242 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001243 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1244 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1245 iOSet.insert(id);
1246 }
John Kessenich7ba63412015-12-20 17:37:07 -07001247 }
1248
1249 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001250 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001251 // Prepare to generate code for the access
1252
1253 // L-value chains will be computed left to right. We're on the symbol now,
1254 // which is the left-most part of the access chain, so now is "clear" time,
1255 // followed by setting the base.
1256 builder.clearAccessChain();
1257
1258 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001259 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001260 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001261 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001262 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001263 // These are also pure R-values.
1264 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001265 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001266 builder.setAccessChainRValue(id);
1267 else
1268 builder.setAccessChainLValue(id);
1269 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001270
1271 // Process linkage-only nodes for any special additional interface work.
1272 if (linkageOnly) {
1273 if (glslangIntermediate->getHlslFunctionality1()) {
1274 // Map implicit counter buffers to their originating buffers, which should have been
1275 // seen by now, given earlier pruning of unused counters, and preservation of order
1276 // of declaration.
1277 if (symbol->getType().getQualifier().isUniformOrBuffer()) {
1278 if (!glslangIntermediate->hasCounterBufferName(symbol->getName())) {
1279 // Save possible originating buffers for counter buffers, keyed by
1280 // making the potential counter-buffer name.
1281 std::string keyName = symbol->getName().c_str();
1282 keyName = glslangIntermediate->addCounterBufferName(keyName);
1283 counterOriginator[keyName] = symbol;
1284 } else {
1285 // Handle a counter buffer, by finding the saved originating buffer.
1286 std::string keyName = symbol->getName().c_str();
1287 auto it = counterOriginator.find(keyName);
1288 if (it != counterOriginator.end()) {
1289 id = getSymbolId(it->second);
1290 if (id != spv::NoResult) {
1291 spv::Id counterId = getSymbolId(symbol);
John Kessenichf52b6382018-04-05 19:35:38 -06001292 if (counterId != spv::NoResult) {
1293 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
John Kessenich5d610ee2018-03-07 18:05:55 -07001294 builder.addDecorationId(id, spv::DecorationHlslCounterBufferGOOGLE, counterId);
John Kessenichf52b6382018-04-05 19:35:38 -06001295 }
John Kessenich5d610ee2018-03-07 18:05:55 -07001296 }
1297 }
1298 }
1299 }
1300 }
1301 }
John Kessenich140f3df2015-06-26 16:58:36 -06001302}
1303
1304bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1305{
John Kesseniche485c7a2017-05-31 18:50:53 -06001306 builder.setLine(node->getLoc().line);
1307
qining40887662016-04-03 22:20:42 -04001308 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1309 if (node->getType().getQualifier().isSpecConstant())
1310 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1311
John Kessenich140f3df2015-06-26 16:58:36 -06001312 // First, handle special cases
1313 switch (node->getOp()) {
1314 case glslang::EOpAssign:
1315 case glslang::EOpAddAssign:
1316 case glslang::EOpSubAssign:
1317 case glslang::EOpMulAssign:
1318 case glslang::EOpVectorTimesMatrixAssign:
1319 case glslang::EOpVectorTimesScalarAssign:
1320 case glslang::EOpMatrixTimesScalarAssign:
1321 case glslang::EOpMatrixTimesMatrixAssign:
1322 case glslang::EOpDivAssign:
1323 case glslang::EOpModAssign:
1324 case glslang::EOpAndAssign:
1325 case glslang::EOpInclusiveOrAssign:
1326 case glslang::EOpExclusiveOrAssign:
1327 case glslang::EOpLeftShiftAssign:
1328 case glslang::EOpRightShiftAssign:
1329 // A bin-op assign "a += b" means the same thing as "a = a + b"
1330 // where a is evaluated before b. For a simple assignment, GLSL
1331 // says to evaluate the left before the right. So, always, left
1332 // node then right node.
1333 {
1334 // get the left l-value, save it away
1335 builder.clearAccessChain();
1336 node->getLeft()->traverse(this);
1337 spv::Builder::AccessChain lValue = builder.getAccessChain();
1338
1339 // evaluate the right
1340 builder.clearAccessChain();
1341 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001342 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001343
1344 if (node->getOp() != glslang::EOpAssign) {
1345 // the left is also an r-value
1346 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001347 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001348
1349 // do the operation
John Kessenichead86222018-03-28 18:01:20 -06001350 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001351 TranslateNoContractionDecoration(node->getType().getQualifier()),
1352 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001353 rValue = createBinaryOperation(node->getOp(), decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06001354 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1355 node->getType().getBasicType());
1356
1357 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001358 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001359 }
1360
1361 // store the result
1362 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001363 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001364
1365 // assignments are expressions having an rValue after they are evaluated...
1366 builder.clearAccessChain();
1367 builder.setAccessChainRValue(rValue);
1368 }
1369 return false;
1370 case glslang::EOpIndexDirect:
1371 case glslang::EOpIndexDirectStruct:
1372 {
1373 // Get the left part of the access chain.
1374 node->getLeft()->traverse(this);
1375
1376 // Add the next element in the chain
1377
David Netoa901ffe2016-06-08 14:11:40 +01001378 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001379 if (! node->getLeft()->getType().isArray() &&
1380 node->getLeft()->getType().isVector() &&
1381 node->getOp() == glslang::EOpIndexDirect) {
1382 // This is essentially a hard-coded vector swizzle of size 1,
1383 // so short circuit the access-chain stuff with a swizzle.
1384 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001385 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001386 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001387 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001388 int spvIndex = glslangIndex;
1389 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1390 node->getOp() == glslang::EOpIndexDirectStruct)
1391 {
1392 // This may be, e.g., an anonymous block-member selection, which generally need
1393 // index remapping due to hidden members in anonymous blocks.
1394 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1395 assert(remapper.size() > 0);
1396 spvIndex = remapper[glslangIndex];
1397 }
John Kessenichebb50532016-05-16 19:22:05 -06001398
David Netoa901ffe2016-06-08 14:11:40 +01001399 // normal case for indexing array or structure or block
1400 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1401
1402 // Add capabilities here for accessing PointSize and clip/cull distance.
1403 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001404 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001405 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001406 }
1407 }
1408 return false;
1409 case glslang::EOpIndexIndirect:
1410 {
1411 // Structure or array or vector indirection.
1412 // Will use native SPIR-V access-chain for struct and array indirection;
1413 // matrices are arrays of vectors, so will also work for a matrix.
1414 // Will use the access chain's 'component' for variable index into a vector.
1415
1416 // This adapter is building access chains left to right.
1417 // Set up the access chain to the left.
1418 node->getLeft()->traverse(this);
1419
1420 // save it so that computing the right side doesn't trash it
1421 spv::Builder::AccessChain partial = builder.getAccessChain();
1422
1423 // compute the next index in the chain
1424 builder.clearAccessChain();
1425 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001426 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001427
John Kessenich5611c6d2018-04-05 11:25:02 -06001428 addIndirectionIndexCapabilities(node->getLeft()->getType(), node->getRight()->getType());
1429
John Kessenich140f3df2015-06-26 16:58:36 -06001430 // restore the saved access chain
1431 builder.setAccessChain(partial);
1432
1433 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001434 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001435 else
John Kessenichfa668da2015-09-13 14:46:30 -06001436 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001437 }
1438 return false;
1439 case glslang::EOpVectorSwizzle:
1440 {
1441 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001442 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001443 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001444 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001445 }
1446 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001447 case glslang::EOpMatrixSwizzle:
1448 logger->missingFunctionality("matrix swizzle");
1449 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001450 case glslang::EOpLogicalOr:
1451 case glslang::EOpLogicalAnd:
1452 {
1453
1454 // These may require short circuiting, but can sometimes be done as straight
1455 // binary operations. The right operand must be short circuited if it has
1456 // side effects, and should probably be if it is complex.
1457 if (isTrivial(node->getRight()->getAsTyped()))
1458 break; // handle below as a normal binary operation
1459 // otherwise, we need to do dynamic short circuiting on the right operand
1460 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1461 builder.clearAccessChain();
1462 builder.setAccessChainRValue(result);
1463 }
1464 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001465 default:
1466 break;
1467 }
1468
1469 // Assume generic binary op...
1470
John Kessenich32cfd492016-02-02 12:37:46 -07001471 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001472 builder.clearAccessChain();
1473 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001474 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001475
John Kessenich32cfd492016-02-02 12:37:46 -07001476 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001477 builder.clearAccessChain();
1478 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001479 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001480
John Kessenich32cfd492016-02-02 12:37:46 -07001481 // get result
John Kessenichead86222018-03-28 18:01:20 -06001482 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001483 TranslateNoContractionDecoration(node->getType().getQualifier()),
1484 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06001485 spv::Id result = createBinaryOperation(node->getOp(), decorations,
John Kessenich32cfd492016-02-02 12:37:46 -07001486 convertGlslangToSpvType(node->getType()), left, right,
1487 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001488
John Kessenich50e57562015-12-21 21:21:11 -07001489 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001490 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001491 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001492 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001493 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001494 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001495 return false;
1496 }
John Kessenich140f3df2015-06-26 16:58:36 -06001497}
1498
1499bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1500{
John Kesseniche485c7a2017-05-31 18:50:53 -06001501 builder.setLine(node->getLoc().line);
1502
qining40887662016-04-03 22:20:42 -04001503 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1504 if (node->getType().getQualifier().isSpecConstant())
1505 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1506
John Kessenichfc51d282015-08-19 13:34:18 -06001507 spv::Id result = spv::NoResult;
1508
1509 // try texturing first
1510 result = createImageTextureFunctionCall(node);
1511 if (result != spv::NoResult) {
1512 builder.clearAccessChain();
1513 builder.setAccessChainRValue(result);
1514
1515 return false; // done with this node
1516 }
1517
1518 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001519
1520 if (node->getOp() == glslang::EOpArrayLength) {
1521 // Quite special; won't want to evaluate the operand.
1522
John Kessenich5611c6d2018-04-05 11:25:02 -06001523 // Currently, the front-end does not allow .length() on an array until it is sized,
1524 // except for the last block membeor of an SSBO.
1525 // TODO: If this changes, link-time sized arrays might show up here, and need their
1526 // size extracted.
1527
John Kessenichc9a80832015-09-12 12:17:44 -06001528 // Normal .length() would have been constant folded by the front-end.
1529 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001530 // SPV wants "block" and member number as the operands, go get them.
John Kessenichead86222018-03-28 18:01:20 -06001531
John Kessenichc9a80832015-09-12 12:17:44 -06001532 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1533 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001534 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1535 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001536
1537 builder.clearAccessChain();
1538 builder.setAccessChainRValue(length);
1539
1540 return false;
1541 }
1542
John Kessenichfc51d282015-08-19 13:34:18 -06001543 // Start by evaluating the operand
1544
John Kessenich8c8505c2016-07-26 12:50:38 -06001545 // Does it need a swizzle inversion? If so, evaluation is inverted;
1546 // operate first on the swizzle base, then apply the swizzle.
1547 spv::Id invertedType = spv::NoType;
1548 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1549 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1550 invertedType = getInvertedSwizzleType(*node->getOperand());
1551
John Kessenich140f3df2015-06-26 16:58:36 -06001552 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001553 if (invertedType != spv::NoType)
1554 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1555 else
1556 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001557
Rex Xufc618912015-09-09 16:42:49 +08001558 spv::Id operand = spv::NoResult;
1559
1560 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1561 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001562 node->getOp() == glslang::EOpAtomicCounter ||
1563 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001564 operand = builder.accessChainGetLValue(); // Special case l-value operands
1565 else
John Kessenich32cfd492016-02-02 12:37:46 -07001566 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001567
John Kessenichead86222018-03-28 18:01:20 -06001568 OpDecorations decorations = { TranslatePrecisionDecoration(node->getOperationPrecision()),
John Kessenich5611c6d2018-04-05 11:25:02 -06001569 TranslateNoContractionDecoration(node->getType().getQualifier()),
1570 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenich140f3df2015-06-26 16:58:36 -06001571
1572 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001573 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001574 result = createConversion(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001575
1576 // if not, then possibly an operation
1577 if (! result)
John Kessenichead86222018-03-28 18:01:20 -06001578 result = createUnaryOperation(node->getOp(), decorations, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001579
1580 if (result) {
John Kessenich5611c6d2018-04-05 11:25:02 -06001581 if (invertedType) {
John Kessenichead86222018-03-28 18:01:20 -06001582 result = createInvertedSwizzle(decorations.precision, *node->getOperand(), result);
John Kessenich5611c6d2018-04-05 11:25:02 -06001583 builder.addDecoration(result, decorations.nonUniform);
1584 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001585
John Kessenich140f3df2015-06-26 16:58:36 -06001586 builder.clearAccessChain();
1587 builder.setAccessChainRValue(result);
1588
1589 return false; // done with this node
1590 }
1591
1592 // it must be a special case, check...
1593 switch (node->getOp()) {
1594 case glslang::EOpPostIncrement:
1595 case glslang::EOpPostDecrement:
1596 case glslang::EOpPreIncrement:
1597 case glslang::EOpPreDecrement:
1598 {
1599 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001600 spv::Id one = 0;
1601 if (node->getBasicType() == glslang::EbtFloat)
1602 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001603 else if (node->getBasicType() == glslang::EbtDouble)
1604 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001605 else if (node->getBasicType() == glslang::EbtFloat16)
1606 one = builder.makeFloat16Constant(1.0F);
John Kessenich66011cb2018-03-06 16:12:04 -07001607 else if (node->getBasicType() == glslang::EbtInt8 || node->getBasicType() == glslang::EbtUint8)
1608 one = builder.makeInt8Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001609 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1610 one = builder.makeInt16Constant(1);
John Kessenich66011cb2018-03-06 16:12:04 -07001611 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1612 one = builder.makeInt64Constant(1);
Rex Xu8ff43de2016-04-22 16:51:45 +08001613 else
1614 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001615 glslang::TOperator op;
1616 if (node->getOp() == glslang::EOpPreIncrement ||
1617 node->getOp() == glslang::EOpPostIncrement)
1618 op = glslang::EOpAdd;
1619 else
1620 op = glslang::EOpSub;
1621
John Kessenichead86222018-03-28 18:01:20 -06001622 spv::Id result = createBinaryOperation(op, decorations,
Rex Xu8ff43de2016-04-22 16:51:45 +08001623 convertGlslangToSpvType(node->getType()), operand, one,
1624 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001625 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001626
1627 // The result of operation is always stored, but conditionally the
1628 // consumed result. The consumed result is always an r-value.
1629 builder.accessChainStore(result);
1630 builder.clearAccessChain();
1631 if (node->getOp() == glslang::EOpPreIncrement ||
1632 node->getOp() == glslang::EOpPreDecrement)
1633 builder.setAccessChainRValue(result);
1634 else
1635 builder.setAccessChainRValue(operand);
1636 }
1637
1638 return false;
1639
1640 case glslang::EOpEmitStreamVertex:
1641 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1642 return false;
1643 case glslang::EOpEndStreamPrimitive:
1644 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1645 return false;
1646
1647 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001648 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001649 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001650 }
John Kessenich140f3df2015-06-26 16:58:36 -06001651}
1652
1653bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1654{
qining27e04a02016-04-14 16:40:20 -04001655 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1656 if (node->getType().getQualifier().isSpecConstant())
1657 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1658
John Kessenichfc51d282015-08-19 13:34:18 -06001659 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001660 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1661 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001662
1663 // try texturing
1664 result = createImageTextureFunctionCall(node);
1665 if (result != spv::NoResult) {
1666 builder.clearAccessChain();
1667 builder.setAccessChainRValue(result);
1668
1669 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001670#ifdef AMD_EXTENSIONS
1671 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1672#else
John Kessenich56bab042015-09-16 10:54:31 -06001673 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001674#endif
Rex Xufc618912015-09-09 16:42:49 +08001675 // "imageStore" is a special case, which has no result
1676 return false;
1677 }
John Kessenichfc51d282015-08-19 13:34:18 -06001678
John Kessenich140f3df2015-06-26 16:58:36 -06001679 glslang::TOperator binOp = glslang::EOpNull;
1680 bool reduceComparison = true;
1681 bool isMatrix = false;
1682 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001683 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001684
1685 assert(node->getOp());
1686
John Kessenichf6640762016-08-01 19:44:00 -06001687 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001688
1689 switch (node->getOp()) {
1690 case glslang::EOpSequence:
1691 {
1692 if (preVisit)
1693 ++sequenceDepth;
1694 else
1695 --sequenceDepth;
1696
1697 if (sequenceDepth == 1) {
1698 // If this is the parent node of all the functions, we want to see them
1699 // early, so all call points have actual SPIR-V functions to reference.
1700 // In all cases, still let the traverser visit the children for us.
1701 makeFunctions(node->getAsAggregate()->getSequence());
1702
John Kessenich6fccb3c2016-09-19 16:01:41 -06001703 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001704 // anything else gets there, so visit out of order, doing them all now.
1705 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1706
John Kessenich6a60c2f2016-12-08 21:01:59 -07001707 // 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 -06001708 // so do them manually.
1709 visitFunctions(node->getAsAggregate()->getSequence());
1710
1711 return false;
1712 }
1713
1714 return true;
1715 }
1716 case glslang::EOpLinkerObjects:
1717 {
1718 if (visit == glslang::EvPreVisit)
1719 linkageOnly = true;
1720 else
1721 linkageOnly = false;
1722
1723 return true;
1724 }
1725 case glslang::EOpComma:
1726 {
1727 // processing from left to right naturally leaves the right-most
1728 // lying around in the access chain
1729 glslang::TIntermSequence& glslangOperands = node->getSequence();
1730 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1731 glslangOperands[i]->traverse(this);
1732
1733 return false;
1734 }
1735 case glslang::EOpFunction:
1736 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001737 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001738 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001739 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001740 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001741 } else {
1742 handleFunctionEntry(node);
1743 }
1744 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001745 if (inEntryPoint)
1746 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001747 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001748 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001749 }
1750
1751 return true;
1752 case glslang::EOpParameters:
1753 // Parameters will have been consumed by EOpFunction processing, but not
1754 // the body, so we still visited the function node's children, making this
1755 // child redundant.
1756 return false;
1757 case glslang::EOpFunctionCall:
1758 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001759 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001760 if (node->isUserDefined())
1761 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001762 // 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 -07001763 if (result) {
1764 builder.clearAccessChain();
1765 builder.setAccessChainRValue(result);
1766 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001767 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001768
1769 return false;
1770 }
1771 case glslang::EOpConstructMat2x2:
1772 case glslang::EOpConstructMat2x3:
1773 case glslang::EOpConstructMat2x4:
1774 case glslang::EOpConstructMat3x2:
1775 case glslang::EOpConstructMat3x3:
1776 case glslang::EOpConstructMat3x4:
1777 case glslang::EOpConstructMat4x2:
1778 case glslang::EOpConstructMat4x3:
1779 case glslang::EOpConstructMat4x4:
1780 case glslang::EOpConstructDMat2x2:
1781 case glslang::EOpConstructDMat2x3:
1782 case glslang::EOpConstructDMat2x4:
1783 case glslang::EOpConstructDMat3x2:
1784 case glslang::EOpConstructDMat3x3:
1785 case glslang::EOpConstructDMat3x4:
1786 case glslang::EOpConstructDMat4x2:
1787 case glslang::EOpConstructDMat4x3:
1788 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001789 case glslang::EOpConstructIMat2x2:
1790 case glslang::EOpConstructIMat2x3:
1791 case glslang::EOpConstructIMat2x4:
1792 case glslang::EOpConstructIMat3x2:
1793 case glslang::EOpConstructIMat3x3:
1794 case glslang::EOpConstructIMat3x4:
1795 case glslang::EOpConstructIMat4x2:
1796 case glslang::EOpConstructIMat4x3:
1797 case glslang::EOpConstructIMat4x4:
1798 case glslang::EOpConstructUMat2x2:
1799 case glslang::EOpConstructUMat2x3:
1800 case glslang::EOpConstructUMat2x4:
1801 case glslang::EOpConstructUMat3x2:
1802 case glslang::EOpConstructUMat3x3:
1803 case glslang::EOpConstructUMat3x4:
1804 case glslang::EOpConstructUMat4x2:
1805 case glslang::EOpConstructUMat4x3:
1806 case glslang::EOpConstructUMat4x4:
1807 case glslang::EOpConstructBMat2x2:
1808 case glslang::EOpConstructBMat2x3:
1809 case glslang::EOpConstructBMat2x4:
1810 case glslang::EOpConstructBMat3x2:
1811 case glslang::EOpConstructBMat3x3:
1812 case glslang::EOpConstructBMat3x4:
1813 case glslang::EOpConstructBMat4x2:
1814 case glslang::EOpConstructBMat4x3:
1815 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001816 case glslang::EOpConstructF16Mat2x2:
1817 case glslang::EOpConstructF16Mat2x3:
1818 case glslang::EOpConstructF16Mat2x4:
1819 case glslang::EOpConstructF16Mat3x2:
1820 case glslang::EOpConstructF16Mat3x3:
1821 case glslang::EOpConstructF16Mat3x4:
1822 case glslang::EOpConstructF16Mat4x2:
1823 case glslang::EOpConstructF16Mat4x3:
1824 case glslang::EOpConstructF16Mat4x4:
John Kessenich140f3df2015-06-26 16:58:36 -06001825 isMatrix = true;
1826 // fall through
1827 case glslang::EOpConstructFloat:
1828 case glslang::EOpConstructVec2:
1829 case glslang::EOpConstructVec3:
1830 case glslang::EOpConstructVec4:
1831 case glslang::EOpConstructDouble:
1832 case glslang::EOpConstructDVec2:
1833 case glslang::EOpConstructDVec3:
1834 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001835 case glslang::EOpConstructFloat16:
1836 case glslang::EOpConstructF16Vec2:
1837 case glslang::EOpConstructF16Vec3:
1838 case glslang::EOpConstructF16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001839 case glslang::EOpConstructBool:
1840 case glslang::EOpConstructBVec2:
1841 case glslang::EOpConstructBVec3:
1842 case glslang::EOpConstructBVec4:
John Kessenich66011cb2018-03-06 16:12:04 -07001843 case glslang::EOpConstructInt8:
1844 case glslang::EOpConstructI8Vec2:
1845 case glslang::EOpConstructI8Vec3:
1846 case glslang::EOpConstructI8Vec4:
1847 case glslang::EOpConstructUint8:
1848 case glslang::EOpConstructU8Vec2:
1849 case glslang::EOpConstructU8Vec3:
1850 case glslang::EOpConstructU8Vec4:
1851 case glslang::EOpConstructInt16:
1852 case glslang::EOpConstructI16Vec2:
1853 case glslang::EOpConstructI16Vec3:
1854 case glslang::EOpConstructI16Vec4:
1855 case glslang::EOpConstructUint16:
1856 case glslang::EOpConstructU16Vec2:
1857 case glslang::EOpConstructU16Vec3:
1858 case glslang::EOpConstructU16Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001859 case glslang::EOpConstructInt:
1860 case glslang::EOpConstructIVec2:
1861 case glslang::EOpConstructIVec3:
1862 case glslang::EOpConstructIVec4:
1863 case glslang::EOpConstructUint:
1864 case glslang::EOpConstructUVec2:
1865 case glslang::EOpConstructUVec3:
1866 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001867 case glslang::EOpConstructInt64:
1868 case glslang::EOpConstructI64Vec2:
1869 case glslang::EOpConstructI64Vec3:
1870 case glslang::EOpConstructI64Vec4:
1871 case glslang::EOpConstructUint64:
1872 case glslang::EOpConstructU64Vec2:
1873 case glslang::EOpConstructU64Vec3:
1874 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001875 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001876 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001877 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001878 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001879 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001880 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001881 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001882 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001883 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001884 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001885 std::vector<spv::Id> constituents;
1886 for (int c = 0; c < (int)arguments.size(); ++c)
1887 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001888 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001889 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001890 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001891 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001892 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001893
1894 builder.clearAccessChain();
1895 builder.setAccessChainRValue(constructed);
1896
1897 return false;
1898 }
1899
1900 // These six are component-wise compares with component-wise results.
1901 // Forward on to createBinaryOperation(), requesting a vector result.
1902 case glslang::EOpLessThan:
1903 case glslang::EOpGreaterThan:
1904 case glslang::EOpLessThanEqual:
1905 case glslang::EOpGreaterThanEqual:
1906 case glslang::EOpVectorEqual:
1907 case glslang::EOpVectorNotEqual:
1908 {
1909 // Map the operation to a binary
1910 binOp = node->getOp();
1911 reduceComparison = false;
1912 switch (node->getOp()) {
1913 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1914 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1915 default: binOp = node->getOp(); break;
1916 }
1917
1918 break;
1919 }
1920 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001921 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001922 binOp = glslang::EOpMul;
1923 break;
1924 case glslang::EOpOuterProduct:
1925 // two vectors multiplied to make a matrix
1926 binOp = glslang::EOpOuterProduct;
1927 break;
1928 case glslang::EOpDot:
1929 {
qining25262b32016-05-06 17:25:16 -04001930 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001931 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001932 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001933 binOp = glslang::EOpMul;
1934 break;
1935 }
1936 case glslang::EOpMod:
1937 // when an aggregate, this is the floating-point mod built-in function,
1938 // which can be emitted by the one in createBinaryOperation()
1939 binOp = glslang::EOpMod;
1940 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001941 case glslang::EOpEmitVertex:
1942 case glslang::EOpEndPrimitive:
1943 case glslang::EOpBarrier:
1944 case glslang::EOpMemoryBarrier:
1945 case glslang::EOpMemoryBarrierAtomicCounter:
1946 case glslang::EOpMemoryBarrierBuffer:
1947 case glslang::EOpMemoryBarrierImage:
1948 case glslang::EOpMemoryBarrierShared:
1949 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07001950 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001951 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07001952 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001953 case glslang::EOpWorkgroupMemoryBarrier:
1954 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich66011cb2018-03-06 16:12:04 -07001955 case glslang::EOpSubgroupBarrier:
1956 case glslang::EOpSubgroupMemoryBarrier:
1957 case glslang::EOpSubgroupMemoryBarrierBuffer:
1958 case glslang::EOpSubgroupMemoryBarrierImage:
1959 case glslang::EOpSubgroupMemoryBarrierShared:
John Kessenich140f3df2015-06-26 16:58:36 -06001960 noReturnValue = true;
1961 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1962 break;
1963
John Kessenich426394d2015-07-23 10:22:48 -06001964 case glslang::EOpAtomicAdd:
1965 case glslang::EOpAtomicMin:
1966 case glslang::EOpAtomicMax:
1967 case glslang::EOpAtomicAnd:
1968 case glslang::EOpAtomicOr:
1969 case glslang::EOpAtomicXor:
1970 case glslang::EOpAtomicExchange:
1971 case glslang::EOpAtomicCompSwap:
1972 atomic = true;
1973 break;
1974
John Kessenich0d0c6d32017-07-23 16:08:26 -06001975 case glslang::EOpAtomicCounterAdd:
1976 case glslang::EOpAtomicCounterSubtract:
1977 case glslang::EOpAtomicCounterMin:
1978 case glslang::EOpAtomicCounterMax:
1979 case glslang::EOpAtomicCounterAnd:
1980 case glslang::EOpAtomicCounterOr:
1981 case glslang::EOpAtomicCounterXor:
1982 case glslang::EOpAtomicCounterExchange:
1983 case glslang::EOpAtomicCounterCompSwap:
1984 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1985 builder.addCapability(spv::CapabilityAtomicStorageOps);
1986 atomic = true;
1987 break;
1988
John Kessenich140f3df2015-06-26 16:58:36 -06001989 default:
1990 break;
1991 }
1992
1993 //
1994 // See if it maps to a regular operation.
1995 //
John Kessenich140f3df2015-06-26 16:58:36 -06001996 if (binOp != glslang::EOpNull) {
1997 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1998 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1999 assert(left && right);
2000
2001 builder.clearAccessChain();
2002 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002003 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002004
2005 builder.clearAccessChain();
2006 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002007 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002008
John Kesseniche485c7a2017-05-31 18:50:53 -06002009 builder.setLine(node->getLoc().line);
John Kessenichead86222018-03-28 18:01:20 -06002010 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002011 TranslateNoContractionDecoration(node->getType().getQualifier()),
2012 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002013 result = createBinaryOperation(binOp, decorations,
John Kessenich8c8505c2016-07-26 12:50:38 -06002014 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06002015 left->getType().getBasicType(), reduceComparison);
2016
2017 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07002018 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002019 builder.clearAccessChain();
2020 builder.setAccessChainRValue(result);
2021
2022 return false;
2023 }
2024
John Kessenich426394d2015-07-23 10:22:48 -06002025 //
2026 // Create the list of operands.
2027 //
John Kessenich140f3df2015-06-26 16:58:36 -06002028 glslang::TIntermSequence& glslangOperands = node->getSequence();
2029 std::vector<spv::Id> operands;
2030 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06002031 // special case l-value operands; there are just a few
2032 bool lvalue = false;
2033 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07002034 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06002035 case glslang::EOpModf:
2036 if (arg == 1)
2037 lvalue = true;
2038 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002039 case glslang::EOpInterpolateAtSample:
2040 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08002041#ifdef AMD_EXTENSIONS
2042 case glslang::EOpInterpolateAtVertex:
2043#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06002044 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08002045 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06002046
2047 // Does it need a swizzle inversion? If so, evaluation is inverted;
2048 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07002049 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002050 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2051 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
2052 }
Rex Xu7a26c172015-12-08 17:12:09 +08002053 break;
Rex Xud4782c12015-09-06 16:30:11 +08002054 case glslang::EOpAtomicAdd:
2055 case glslang::EOpAtomicMin:
2056 case glslang::EOpAtomicMax:
2057 case glslang::EOpAtomicAnd:
2058 case glslang::EOpAtomicOr:
2059 case glslang::EOpAtomicXor:
2060 case glslang::EOpAtomicExchange:
2061 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06002062 case glslang::EOpAtomicCounterAdd:
2063 case glslang::EOpAtomicCounterSubtract:
2064 case glslang::EOpAtomicCounterMin:
2065 case glslang::EOpAtomicCounterMax:
2066 case glslang::EOpAtomicCounterAnd:
2067 case glslang::EOpAtomicCounterOr:
2068 case glslang::EOpAtomicCounterXor:
2069 case glslang::EOpAtomicCounterExchange:
2070 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08002071 if (arg == 0)
2072 lvalue = true;
2073 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002074 case glslang::EOpAddCarry:
2075 case glslang::EOpSubBorrow:
2076 if (arg == 2)
2077 lvalue = true;
2078 break;
2079 case glslang::EOpUMulExtended:
2080 case glslang::EOpIMulExtended:
2081 if (arg >= 2)
2082 lvalue = true;
2083 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002084 default:
2085 break;
2086 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002087 builder.clearAccessChain();
2088 if (invertedType != spv::NoType && arg == 0)
2089 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
2090 else
2091 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06002092 if (lvalue)
2093 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06002094 else {
2095 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07002096 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06002097 }
John Kessenich140f3df2015-06-26 16:58:36 -06002098 }
John Kessenich426394d2015-07-23 10:22:48 -06002099
John Kesseniche485c7a2017-05-31 18:50:53 -06002100 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06002101 if (atomic) {
2102 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06002103 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002104 } else {
2105 // Pass through to generic operations.
2106 switch (glslangOperands.size()) {
2107 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06002108 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06002109 break;
2110 case 1:
John Kessenichead86222018-03-28 18:01:20 -06002111 {
2112 OpDecorations decorations = { precision,
John Kessenich5611c6d2018-04-05 11:25:02 -06002113 TranslateNoContractionDecoration(node->getType().getQualifier()),
2114 TranslateNonUniformDecoration(node->getType().getQualifier()) };
John Kessenichead86222018-03-28 18:01:20 -06002115 result = createUnaryOperation(
2116 node->getOp(), decorations,
2117 resultType(), operands.front(),
2118 glslangOperands[0]->getAsTyped()->getBasicType());
2119 }
John Kessenich426394d2015-07-23 10:22:48 -06002120 break;
2121 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06002122 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06002123 break;
2124 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002125 if (invertedType)
2126 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002127 }
2128
2129 if (noReturnValue)
2130 return false;
2131
2132 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04002133 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07002134 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06002135 } else {
2136 builder.clearAccessChain();
2137 builder.setAccessChainRValue(result);
2138 return false;
2139 }
2140}
2141
John Kessenich433e9ff2017-01-26 20:31:11 -07002142// This path handles both if-then-else and ?:
2143// The if-then-else has a node type of void, while
2144// ?: has either a void or a non-void node type
2145//
2146// Leaving the result, when not void:
2147// GLSL only has r-values as the result of a :?, but
2148// if we have an l-value, that can be more efficient if it will
2149// become the base of a complex r-value expression, because the
2150// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06002151bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
2152{
John Kessenich4bee5312018-02-20 21:29:05 -07002153 // See if it simple and safe, or required, to execute both sides.
2154 // Crucially, side effects must be either semantically required or avoided,
2155 // and there are performance trade-offs.
2156 // Return true if required or a good idea (and safe) to execute both sides,
2157 // false otherwise.
2158 const auto bothSidesPolicy = [&]() -> bool {
2159 // do we have both sides?
John Kessenich433e9ff2017-01-26 20:31:11 -07002160 if (node->getTrueBlock() == nullptr ||
2161 node->getFalseBlock() == nullptr)
2162 return false;
2163
John Kessenich4bee5312018-02-20 21:29:05 -07002164 // required? (unless we write additional code to look for side effects
2165 // and make performance trade-offs if none are present)
2166 if (!node->getShortCircuit())
2167 return true;
2168
2169 // if not required to execute both, decide based on performance/practicality...
2170
2171 // see if OpSelect can handle it
2172 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
2173 node->getBasicType() == glslang::EbtVoid)
2174 return false;
2175
John Kessenich433e9ff2017-01-26 20:31:11 -07002176 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
2177 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
2178
2179 // return true if a single operand to ? : is okay for OpSelect
2180 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002181 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07002182 };
2183
2184 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
2185 operandOkay(node->getFalseBlock()->getAsTyped());
2186 };
2187
John Kessenich4bee5312018-02-20 21:29:05 -07002188 spv::Id result = spv::NoResult; // upcoming result selecting between trueValue and falseValue
2189 // emit the condition before doing anything with selection
2190 node->getCondition()->traverse(this);
2191 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2192
2193 // Find a way of executing both sides and selecting the right result.
2194 const auto executeBothSides = [&]() -> void {
2195 // execute both sides
John Kessenich433e9ff2017-01-26 20:31:11 -07002196 node->getTrueBlock()->traverse(this);
2197 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2198 node->getFalseBlock()->traverse(this);
2199 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2200
John Kesseniche485c7a2017-05-31 18:50:53 -06002201 builder.setLine(node->getLoc().line);
2202
John Kessenich4bee5312018-02-20 21:29:05 -07002203 // done if void
2204 if (node->getBasicType() == glslang::EbtVoid)
2205 return;
John Kesseniche434ad92017-03-30 10:09:28 -06002206
John Kessenich4bee5312018-02-20 21:29:05 -07002207 // emit code to select between trueValue and falseValue
2208
2209 // see if OpSelect can handle it
2210 if (node->getType().isScalar() || node->getType().isVector()) {
2211 // Emit OpSelect for this selection.
2212
2213 // smear condition to vector, if necessary (AST is always scalar)
2214 if (builder.isVector(trueValue))
2215 condition = builder.smearScalar(spv::NoPrecision, condition,
2216 builder.makeVectorType(builder.makeBoolType(),
2217 builder.getNumComponents(trueValue)));
2218
2219 // OpSelect
2220 result = builder.createTriOp(spv::OpSelect,
2221 convertGlslangToSpvType(node->getType()), condition,
2222 trueValue, falseValue);
2223
2224 builder.clearAccessChain();
2225 builder.setAccessChainRValue(result);
2226 } else {
2227 // We need control flow to select the result.
2228 // TODO: Once SPIR-V OpSelect allows arbitrary types, eliminate this path.
2229 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2230
2231 // Selection control:
2232 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2233
2234 // make an "if" based on the value created by the condition
2235 spv::Builder::If ifBuilder(condition, control, builder);
2236
2237 // emit the "then" statement
2238 builder.createStore(trueValue, result);
2239 ifBuilder.makeBeginElse();
2240 // emit the "else" statement
2241 builder.createStore(falseValue, result);
2242
2243 // finish off the control flow
2244 ifBuilder.makeEndIf();
2245
2246 builder.clearAccessChain();
2247 builder.setAccessChainLValue(result);
2248 }
John Kessenich433e9ff2017-01-26 20:31:11 -07002249 };
2250
John Kessenich4bee5312018-02-20 21:29:05 -07002251 // Execute the one side needed, as per the condition
2252 const auto executeOneSide = [&]() {
2253 // Always emit control flow.
2254 if (node->getBasicType() != glslang::EbtVoid)
2255 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
John Kessenich433e9ff2017-01-26 20:31:11 -07002256
John Kessenich4bee5312018-02-20 21:29:05 -07002257 // Selection control:
2258 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
2259
2260 // make an "if" based on the value created by the condition
2261 spv::Builder::If ifBuilder(condition, control, builder);
2262
2263 // emit the "then" statement
2264 if (node->getTrueBlock() != nullptr) {
2265 node->getTrueBlock()->traverse(this);
2266 if (result != spv::NoResult)
2267 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
2268 }
2269
2270 if (node->getFalseBlock() != nullptr) {
2271 ifBuilder.makeBeginElse();
2272 // emit the "else" statement
2273 node->getFalseBlock()->traverse(this);
2274 if (result != spv::NoResult)
2275 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
2276 }
2277
2278 // finish off the control flow
2279 ifBuilder.makeEndIf();
2280
2281 if (result != spv::NoResult) {
2282 builder.clearAccessChain();
2283 builder.setAccessChainLValue(result);
2284 }
2285 };
2286
2287 // Try for OpSelect (or a requirement to execute both sides)
2288 if (bothSidesPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002289 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2290 if (node->getType().getQualifier().isSpecConstant())
2291 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
John Kessenich4bee5312018-02-20 21:29:05 -07002292 executeBothSides();
2293 } else
2294 executeOneSide();
John Kessenich140f3df2015-06-26 16:58:36 -06002295
2296 return false;
2297}
2298
2299bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2300{
2301 // emit and get the condition before doing anything with switch
2302 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002303 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002304
Rex Xu57e65922017-07-04 23:23:40 +08002305 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002306 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002307
John Kessenich140f3df2015-06-26 16:58:36 -06002308 // browse the children to sort out code segments
2309 int defaultSegment = -1;
2310 std::vector<TIntermNode*> codeSegments;
2311 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2312 std::vector<int> caseValues;
2313 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2314 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2315 TIntermNode* child = *c;
2316 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002317 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002318 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002319 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002320 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2321 } else
2322 codeSegments.push_back(child);
2323 }
2324
qining25262b32016-05-06 17:25:16 -04002325 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002326 // statements between the last case and the end of the switch statement
2327 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2328 (int)codeSegments.size() == defaultSegment)
2329 codeSegments.push_back(nullptr);
2330
2331 // make the switch statement
2332 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002333 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002334
2335 // emit all the code in the segments
2336 breakForLoop.push(false);
2337 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2338 builder.nextSwitchSegment(segmentBlocks, s);
2339 if (codeSegments[s])
2340 codeSegments[s]->traverse(this);
2341 else
2342 builder.addSwitchBreak();
2343 }
2344 breakForLoop.pop();
2345
2346 builder.endSwitch(segmentBlocks);
2347
2348 return false;
2349}
2350
2351void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2352{
2353 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002354 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002355
2356 builder.clearAccessChain();
2357 builder.setAccessChainRValue(constant);
2358}
2359
2360bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2361{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002362 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002363 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002364
2365 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002366 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2367 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002368
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002369 // Spec requires back edges to target header blocks, and every header block
2370 // must dominate its merge block. Make a header block first to ensure these
2371 // conditions are met. By definition, it will contain OpLoopMerge, followed
2372 // by a block-ending branch. But we don't want to put any other body/test
2373 // instructions in it, since the body/test may have arbitrary instructions,
2374 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002375 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002376 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002377 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002378 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002379 spv::Block& test = builder.makeNewBlock();
2380 builder.createBranch(&test);
2381
2382 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002383 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002384 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002385 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2386
2387 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002388 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002389 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002390 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002391 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002392 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002393
2394 builder.setBuildPoint(&blocks.continue_target);
2395 if (node->getTerminal())
2396 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002397 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002398 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002399 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002400 builder.createBranch(&blocks.body);
2401
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002402 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002403 builder.setBuildPoint(&blocks.body);
2404 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002405 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002406 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002407 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002408
2409 builder.setBuildPoint(&blocks.continue_target);
2410 if (node->getTerminal())
2411 node->getTerminal()->traverse(this);
2412 if (node->getTest()) {
2413 node->getTest()->traverse(this);
2414 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002415 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002416 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002417 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002418 // TODO: unless there was a break/return/discard instruction
2419 // somewhere in the body, this is an infinite loop, so we should
2420 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002421 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002422 }
John Kessenich140f3df2015-06-26 16:58:36 -06002423 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002424 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002425 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002426 return false;
2427}
2428
2429bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2430{
2431 if (node->getExpression())
2432 node->getExpression()->traverse(this);
2433
John Kesseniche485c7a2017-05-31 18:50:53 -06002434 builder.setLine(node->getLoc().line);
2435
John Kessenich140f3df2015-06-26 16:58:36 -06002436 switch (node->getFlowOp()) {
2437 case glslang::EOpKill:
2438 builder.makeDiscard();
2439 break;
2440 case glslang::EOpBreak:
2441 if (breakForLoop.top())
2442 builder.createLoopExit();
2443 else
2444 builder.addSwitchBreak();
2445 break;
2446 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002447 builder.createLoopContinue();
2448 break;
2449 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002450 if (node->getExpression()) {
2451 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2452 spv::Id returnId = accessChainLoad(glslangReturnType);
2453 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2454 builder.clearAccessChain();
2455 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2456 builder.setAccessChainLValue(copyId);
2457 multiTypeStore(glslangReturnType, returnId);
2458 returnId = builder.createLoad(copyId);
2459 }
2460 builder.makeReturn(false, returnId);
2461 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002462 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002463
2464 builder.clearAccessChain();
2465 break;
2466
2467 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002468 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002469 break;
2470 }
2471
2472 return false;
2473}
2474
2475spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2476{
qining25262b32016-05-06 17:25:16 -04002477 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002478 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002479 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002480 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002481 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002482 }
2483
2484 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002485 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002486 spv::Id spvType = convertGlslangToSpvType(node->getType());
2487
Rex Xucabbb782017-03-24 13:41:14 +08002488 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2489 node->getType().containsBasicType(glslang::EbtInt16) ||
2490 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002491 if (contains16BitType) {
John Kessenich18310872018-05-14 22:08:53 -06002492 switch (storageClass) {
2493 case spv::StorageClassInput:
2494 case spv::StorageClassOutput:
John Kessenich66011cb2018-03-06 16:12:04 -07002495 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002496 builder.addCapability(spv::CapabilityStorageInputOutput16);
John Kessenich18310872018-05-14 22:08:53 -06002497 break;
2498 case spv::StorageClassPushConstant:
John Kessenich66011cb2018-03-06 16:12:04 -07002499 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002500 builder.addCapability(spv::CapabilityStoragePushConstant16);
John Kessenich18310872018-05-14 22:08:53 -06002501 break;
2502 case spv::StorageClassUniform:
John Kessenich66011cb2018-03-06 16:12:04 -07002503 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
Rex Xuf89ad982017-04-07 23:22:33 +08002504 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2505 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
John Kessenich18310872018-05-14 22:08:53 -06002506 else
2507 builder.addCapability(spv::CapabilityStorageUniform16);
2508 break;
2509 case spv::StorageClassStorageBuffer:
2510 addPre13Extension(spv::E_SPV_KHR_16bit_storage);
2511 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2512 break;
2513 default:
2514 break;
Rex Xuf89ad982017-04-07 23:22:33 +08002515 }
2516 }
Rex Xuf89ad982017-04-07 23:22:33 +08002517
John Kessenich312dcfb2018-07-03 13:19:51 -06002518 const bool contains8BitType = node->getType().containsBasicType(glslang::EbtInt8) ||
2519 node->getType().containsBasicType(glslang::EbtUint8);
2520 if (contains8BitType) {
2521 if (storageClass == spv::StorageClassPushConstant) {
2522 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2523 builder.addCapability(spv::CapabilityStoragePushConstant8);
2524 } else if (storageClass == spv::StorageClassUniform) {
2525 builder.addExtension(spv::E_SPV_KHR_8bit_storage);
2526 builder.addCapability(spv::CapabilityUniformAndStorageBuffer8BitAccess);
2527 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2528 builder.addCapability(spv::CapabilityStorageBuffer8BitAccess);
2529 }
2530 }
2531
John Kessenich140f3df2015-06-26 16:58:36 -06002532 const char* name = node->getName().c_str();
2533 if (glslang::IsAnonymous(name))
2534 name = "";
2535
2536 return builder.createVariable(storageClass, spvType, name);
2537}
2538
2539// Return type Id of the sampled type.
2540spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2541{
2542 switch (sampler.type) {
2543 case glslang::EbtFloat: return builder.makeFloatType(32);
Rex Xu1e5d7b02016-11-29 17:36:31 +08002544#ifdef AMD_EXTENSIONS
2545 case glslang::EbtFloat16:
2546 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float_fetch);
2547 builder.addCapability(spv::CapabilityFloat16ImageAMD);
2548 return builder.makeFloatType(16);
2549#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002550 case glslang::EbtInt: return builder.makeIntType(32);
2551 case glslang::EbtUint: return builder.makeUintType(32);
2552 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002553 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002554 return builder.makeFloatType(32);
2555 }
2556}
2557
John Kessenich8c8505c2016-07-26 12:50:38 -06002558// If node is a swizzle operation, return the type that should be used if
2559// the swizzle base is first consumed by another operation, before the swizzle
2560// is applied.
2561spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2562{
John Kessenichecba76f2017-01-06 00:34:48 -07002563 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002564 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2565 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2566 else
2567 return spv::NoType;
2568}
2569
2570// When inverting a swizzle with a parent op, this function
2571// will apply the swizzle operation to a completed parent operation.
2572spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2573{
2574 std::vector<unsigned> swizzle;
2575 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2576 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2577}
2578
John Kessenich8c8505c2016-07-26 12:50:38 -06002579// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2580void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2581{
2582 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2583 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2584 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2585}
2586
John Kessenich3ac051e2015-12-20 11:29:16 -07002587// Convert from a glslang type to an SPV type, by calling into a
2588// recursive version of this function. This establishes the inherited
2589// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002590spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2591{
John Kessenichead86222018-03-28 18:01:20 -06002592 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier(), false);
John Kessenich31ed4832015-09-09 17:51:38 -06002593}
2594
2595// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002596// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002597// Mutually recursive with convertGlslangStructToSpvType().
John Kessenichead86222018-03-28 18:01:20 -06002598spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type,
2599 glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier, bool lastBufferBlockMember)
John Kessenich31ed4832015-09-09 17:51:38 -06002600{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002601 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002602
2603 switch (type.getBasicType()) {
2604 case glslang::EbtVoid:
2605 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002606 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002607 break;
2608 case glslang::EbtFloat:
2609 spvType = builder.makeFloatType(32);
2610 break;
2611 case glslang::EbtDouble:
2612 spvType = builder.makeFloatType(64);
2613 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002614 case glslang::EbtFloat16:
John Kessenich66011cb2018-03-06 16:12:04 -07002615#if AMD_EXTENSIONS
2616 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2617 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
2618#endif
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002619 spvType = builder.makeFloatType(16);
2620 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002621 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002622 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2623 // a 32-bit int where non-0 means true.
2624 if (explicitLayout != glslang::ElpNone)
2625 spvType = builder.makeUintType(32);
2626 else
2627 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002628 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002629 case glslang::EbtInt8:
John Kessenich66011cb2018-03-06 16:12:04 -07002630 spvType = builder.makeIntType(8);
2631 break;
2632 case glslang::EbtUint8:
John Kessenich66011cb2018-03-06 16:12:04 -07002633 spvType = builder.makeUintType(8);
2634 break;
John Kessenich31aa3d62018-08-15 13:54:09 -06002635 case glslang::EbtInt16:
John Kessenich66011cb2018-03-06 16:12:04 -07002636#ifdef AMD_EXTENSIONS
2637 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2638 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2639#endif
2640 spvType = builder.makeIntType(16);
2641 break;
2642 case glslang::EbtUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07002643#ifdef AMD_EXTENSIONS
2644 if (builder.getSpvVersion() < glslang::EShTargetSpv_1_3)
2645 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2646#endif
2647 spvType = builder.makeUintType(16);
2648 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002649 case glslang::EbtInt:
2650 spvType = builder.makeIntType(32);
2651 break;
2652 case glslang::EbtUint:
2653 spvType = builder.makeUintType(32);
2654 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002655 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002656 spvType = builder.makeIntType(64);
2657 break;
2658 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002659 spvType = builder.makeUintType(64);
2660 break;
John Kessenich426394d2015-07-23 10:22:48 -06002661 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002662 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002663 spvType = builder.makeUintType(32);
2664 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002665 case glslang::EbtSampler:
2666 {
2667 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002668 if (sampler.sampler) {
2669 // pure sampler
2670 spvType = builder.makeSamplerType();
2671 } else {
2672 // an image is present, make its type
2673 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2674 sampler.image ? 2 : 1, TranslateImageFormat(type));
2675 if (sampler.combined) {
2676 // already has both image and sampler, make the combined type
2677 spvType = builder.makeSampledImageType(spvType);
2678 }
John Kessenich55e7d112015-11-15 21:33:39 -07002679 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002680 }
John Kessenich140f3df2015-06-26 16:58:36 -06002681 break;
2682 case glslang::EbtStruct:
2683 case glslang::EbtBlock:
2684 {
2685 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002686 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002687
2688 // Try to share structs for different layouts, but not yet for other
2689 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002690 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002691 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002692 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002693 break;
2694
2695 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002696 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002697 memberRemapper[glslangMembers].resize(glslangMembers->size());
2698 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002699 }
2700 break;
2701 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002702 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002703 break;
2704 }
2705
2706 if (type.isMatrix())
2707 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2708 else {
2709 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2710 if (type.getVectorSize() > 1)
2711 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2712 }
2713
2714 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002715 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2716
John Kessenichc9a80832015-09-12 12:17:44 -06002717 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002718 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002719 // We need to decorate array strides for types needing explicit layout, except blocks.
2720 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002721 // Use a dummy glslang type for querying internal strides of
2722 // arrays of arrays, but using just a one-dimensional array.
2723 glslang::TType simpleArrayType(type, 0); // deference type of the array
John Kessenich859b0342018-03-26 00:38:53 -06002724 while (simpleArrayType.getArraySizes()->getNumDims() > 1)
2725 simpleArrayType.getArraySizes()->dereference();
John Kessenichc9e0a422015-12-29 21:27:24 -07002726
2727 // Will compute the higher-order strides here, rather than making a whole
2728 // pile of types and doing repetitive recursion on their contents.
2729 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2730 }
John Kessenichf8842e52016-01-04 19:22:56 -07002731
2732 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002733 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002734 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002735 if (stride > 0)
2736 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002737 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002738 }
2739 } else {
2740 // single-dimensional array, and don't yet have stride
2741
John Kessenichf8842e52016-01-04 19:22:56 -07002742 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002743 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2744 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002745 }
John Kessenich31ed4832015-09-09 17:51:38 -06002746
John Kessenichead86222018-03-28 18:01:20 -06002747 // Do the outer dimension, which might not be known for a runtime-sized array.
2748 // (Unsized arrays that survive through linking will be runtime-sized arrays)
2749 if (type.isSizedArray())
John Kessenich6c292d32016-02-15 20:58:50 -07002750 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenich5611c6d2018-04-05 11:25:02 -06002751 else {
2752 if (!lastBufferBlockMember) {
2753 builder.addExtension("SPV_EXT_descriptor_indexing");
2754 builder.addCapability(spv::CapabilityRuntimeDescriptorArrayEXT);
2755 }
John Kessenichead86222018-03-28 18:01:20 -06002756 spvType = builder.makeRuntimeArray(spvType);
John Kessenich5611c6d2018-04-05 11:25:02 -06002757 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002758 if (stride > 0)
2759 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002760 }
2761
2762 return spvType;
2763}
2764
John Kessenich0e737842017-03-24 18:38:16 -06002765// TODO: this functionality should exist at a higher level, in creating the AST
2766//
2767// Identify interface members that don't have their required extension turned on.
2768//
2769bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2770{
2771 auto& extensions = glslangIntermediate->getRequestedExtensions();
2772
Rex Xubcf291a2017-03-29 23:01:36 +08002773 if (member.getFieldName() == "gl_ViewportMask" &&
2774 extensions.find("GL_NV_viewport_array2") == extensions.end())
2775 return true;
2776 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2777 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2778 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002779 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2780 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2781 return true;
2782 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2783 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2784 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002785 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2786 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2787 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002788
2789 return false;
2790};
2791
John Kessenich6090df02016-06-30 21:18:02 -06002792// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2793// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2794// Mutually recursive with convertGlslangToSpvType().
2795spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2796 const glslang::TTypeList* glslangMembers,
2797 glslang::TLayoutPacking explicitLayout,
2798 const glslang::TQualifier& qualifier)
2799{
2800 // Create a vector of struct types for SPIR-V to consume
2801 std::vector<spv::Id> spvMembers;
2802 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 -06002803 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2804 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2805 if (glslangMember.hiddenMember()) {
2806 ++memberDelta;
2807 if (type.getBasicType() == glslang::EbtBlock)
2808 memberRemapper[glslangMembers][i] = -1;
2809 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002810 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002811 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002812 if (filterMember(glslangMember))
2813 continue;
2814 }
John Kessenich6090df02016-06-30 21:18:02 -06002815 // modify just this child's view of the qualifier
2816 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2817 InheritQualifiers(memberQualifier, qualifier);
2818
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002819 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002820 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002821 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002822
2823 // recurse
John Kessenichead86222018-03-28 18:01:20 -06002824 bool lastBufferBlockMember = qualifier.storage == glslang::EvqBuffer &&
2825 i == (int)glslangMembers->size() - 1;
2826 spvMembers.push_back(
2827 convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier, lastBufferBlockMember));
John Kessenich6090df02016-06-30 21:18:02 -06002828 }
2829 }
2830
2831 // Make the SPIR-V type
2832 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002833 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002834 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2835
2836 // Decorate it
2837 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2838
2839 return spvType;
2840}
2841
2842void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2843 const glslang::TTypeList* glslangMembers,
2844 glslang::TLayoutPacking explicitLayout,
2845 const glslang::TQualifier& qualifier,
2846 spv::Id spvType)
2847{
2848 // Name and decorate the non-hidden members
2849 int offset = -1;
2850 int locationOffset = 0; // for use within the members of this struct
2851 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2852 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2853 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002854 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002855 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002856 if (filterMember(glslangMember))
2857 continue;
2858 }
John Kessenich6090df02016-06-30 21:18:02 -06002859
2860 // modify just this child's view of the qualifier
2861 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2862 InheritQualifiers(memberQualifier, qualifier);
2863
2864 // using -1 above to indicate a hidden member
John Kessenich5d610ee2018-03-07 18:05:55 -07002865 if (member < 0)
2866 continue;
2867
2868 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2869 builder.addMemberDecoration(spvType, member,
2870 TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2871 builder.addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2872 // Add interpolation and auxiliary storage decorations only to
2873 // top-level members of Input and Output storage classes
2874 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2875 type.getQualifier().storage == glslang::EvqVaryingOut) {
2876 if (type.getBasicType() == glslang::EbtBlock ||
2877 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
2878 builder.addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2879 builder.addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002880 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002881 }
2882 builder.addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
John Kessenich6090df02016-06-30 21:18:02 -06002883
John Kessenich5d610ee2018-03-07 18:05:55 -07002884 if (type.getBasicType() == glslang::EbtBlock &&
2885 qualifier.storage == glslang::EvqBuffer) {
2886 // Add memory decorations only to top-level members of shader storage block
2887 std::vector<spv::Decoration> memory;
2888 TranslateMemoryDecoration(memberQualifier, memory);
2889 for (unsigned int i = 0; i < memory.size(); ++i)
2890 builder.addMemberDecoration(spvType, member, memory[i]);
2891 }
John Kessenich6090df02016-06-30 21:18:02 -06002892
John Kessenich5d610ee2018-03-07 18:05:55 -07002893 // Location assignment was already completed correctly by the front end,
2894 // just track whether a member needs to be decorated.
2895 // Ignore member locations if the container is an array, as that's
2896 // ill-specified and decisions have been made to not allow this.
2897 if (! type.isArray() && memberQualifier.hasLocation())
2898 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002899
John Kessenich5d610ee2018-03-07 18:05:55 -07002900 if (qualifier.hasLocation()) // track for upcoming inheritance
2901 locationOffset += glslangIntermediate->computeTypeLocationSize(
2902 glslangMember, glslangIntermediate->getStage());
John Kessenich2f47bc92016-06-30 21:47:35 -06002903
John Kessenich5d610ee2018-03-07 18:05:55 -07002904 // component, XFB, others
2905 if (glslangMember.getQualifier().hasComponent())
2906 builder.addMemberDecoration(spvType, member, spv::DecorationComponent,
2907 glslangMember.getQualifier().layoutComponent);
2908 if (glslangMember.getQualifier().hasXfbOffset())
2909 builder.addMemberDecoration(spvType, member, spv::DecorationOffset,
2910 glslangMember.getQualifier().layoutXfbOffset);
2911 else if (explicitLayout != glslang::ElpNone) {
2912 // figure out what to do with offset, which is accumulating
2913 int nextOffset;
2914 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2915 if (offset >= 0)
2916 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2917 offset = nextOffset;
2918 }
John Kessenich6090df02016-06-30 21:18:02 -06002919
John Kessenich5d610ee2018-03-07 18:05:55 -07002920 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2921 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride,
2922 getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
John Kessenich6090df02016-06-30 21:18:02 -06002923
John Kessenich5d610ee2018-03-07 18:05:55 -07002924 // built-in variable decorations
2925 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
2926 if (builtIn != spv::BuiltInMax)
2927 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002928
John Kessenich5611c6d2018-04-05 11:25:02 -06002929 // nonuniform
2930 builder.addMemberDecoration(spvType, member, TranslateNonUniformDecoration(glslangMember.getQualifier()));
2931
John Kessenichead86222018-03-28 18:01:20 -06002932 if (glslangIntermediate->getHlslFunctionality1() && memberQualifier.semanticName != nullptr) {
2933 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
2934 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
2935 memberQualifier.semanticName);
2936 }
2937
chaoc771d89f2017-01-13 01:10:53 -08002938#ifdef NV_EXTENSIONS
John Kessenich5d610ee2018-03-07 18:05:55 -07002939 if (builtIn == spv::BuiltInLayer) {
2940 // SPV_NV_viewport_array2 extension
2941 if (glslangMember.getQualifier().layoutViewportRelative){
2942 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2943 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2944 builder.addExtension(spv::E_SPV_NV_viewport_array2);
chaoc771d89f2017-01-13 01:10:53 -08002945 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002946 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2947 builder.addMemberDecoration(spvType, member,
2948 (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
2949 glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2950 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2951 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
chaocdf3956c2017-02-14 14:52:34 -08002952 }
John Kessenich5d610ee2018-03-07 18:05:55 -07002953 }
2954 if (glslangMember.getQualifier().layoutPassthrough) {
2955 builder.addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2956 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2957 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2958 }
chaoc771d89f2017-01-13 01:10:53 -08002959#endif
John Kessenich6090df02016-06-30 21:18:02 -06002960 }
2961
2962 // Decorate the structure
John Kessenich5d610ee2018-03-07 18:05:55 -07002963 builder.addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2964 builder.addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002965 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2966 builder.addCapability(spv::CapabilityGeometryStreams);
2967 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2968 }
John Kessenich6090df02016-06-30 21:18:02 -06002969}
2970
John Kessenich6c292d32016-02-15 20:58:50 -07002971// Turn the expression forming the array size into an id.
2972// This is not quite trivial, because of specialization constants.
2973// Sometimes, a raw constant is turned into an Id, and sometimes
2974// a specialization constant expression is.
2975spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2976{
2977 // First, see if this is sized with a node, meaning a specialization constant:
2978 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2979 if (specNode != nullptr) {
2980 builder.clearAccessChain();
2981 specNode->traverse(this);
2982 return accessChainLoad(specNode->getAsTyped()->getType());
2983 }
qining25262b32016-05-06 17:25:16 -04002984
John Kessenich6c292d32016-02-15 20:58:50 -07002985 // Otherwise, need a compile-time (front end) size, get it:
2986 int size = arraySizes.getDimSize(dim);
2987 assert(size > 0);
2988 return builder.makeUintConstant(size);
2989}
2990
John Kessenich103bef92016-02-08 21:38:15 -07002991// Wrap the builder's accessChainLoad to:
2992// - localize handling of RelaxedPrecision
2993// - use the SPIR-V inferred type instead of another conversion of the glslang type
2994// (avoids unnecessary work and possible type punning for structures)
2995// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002996spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2997{
John Kessenich103bef92016-02-08 21:38:15 -07002998 spv::Id nominalTypeId = builder.accessChainGetInferredType();
John Kessenich5611c6d2018-04-05 11:25:02 -06002999 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type),
3000 TranslateNonUniformDecoration(type.getQualifier()), nominalTypeId);
John Kessenich103bef92016-02-08 21:38:15 -07003001
3002 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08003003 if (type.getBasicType() == glslang::EbtBool) {
3004 if (builder.isScalarType(nominalTypeId)) {
3005 // Conversion for bool
3006 spv::Id boolType = builder.makeBoolType();
3007 if (nominalTypeId != boolType)
3008 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
3009 } else if (builder.isVectorType(nominalTypeId)) {
3010 // Conversion for bvec
3011 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3012 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
3013 if (nominalTypeId != bvecType)
3014 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
3015 }
3016 }
John Kessenich103bef92016-02-08 21:38:15 -07003017
3018 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07003019}
3020
Rex Xu27253232016-02-23 17:51:09 +08003021// Wrap the builder's accessChainStore to:
3022// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06003023//
3024// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08003025void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
3026{
3027 // Need to convert to abstract types when necessary
3028 if (type.getBasicType() == glslang::EbtBool) {
3029 spv::Id nominalTypeId = builder.accessChainGetInferredType();
3030
3031 if (builder.isScalarType(nominalTypeId)) {
3032 // Conversion for bool
3033 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06003034 if (nominalTypeId != boolType) {
3035 // keep these outside arguments, for determinant order-of-evaluation
3036 spv::Id one = builder.makeUintConstant(1);
3037 spv::Id zero = builder.makeUintConstant(0);
3038 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
3039 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06003040 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08003041 } else if (builder.isVectorType(nominalTypeId)) {
3042 // Conversion for bvec
3043 int vecSize = builder.getNumTypeComponents(nominalTypeId);
3044 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06003045 if (nominalTypeId != bvecType) {
3046 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06003047 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
3048 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
3049 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06003050 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06003051 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
3052 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08003053 }
3054 }
3055
3056 builder.accessChainStore(rvalue);
3057}
3058
John Kessenich4bf71552016-09-02 11:20:21 -06003059// For storing when types match at the glslang level, but not might match at the
3060// SPIR-V level.
3061//
3062// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06003063// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06003064// as in a member-decorated way.
3065//
3066// NOTE: This function can handle any store request; if it's not special it
3067// simplifies to a simple OpStore.
3068//
3069// Implicitly uses the existing builder.accessChain as the storage target.
3070void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
3071{
John Kessenichb3e24e42016-09-11 12:33:43 -06003072 // we only do the complex path here if it's an aggregate
3073 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06003074 accessChainStore(type, rValue);
3075 return;
3076 }
3077
John Kessenichb3e24e42016-09-11 12:33:43 -06003078 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06003079 spv::Id rType = builder.getTypeId(rValue);
3080 spv::Id lValue = builder.accessChainGetLValue();
3081 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
3082 if (lType == rType) {
3083 accessChainStore(type, rValue);
3084 return;
3085 }
3086
John Kessenichb3e24e42016-09-11 12:33:43 -06003087 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06003088 // where the two types were the same type in GLSL. This requires member
3089 // by member copy, recursively.
3090
John Kessenichb3e24e42016-09-11 12:33:43 -06003091 // If an array, copy element by element.
3092 if (type.isArray()) {
3093 glslang::TType glslangElementType(type, 0);
3094 spv::Id elementRType = builder.getContainedTypeId(rType);
3095 for (int index = 0; index < type.getOuterArraySize(); ++index) {
3096 // get the source member
3097 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06003098
John Kessenichb3e24e42016-09-11 12:33:43 -06003099 // set up the target storage
3100 builder.clearAccessChain();
3101 builder.setAccessChainLValue(lValue);
3102 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06003103
John Kessenichb3e24e42016-09-11 12:33:43 -06003104 // store the member
3105 multiTypeStore(glslangElementType, elementRValue);
3106 }
3107 } else {
3108 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06003109
John Kessenichb3e24e42016-09-11 12:33:43 -06003110 // loop over structure members
3111 const glslang::TTypeList& members = *type.getStruct();
3112 for (int m = 0; m < (int)members.size(); ++m) {
3113 const glslang::TType& glslangMemberType = *members[m].type;
3114
3115 // get the source member
3116 spv::Id memberRType = builder.getContainedTypeId(rType, m);
3117 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
3118
3119 // set up the target storage
3120 builder.clearAccessChain();
3121 builder.setAccessChainLValue(lValue);
3122 builder.accessChainPush(builder.makeIntConstant(m));
3123
3124 // store the member
3125 multiTypeStore(glslangMemberType, memberRValue);
3126 }
John Kessenich4bf71552016-09-02 11:20:21 -06003127 }
3128}
3129
John Kessenichf85e8062015-12-19 13:57:10 -07003130// Decide whether or not this type should be
3131// decorated with offsets and strides, and if so
3132// whether std140 or std430 rules should be applied.
3133glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06003134{
John Kessenichf85e8062015-12-19 13:57:10 -07003135 // has to be a block
3136 if (type.getBasicType() != glslang::EbtBlock)
3137 return glslang::ElpNone;
3138
3139 // has to be a uniform or buffer block
3140 if (type.getQualifier().storage != glslang::EvqUniform &&
3141 type.getQualifier().storage != glslang::EvqBuffer)
3142 return glslang::ElpNone;
3143
3144 // return the layout to use
3145 switch (type.getQualifier().layoutPacking) {
3146 case glslang::ElpStd140:
3147 case glslang::ElpStd430:
3148 return type.getQualifier().layoutPacking;
3149 default:
3150 return glslang::ElpNone;
3151 }
John Kessenich31ed4832015-09-09 17:51:38 -06003152}
3153
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003154// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07003155int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003156{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003157 int size;
John Kessenich49987892015-12-29 17:11:44 -07003158 int stride;
3159 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07003160
3161 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003162}
3163
John Kessenich49987892015-12-29 17:11:44 -07003164// 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 -07003165// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07003166int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003167{
John Kessenich49987892015-12-29 17:11:44 -07003168 glslang::TType elementType;
3169 elementType.shallowCopy(matrixType);
3170 elementType.clearArraySizes();
3171
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003172 int size;
John Kessenich49987892015-12-29 17:11:44 -07003173 int stride;
3174 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
3175
3176 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07003177}
3178
John Kessenich5e4b1242015-08-06 22:53:06 -06003179// Given a member type of a struct, realign the current offset for it, and compute
3180// the next (not yet aligned) offset for the next member, which will get aligned
3181// on the next call.
3182// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
3183// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
3184// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06003185void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07003186 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06003187{
3188 // this will get a positive value when deemed necessary
3189 nextOffset = -1;
3190
John Kessenich5e4b1242015-08-06 22:53:06 -06003191 // override anything in currentOffset with user-set offset
3192 if (memberType.getQualifier().hasOffset())
3193 currentOffset = memberType.getQualifier().layoutOffset;
3194
3195 // It could be that current linker usage in glslang updated all the layoutOffset,
3196 // in which case the following code does not matter. But, that's not quite right
3197 // once cross-compilation unit GLSL validation is done, as the original user
3198 // settings are needed in layoutOffset, and then the following will come into play.
3199
John Kessenichf85e8062015-12-19 13:57:10 -07003200 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06003201 if (! memberType.getQualifier().hasOffset())
3202 currentOffset = -1;
3203
3204 return;
3205 }
3206
John Kessenichf85e8062015-12-19 13:57:10 -07003207 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06003208 if (currentOffset < 0)
3209 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04003210
John Kessenich5e4b1242015-08-06 22:53:06 -06003211 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
3212 // but possibly not yet correctly aligned.
3213
3214 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07003215 int dummyStride;
3216 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06003217
3218 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06003219 // TODO: make this consistent in early phases of code:
3220 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
3221 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
3222 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06003223 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06003224 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06003225 int dummySize;
3226 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
3227 if (componentAlignment <= 4)
3228 memberAlignment = componentAlignment;
3229 }
3230
3231 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06003232 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06003233
3234 // Bump up to vec4 if there is a bad straddle
3235 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
3236 glslang::RoundToPow2(currentOffset, 16);
3237
John Kessenich5e4b1242015-08-06 22:53:06 -06003238 nextOffset = currentOffset + memberSize;
3239}
3240
David Netoa901ffe2016-06-08 14:11:40 +01003241void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06003242{
David Netoa901ffe2016-06-08 14:11:40 +01003243 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
3244 switch (glslangBuiltIn)
3245 {
3246 case glslang::EbvClipDistance:
3247 case glslang::EbvCullDistance:
3248 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08003249#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08003250 case glslang::EbvViewportMaskNV:
3251 case glslang::EbvSecondaryPositionNV:
3252 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08003253 case glslang::EbvPositionPerViewNV:
3254 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08003255#endif
David Netoa901ffe2016-06-08 14:11:40 +01003256 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
3257 // Alternately, we could just call this for any glslang built-in, since the
3258 // capability already guards against duplicates.
3259 TranslateBuiltInDecoration(glslangBuiltIn, false);
3260 break;
3261 default:
3262 // Capabilities were already generated when the struct was declared.
3263 break;
3264 }
John Kessenichebb50532016-05-16 19:22:05 -06003265}
3266
John Kessenich6fccb3c2016-09-19 16:01:41 -06003267bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06003268{
John Kessenicheee9d532016-09-19 18:09:30 -06003269 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003270}
3271
John Kessenichd41993d2017-09-10 15:21:05 -06003272// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07003273// Assumes called after originalParam(), which filters out block/buffer/opaque-based
3274// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd3ed90b2018-05-04 11:43:03 -06003275bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier) const
John Kessenichd41993d2017-09-10 15:21:05 -06003276{
John Kessenich6a14f782017-12-04 02:48:10 -07003277 assert(qualifier == glslang::EvqIn ||
3278 qualifier == glslang::EvqOut ||
3279 qualifier == glslang::EvqInOut ||
3280 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06003281 return qualifier != glslang::EvqConstReadOnly;
3282}
3283
3284// Is parameter pass-by-original?
3285bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3286 bool implicitThisParam)
3287{
3288 if (implicitThisParam) // implicit this
3289 return true;
3290 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003291 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003292 return paramType.containsOpaque() || // sampler, etc.
3293 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3294}
3295
John Kessenich140f3df2015-06-26 16:58:36 -06003296// Make all the functions, skeletally, without actually visiting their bodies.
3297void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3298{
John Kessenichfad62972017-07-18 02:35:46 -06003299 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
3300 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3301 if (paramPrecision != spv::NoPrecision)
3302 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06003303 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003304 };
3305
John Kessenich140f3df2015-06-26 16:58:36 -06003306 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3307 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003308 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003309 continue;
3310
3311 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003312 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003313 //
qining25262b32016-05-06 17:25:16 -04003314 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003315 // function. What it is an address of varies:
3316 //
John Kessenich4bf71552016-09-02 11:20:21 -06003317 // - "in" parameters not marked as "const" can be written to without modifying the calling
3318 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003319 //
3320 // - "const in" parameters can just be the r-value, as no writes need occur.
3321 //
John Kessenich4bf71552016-09-02 11:20:21 -06003322 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3323 // 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 -06003324
3325 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003326 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003327 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3328
John Kessenichfad62972017-07-18 02:35:46 -06003329 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3330 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003331
John Kessenichfad62972017-07-18 02:35:46 -06003332 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003333 for (int p = 0; p < (int)parameters.size(); ++p) {
3334 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3335 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003336 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003337 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003338 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003339 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3340 else
John Kessenich4bf71552016-09-02 11:20:21 -06003341 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003342 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003343 paramTypes.push_back(typeId);
3344 }
3345
3346 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003347 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3348 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003349 glslFunction->getName().c_str(), paramTypes,
3350 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003351 if (implicitThis)
3352 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003353
3354 // Track function to emit/call later
3355 functionMap[glslFunction->getName().c_str()] = function;
3356
3357 // Set the parameter id's
3358 for (int p = 0; p < (int)parameters.size(); ++p) {
3359 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3360 // give a name too
3361 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3362 }
3363 }
3364}
3365
3366// Process all the initializers, while skipping the functions and link objects
3367void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3368{
3369 builder.setBuildPoint(shaderEntry->getLastBlock());
3370 for (int i = 0; i < (int)initializers.size(); ++i) {
3371 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3372 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3373
3374 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003375 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003376 initializer->traverse(this);
3377 }
3378 }
3379}
3380
3381// Process all the functions, while skipping initializers.
3382void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3383{
3384 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3385 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003386 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003387 node->traverse(this);
3388 }
3389}
3390
3391void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3392{
qining25262b32016-05-06 17:25:16 -04003393 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003394 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003395 currentFunction = functionMap[node->getName().c_str()];
3396 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003397 builder.setBuildPoint(functionBlock);
3398}
3399
Rex Xu04db3f52015-09-16 11:44:02 +08003400void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003401{
Rex Xufc618912015-09-09 16:42:49 +08003402 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003403
3404 glslang::TSampler sampler = {};
3405 bool cubeCompare = false;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003406#ifdef AMD_EXTENSIONS
3407 bool f16ShadowCompare = false;
3408#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003409 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003410 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3411 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003412#ifdef AMD_EXTENSIONS
3413 f16ShadowCompare = sampler.shadow && glslangArguments[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16;
3414#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003415 }
3416
John Kessenich140f3df2015-06-26 16:58:36 -06003417 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3418 builder.clearAccessChain();
3419 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003420
3421 // Special case l-value operands
3422 bool lvalue = false;
3423 switch (node.getOp()) {
3424 case glslang::EOpImageAtomicAdd:
3425 case glslang::EOpImageAtomicMin:
3426 case glslang::EOpImageAtomicMax:
3427 case glslang::EOpImageAtomicAnd:
3428 case glslang::EOpImageAtomicOr:
3429 case glslang::EOpImageAtomicXor:
3430 case glslang::EOpImageAtomicExchange:
3431 case glslang::EOpImageAtomicCompSwap:
3432 if (i == 0)
3433 lvalue = true;
3434 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003435 case glslang::EOpSparseImageLoad:
3436 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3437 lvalue = true;
3438 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003439#ifdef AMD_EXTENSIONS
3440 case glslang::EOpSparseTexture:
3441 if (((cubeCompare || f16ShadowCompare) && i == 3) || (! (cubeCompare || f16ShadowCompare) && i == 2))
3442 lvalue = true;
3443 break;
3444 case glslang::EOpSparseTextureClamp:
3445 if (((cubeCompare || f16ShadowCompare) && i == 4) || (! (cubeCompare || f16ShadowCompare) && i == 3))
3446 lvalue = true;
3447 break;
3448 case glslang::EOpSparseTextureLod:
3449 case glslang::EOpSparseTextureOffset:
3450 if ((f16ShadowCompare && i == 4) || (! f16ShadowCompare && i == 3))
3451 lvalue = true;
3452 break;
3453#else
Rex Xu48edadf2015-12-31 16:11:41 +08003454 case glslang::EOpSparseTexture:
3455 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3456 lvalue = true;
3457 break;
3458 case glslang::EOpSparseTextureClamp:
3459 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3460 lvalue = true;
3461 break;
3462 case glslang::EOpSparseTextureLod:
3463 case glslang::EOpSparseTextureOffset:
3464 if (i == 3)
3465 lvalue = true;
3466 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003467#endif
Rex Xu48edadf2015-12-31 16:11:41 +08003468 case glslang::EOpSparseTextureFetch:
3469 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3470 lvalue = true;
3471 break;
3472 case glslang::EOpSparseTextureFetchOffset:
3473 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3474 lvalue = true;
3475 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003476#ifdef AMD_EXTENSIONS
3477 case glslang::EOpSparseTextureLodOffset:
3478 case glslang::EOpSparseTextureGrad:
3479 case glslang::EOpSparseTextureOffsetClamp:
3480 if ((f16ShadowCompare && i == 5) || (! f16ShadowCompare && i == 4))
3481 lvalue = true;
3482 break;
3483 case glslang::EOpSparseTextureGradOffset:
3484 case glslang::EOpSparseTextureGradClamp:
3485 if ((f16ShadowCompare && i == 6) || (! f16ShadowCompare && i == 5))
3486 lvalue = true;
3487 break;
3488 case glslang::EOpSparseTextureGradOffsetClamp:
3489 if ((f16ShadowCompare && i == 7) || (! f16ShadowCompare && i == 6))
3490 lvalue = true;
3491 break;
3492#else
Rex Xu48edadf2015-12-31 16:11:41 +08003493 case glslang::EOpSparseTextureLodOffset:
3494 case glslang::EOpSparseTextureGrad:
3495 case glslang::EOpSparseTextureOffsetClamp:
3496 if (i == 4)
3497 lvalue = true;
3498 break;
3499 case glslang::EOpSparseTextureGradOffset:
3500 case glslang::EOpSparseTextureGradClamp:
3501 if (i == 5)
3502 lvalue = true;
3503 break;
3504 case glslang::EOpSparseTextureGradOffsetClamp:
3505 if (i == 6)
3506 lvalue = true;
3507 break;
Rex Xu1e5d7b02016-11-29 17:36:31 +08003508#endif
Rex Xu225e0fc2016-11-17 17:47:59 +08003509 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003510 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3511 lvalue = true;
3512 break;
3513 case glslang::EOpSparseTextureGatherOffset:
3514 case glslang::EOpSparseTextureGatherOffsets:
3515 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3516 lvalue = true;
3517 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003518#ifdef AMD_EXTENSIONS
3519 case glslang::EOpSparseTextureGatherLod:
3520 if (i == 3)
3521 lvalue = true;
3522 break;
3523 case glslang::EOpSparseTextureGatherLodOffset:
3524 case glslang::EOpSparseTextureGatherLodOffsets:
3525 if (i == 4)
3526 lvalue = true;
3527 break;
Rex Xu129799a2017-07-05 17:23:28 +08003528 case glslang::EOpSparseImageLoadLod:
3529 if (i == 3)
3530 lvalue = true;
3531 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003532#endif
Rex Xufc618912015-09-09 16:42:49 +08003533 default:
3534 break;
3535 }
3536
Rex Xu6b86d492015-09-16 17:48:22 +08003537 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003538 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003539 else
John Kessenich32cfd492016-02-02 12:37:46 -07003540 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003541 }
3542}
3543
John Kessenichfc51d282015-08-19 13:34:18 -06003544void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003545{
John Kessenichfc51d282015-08-19 13:34:18 -06003546 builder.clearAccessChain();
3547 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003548 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003549}
John Kessenich140f3df2015-06-26 16:58:36 -06003550
John Kessenichfc51d282015-08-19 13:34:18 -06003551spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3552{
John Kesseniche485c7a2017-05-31 18:50:53 -06003553 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003554 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003555
3556 builder.setLine(node->getLoc().line);
3557
John Kessenichfc51d282015-08-19 13:34:18 -06003558 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003559 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3560 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
Rex Xu1e5d7b02016-11-29 17:36:31 +08003561#ifdef AMD_EXTENSIONS
3562 bool f16ShadowCompare = (sampler.shadow && node->getAsAggregate())
3563 ? node->getAsAggregate()->getSequence()[1]->getAsTyped()->getType().getBasicType() == glslang::EbtFloat16
3564 : false;
3565#endif
3566
John Kessenichfc51d282015-08-19 13:34:18 -06003567 std::vector<spv::Id> arguments;
3568 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003569 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003570 else
3571 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003572 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003573
3574 spv::Builder::TextureParameters params = { };
3575 params.sampler = arguments[0];
3576
Rex Xu04db3f52015-09-16 11:44:02 +08003577 glslang::TCrackedTextureOp cracked;
3578 node->crackTexture(sampler, cracked);
3579
amhagan05506bb2017-06-13 16:53:02 -04003580 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003581
John Kessenichfc51d282015-08-19 13:34:18 -06003582 // Check for queries
3583 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003584 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3585 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003586 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003587
John Kessenichfc51d282015-08-19 13:34:18 -06003588 switch (node->getOp()) {
3589 case glslang::EOpImageQuerySize:
3590 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003591 if (arguments.size() > 1) {
3592 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003593 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003594 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003595 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003596 case glslang::EOpImageQuerySamples:
3597 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003598 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003599 case glslang::EOpTextureQueryLod:
3600 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003601 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003602 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003603 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003604 case glslang::EOpSparseTexelsResident:
3605 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003606 default:
3607 assert(0);
3608 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003609 }
John Kessenich140f3df2015-06-26 16:58:36 -06003610 }
3611
LoopDawg4425f242018-02-18 11:40:01 -07003612 int components = node->getType().getVectorSize();
3613
3614 if (node->getOp() == glslang::EOpTextureFetch) {
3615 // These must produce 4 components, per SPIR-V spec. We'll add a conversion constructor if needed.
3616 // This will only happen through the HLSL path for operator[], so we do not have to handle e.g.
3617 // the EOpTexture/Proj/Lod/etc family. It would be harmless to do so, but would need more logic
3618 // here around e.g. which ones return scalars or other types.
3619 components = 4;
3620 }
3621
3622 glslang::TType returnType(node->getType().getBasicType(), glslang::EvqTemporary, components);
3623
3624 auto resultType = [&returnType,this]{ return convertGlslangToSpvType(returnType); };
3625
Rex Xufc618912015-09-09 16:42:49 +08003626 // Check for image functions other than queries
3627 if (node->isImage()) {
John Kessenich149afc32018-08-14 13:31:43 -06003628 std::vector<spv::IdImmediate> operands;
John Kessenich56bab042015-09-16 10:54:31 -06003629 auto opIt = arguments.begin();
John Kessenich149afc32018-08-14 13:31:43 -06003630 spv::IdImmediate image = { true, *(opIt++) };
3631 operands.push_back(image);
John Kessenich6c292d32016-02-15 20:58:50 -07003632
3633 // Handle subpass operations
3634 // TODO: GLSL should change to have the "MS" only on the type rather than the
3635 // built-in function.
3636 if (cracked.subpass) {
3637 // add on the (0,0) coordinate
3638 spv::Id zero = builder.makeIntConstant(0);
3639 std::vector<spv::Id> comps;
3640 comps.push_back(zero);
3641 comps.push_back(zero);
John Kessenich149afc32018-08-14 13:31:43 -06003642 spv::IdImmediate coord = { true,
3643 builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps) };
3644 operands.push_back(coord);
John Kessenich6c292d32016-02-15 20:58:50 -07003645 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003646 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3647 operands.push_back(imageOperands);
3648 spv::IdImmediate imageOperand = { true, *(opIt++) };
3649 operands.push_back(imageOperand);
John Kessenich6c292d32016-02-15 20:58:50 -07003650 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003651 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3652 builder.setPrecision(result, precision);
3653 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003654 }
3655
John Kessenich149afc32018-08-14 13:31:43 -06003656 spv::IdImmediate coord = { true, *(opIt++) };
3657 operands.push_back(coord);
Rex Xu129799a2017-07-05 17:23:28 +08003658#ifdef AMD_EXTENSIONS
3659 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3660#else
John Kessenich56bab042015-09-16 10:54:31 -06003661 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003662#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003663 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003664 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3665 operands.push_back(imageOperands);
3666 spv::IdImmediate imageOperand = { true, *opIt };
3667 operands.push_back(imageOperand);
Rex Xu129799a2017-07-05 17:23:28 +08003668#ifdef AMD_EXTENSIONS
3669 } else if (cracked.lod) {
3670 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3671 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3672
John Kessenich149afc32018-08-14 13:31:43 -06003673 spv::IdImmediate imageOperands = { false, spv::ImageOperandsLodMask };
3674 operands.push_back(imageOperands);
3675 spv::IdImmediate imageOperand = { true, *opIt };
3676 operands.push_back(imageOperand);
Rex Xu129799a2017-07-05 17:23:28 +08003677#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003678 }
John Kessenich149afc32018-08-14 13:31:43 -06003679 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07003680 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003681
John Kessenich149afc32018-08-14 13:31:43 -06003682 std::vector<spv::Id> result(1, builder.createOp(spv::OpImageRead, resultType(), operands));
LoopDawg4425f242018-02-18 11:40:01 -07003683 builder.setPrecision(result[0], precision);
3684
3685 // If needed, add a conversion constructor to the proper size.
3686 if (components != node->getType().getVectorSize())
3687 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3688
3689 return result[0];
Rex Xu129799a2017-07-05 17:23:28 +08003690#ifdef AMD_EXTENSIONS
3691 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3692#else
John Kessenich56bab042015-09-16 10:54:31 -06003693 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003694#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003695 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003696 spv::IdImmediate texel = { true, *(opIt + 1) };
3697 operands.push_back(texel);
3698 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3699 operands.push_back(imageOperands);
3700 spv::IdImmediate imageOperand = { true, *opIt };
3701 operands.push_back(imageOperand);
Rex Xu129799a2017-07-05 17:23:28 +08003702#ifdef AMD_EXTENSIONS
3703 } else if (cracked.lod) {
3704 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3705 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3706
John Kessenich149afc32018-08-14 13:31:43 -06003707 spv::IdImmediate texel = { true, *(opIt + 1) };
3708 operands.push_back(texel);
3709 spv::IdImmediate imageOperands = { false, spv::ImageOperandsLodMask };
3710 operands.push_back(imageOperands);
3711 spv::IdImmediate imageOperand = { true, *opIt };
3712 operands.push_back(imageOperand);
Rex Xu129799a2017-07-05 17:23:28 +08003713#endif
John Kessenich149afc32018-08-14 13:31:43 -06003714 } else {
3715 spv::IdImmediate texel = { true, *opIt };
3716 operands.push_back(texel);
3717 }
John Kessenich56bab042015-09-16 10:54:31 -06003718 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich149afc32018-08-14 13:31:43 -06003719 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
John Kessenich5d0fa972016-02-15 11:57:00 -07003720 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003721 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003722#ifdef AMD_EXTENSIONS
3723 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3724#else
Rex Xu5eafa472016-02-19 22:24:03 +08003725 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003726#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003727 builder.addCapability(spv::CapabilitySparseResidency);
John Kessenich149afc32018-08-14 13:31:43 -06003728 if (builder.getImageTypeFormat(builder.getImageType(operands.front().word)) == spv::ImageFormatUnknown)
Rex Xu5eafa472016-02-19 22:24:03 +08003729 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3730
3731 if (sampler.ms) {
John Kessenich149afc32018-08-14 13:31:43 -06003732 spv::IdImmediate imageOperands = { false, spv::ImageOperandsSampleMask };
3733 operands.push_back(imageOperands);
3734 spv::IdImmediate imageOperand = { true, *opIt++ };
3735 operands.push_back(imageOperand);
Rex Xu129799a2017-07-05 17:23:28 +08003736#ifdef AMD_EXTENSIONS
3737 } else if (cracked.lod) {
3738 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3739 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3740
John Kessenich149afc32018-08-14 13:31:43 -06003741 spv::IdImmediate imageOperands = { false, spv::ImageOperandsLodMask };
3742 operands.push_back(imageOperands);
3743 spv::IdImmediate imageOperand = { true, *opIt++ };
3744 operands.push_back(imageOperand);
Rex Xu129799a2017-07-05 17:23:28 +08003745#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003746 }
3747
3748 // Create the return type that was a special structure
3749 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003750 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003751 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3752 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3753
3754 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3755
3756 // Decode the return type
3757 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3758 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003759 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003760 // Process image atomic operations
3761
3762 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3763 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich149afc32018-08-14 13:31:43 -06003764 // For non-MS, the sample value should be 0
3765 spv::IdImmediate sample = { true, sampler.ms ? *(opIt++) : builder.makeUintConstant(0) };
3766 operands.push_back(sample);
John Kessenich140f3df2015-06-26 16:58:36 -06003767
John Kessenich8c8505c2016-07-26 12:50:38 -06003768 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003769 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003770
3771 std::vector<spv::Id> operands;
3772 operands.push_back(pointer);
3773 for (; opIt != arguments.end(); ++opIt)
3774 operands.push_back(*opIt);
3775
John Kessenich8c8505c2016-07-26 12:50:38 -06003776 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003777 }
3778 }
3779
amhagan05506bb2017-06-13 16:53:02 -04003780#ifdef AMD_EXTENSIONS
3781 // Check for fragment mask functions other than queries
3782 if (cracked.fragMask) {
3783 assert(sampler.ms);
3784
3785 auto opIt = arguments.begin();
3786 std::vector<spv::Id> operands;
3787
3788 // Extract the image if necessary
3789 if (builder.isSampledImage(params.sampler))
3790 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3791
3792 operands.push_back(params.sampler);
3793 ++opIt;
3794
3795 if (sampler.isSubpass()) {
3796 // add on the (0,0) coordinate
3797 spv::Id zero = builder.makeIntConstant(0);
3798 std::vector<spv::Id> comps;
3799 comps.push_back(zero);
3800 comps.push_back(zero);
3801 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3802 }
3803
3804 for (; opIt != arguments.end(); ++opIt)
3805 operands.push_back(*opIt);
3806
3807 spv::Op fragMaskOp = spv::OpNop;
3808 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3809 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3810 else if (node->getOp() == glslang::EOpFragmentFetch)
3811 fragMaskOp = spv::OpFragmentFetchAMD;
3812
3813 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3814 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3815 return builder.createOp(fragMaskOp, resultType(), operands);
3816 }
3817#endif
3818
Rex Xufc618912015-09-09 16:42:49 +08003819 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003820 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003821 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3822
John Kessenichfc51d282015-08-19 13:34:18 -06003823 // check for bias argument
3824 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003825#ifdef AMD_EXTENSIONS
3826 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3827#else
Rex Xu71519fe2015-11-11 15:35:47 +08003828 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003829#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003830 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003831#ifdef AMD_EXTENSIONS
3832 if (cracked.gather)
3833 ++nonBiasArgCount; // comp argument should be present when bias argument is present
Rex Xu1e5d7b02016-11-29 17:36:31 +08003834
3835 if (f16ShadowCompare)
3836 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003837#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003838 if (cracked.offset)
3839 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003840#ifdef AMD_EXTENSIONS
3841 else if (cracked.offsets)
3842 ++nonBiasArgCount;
3843#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003844 if (cracked.grad)
3845 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003846 if (cracked.lodClamp)
3847 ++nonBiasArgCount;
3848 if (sparse)
3849 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003850
3851 if ((int)arguments.size() > nonBiasArgCount)
3852 bias = true;
3853 }
3854
John Kessenicha5c33d62016-06-02 23:45:21 -06003855 // See if the sampler param should really be just the SPV image part
3856 if (cracked.fetch) {
3857 // a fetch needs to have the image extracted first
3858 if (builder.isSampledImage(params.sampler))
3859 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3860 }
3861
Rex Xu225e0fc2016-11-17 17:47:59 +08003862#ifdef AMD_EXTENSIONS
3863 if (cracked.gather) {
3864 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3865 if (bias || cracked.lod ||
3866 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3867 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003868 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003869 }
3870 }
3871#endif
3872
John Kessenichfc51d282015-08-19 13:34:18 -06003873 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003874
John Kessenichfc51d282015-08-19 13:34:18 -06003875 params.coords = arguments[1];
3876 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003877 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003878
3879 // sort out where Dref is coming from
Rex Xu1e5d7b02016-11-29 17:36:31 +08003880#ifdef AMD_EXTENSIONS
3881 if (cubeCompare || f16ShadowCompare) {
3882#else
Rex Xu48edadf2015-12-31 16:11:41 +08003883 if (cubeCompare) {
Rex Xu1e5d7b02016-11-29 17:36:31 +08003884#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003885 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003886 ++extraArgs;
3887 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003888 params.Dref = arguments[2];
3889 ++extraArgs;
3890 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003891 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003892 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003893 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003894 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003895 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003896 dRefComp = builder.getNumComponents(params.coords) - 1;
3897 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003898 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3899 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003900
3901 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003902 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003903 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003904 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003905 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3906 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3907 noImplicitLod = true;
3908 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003909
3910 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003911 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003912 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003913 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003914 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003915
3916 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003917 if (cracked.grad) {
3918 params.gradX = arguments[2 + extraArgs];
3919 params.gradY = arguments[3 + extraArgs];
3920 extraArgs += 2;
3921 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003922
3923 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003924 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003925 params.offset = arguments[2 + extraArgs];
3926 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003927 } else if (cracked.offsets) {
3928 params.offsets = arguments[2 + extraArgs];
3929 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003930 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003931
3932 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003933 if (cracked.lodClamp) {
3934 params.lodClamp = arguments[2 + extraArgs];
3935 ++extraArgs;
3936 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003937
3938 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003939 if (sparse) {
3940 params.texelOut = arguments[2 + extraArgs];
3941 ++extraArgs;
3942 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003943
John Kessenich76d4dfc2016-06-16 12:43:23 -06003944 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003945 if (cracked.gather && ! sampler.shadow) {
3946 // default component is 0, if missing, otherwise an argument
3947 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003948 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003949 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003950 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003951 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003952 }
3953
3954 // bias
3955 if (bias) {
3956 params.bias = arguments[2 + extraArgs];
3957 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003958 }
John Kessenichfc51d282015-08-19 13:34:18 -06003959
John Kessenich65336482016-06-16 14:06:26 -06003960 // projective component (might not to move)
3961 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3962 // are divided by the last component of P."
3963 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3964 // unused components will appear after all used components."
3965 if (cracked.proj) {
3966 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3967 int projTargetComp;
3968 switch (sampler.dim) {
3969 case glslang::Esd1D: projTargetComp = 1; break;
3970 case glslang::Esd2D: projTargetComp = 2; break;
3971 case glslang::EsdRect: projTargetComp = 2; break;
3972 default: projTargetComp = projSourceComp; break;
3973 }
3974 // copy the projective coordinate if we have to
3975 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003976 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003977 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3978 projSourceComp);
3979 params.coords = builder.createCompositeInsert(projComp, params.coords,
3980 builder.getTypeId(params.coords), projTargetComp);
3981 }
3982 }
3983
St0fFa1184dd2018-04-09 21:08:14 +02003984 std::vector<spv::Id> result( 1,
LoopDawg4425f242018-02-18 11:40:01 -07003985 builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params)
St0fFa1184dd2018-04-09 21:08:14 +02003986 );
LoopDawg4425f242018-02-18 11:40:01 -07003987
3988 if (components != node->getType().getVectorSize())
3989 result[0] = builder.createConstructor(precision, result, convertGlslangToSpvType(node->getType()));
3990
3991 return result[0];
John Kessenich140f3df2015-06-26 16:58:36 -06003992}
3993
3994spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3995{
3996 // Grab the function's pointer from the previously created function
3997 spv::Function* function = functionMap[node->getName().c_str()];
3998 if (! function)
3999 return 0;
4000
4001 const glslang::TIntermSequence& glslangArgs = node->getSequence();
4002 const glslang::TQualifierList& qualifiers = node->getQualifierList();
4003
4004 // See comments in makeFunctions() for details about the semantics for parameter passing.
4005 //
4006 // These imply we need a four step process:
4007 // 1. Evaluate the arguments
4008 // 2. Allocate and make copies of in, out, and inout arguments
4009 // 3. Make the call
4010 // 4. Copy back the results
4011
John Kessenichd3ed90b2018-05-04 11:43:03 -06004012 // 1. Evaluate the arguments and their types
John Kessenich140f3df2015-06-26 16:58:36 -06004013 std::vector<spv::Builder::AccessChain> lValues;
4014 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07004015 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06004016 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004017 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06004018 // build l-value
4019 builder.clearAccessChain();
4020 glslangArgs[a]->traverse(this);
John Kessenichd41993d2017-09-10 15:21:05 -06004021 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenichd3ed90b2018-05-04 11:43:03 -06004022 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0) ||
John Kessenich6a14f782017-12-04 02:48:10 -07004023 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004024 // save l-value
4025 lValues.push_back(builder.getAccessChain());
4026 } else {
4027 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07004028 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06004029 }
4030 }
4031
4032 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
4033 // copy the original into that space.
4034 //
4035 // Also, build up the list of actual arguments to pass in for the call
4036 int lValueCount = 0;
4037 int rValueCount = 0;
4038 std::vector<spv::Id> spvArgs;
4039 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
4040 spv::Id arg;
John Kessenichd3ed90b2018-05-04 11:43:03 -06004041 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07004042 builder.setAccessChain(lValues[lValueCount]);
4043 arg = builder.accessChainGetLValue();
4044 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06004045 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004046 // need space to hold the copy
John Kessenichd3ed90b2018-05-04 11:43:03 -06004047 arg = builder.createVariable(spv::StorageClassFunction, builder.getContainedTypeId(function->getParamType(a)), "param");
John Kessenich140f3df2015-06-26 16:58:36 -06004048 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
4049 // need to copy the input into output space
4050 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07004051 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06004052 builder.clearAccessChain();
4053 builder.setAccessChainLValue(arg);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004054 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004055 }
4056 ++lValueCount;
4057 } else {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004058 // process r-value, which involves a copy for a type mismatch
4059 if (function->getParamType(a) != convertGlslangToSpvType(*argTypes[a])) {
4060 spv::Id argCopy = builder.createVariable(spv::StorageClassFunction, function->getParamType(a), "arg");
4061 builder.clearAccessChain();
4062 builder.setAccessChainLValue(argCopy);
4063 multiTypeStore(*argTypes[a], rValues[rValueCount]);
4064 arg = builder.createLoad(argCopy);
4065 } else
4066 arg = rValues[rValueCount];
John Kessenich140f3df2015-06-26 16:58:36 -06004067 ++rValueCount;
4068 }
4069 spvArgs.push_back(arg);
4070 }
4071
4072 // 3. Make the call.
4073 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07004074 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06004075
4076 // 4. Copy back out an "out" arguments.
4077 lValueCount = 0;
4078 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenichd3ed90b2018-05-04 11:43:03 -06004079 if (originalParam(qualifiers[a], *argTypes[a], function->hasImplicitThis() && a == 0))
John Kessenichd41993d2017-09-10 15:21:05 -06004080 ++lValueCount;
4081 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06004082 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
4083 spv::Id copy = builder.createLoad(spvArgs[a]);
4084 builder.setAccessChain(lValues[lValueCount]);
John Kessenichd3ed90b2018-05-04 11:43:03 -06004085 multiTypeStore(*argTypes[a], copy);
John Kessenich140f3df2015-06-26 16:58:36 -06004086 }
4087 ++lValueCount;
4088 }
4089 }
4090
4091 return result;
4092}
4093
4094// Translate AST operation to SPV operation, already having SPV-based operands/types.
John Kessenichead86222018-03-28 18:01:20 -06004095spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, OpDecorations& decorations,
John Kessenich140f3df2015-06-26 16:58:36 -06004096 spv::Id typeId, spv::Id left, spv::Id right,
4097 glslang::TBasicType typeProxy, bool reduceComparison)
4098{
John Kessenich66011cb2018-03-06 16:12:04 -07004099 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4100 bool isFloat = isTypeFloat(typeProxy);
Rex Xuc7d36562016-04-27 08:15:37 +08004101 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06004102
4103 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06004104 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06004105 bool comparison = false;
4106
4107 switch (op) {
4108 case glslang::EOpAdd:
4109 case glslang::EOpAddAssign:
4110 if (isFloat)
4111 binOp = spv::OpFAdd;
4112 else
4113 binOp = spv::OpIAdd;
4114 break;
4115 case glslang::EOpSub:
4116 case glslang::EOpSubAssign:
4117 if (isFloat)
4118 binOp = spv::OpFSub;
4119 else
4120 binOp = spv::OpISub;
4121 break;
4122 case glslang::EOpMul:
4123 case glslang::EOpMulAssign:
4124 if (isFloat)
4125 binOp = spv::OpFMul;
4126 else
4127 binOp = spv::OpIMul;
4128 break;
4129 case glslang::EOpVectorTimesScalar:
4130 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06004131 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06004132 if (builder.isVector(right))
4133 std::swap(left, right);
4134 assert(builder.isScalar(right));
4135 needMatchingVectors = false;
4136 binOp = spv::OpVectorTimesScalar;
4137 } else
4138 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06004139 break;
4140 case glslang::EOpVectorTimesMatrix:
4141 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004142 binOp = spv::OpVectorTimesMatrix;
4143 break;
4144 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06004145 binOp = spv::OpMatrixTimesVector;
4146 break;
4147 case glslang::EOpMatrixTimesScalar:
4148 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004149 binOp = spv::OpMatrixTimesScalar;
4150 break;
4151 case glslang::EOpMatrixTimesMatrix:
4152 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06004153 binOp = spv::OpMatrixTimesMatrix;
4154 break;
4155 case glslang::EOpOuterProduct:
4156 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06004157 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004158 break;
4159
4160 case glslang::EOpDiv:
4161 case glslang::EOpDivAssign:
4162 if (isFloat)
4163 binOp = spv::OpFDiv;
4164 else if (isUnsigned)
4165 binOp = spv::OpUDiv;
4166 else
4167 binOp = spv::OpSDiv;
4168 break;
4169 case glslang::EOpMod:
4170 case glslang::EOpModAssign:
4171 if (isFloat)
4172 binOp = spv::OpFMod;
4173 else if (isUnsigned)
4174 binOp = spv::OpUMod;
4175 else
4176 binOp = spv::OpSMod;
4177 break;
4178 case glslang::EOpRightShift:
4179 case glslang::EOpRightShiftAssign:
4180 if (isUnsigned)
4181 binOp = spv::OpShiftRightLogical;
4182 else
4183 binOp = spv::OpShiftRightArithmetic;
4184 break;
4185 case glslang::EOpLeftShift:
4186 case glslang::EOpLeftShiftAssign:
4187 binOp = spv::OpShiftLeftLogical;
4188 break;
4189 case glslang::EOpAnd:
4190 case glslang::EOpAndAssign:
4191 binOp = spv::OpBitwiseAnd;
4192 break;
4193 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06004194 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004195 binOp = spv::OpLogicalAnd;
4196 break;
4197 case glslang::EOpInclusiveOr:
4198 case glslang::EOpInclusiveOrAssign:
4199 binOp = spv::OpBitwiseOr;
4200 break;
4201 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06004202 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06004203 binOp = spv::OpLogicalOr;
4204 break;
4205 case glslang::EOpExclusiveOr:
4206 case glslang::EOpExclusiveOrAssign:
4207 binOp = spv::OpBitwiseXor;
4208 break;
4209 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06004210 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06004211 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004212 break;
4213
4214 case glslang::EOpLessThan:
4215 case glslang::EOpGreaterThan:
4216 case glslang::EOpLessThanEqual:
4217 case glslang::EOpGreaterThanEqual:
4218 case glslang::EOpEqual:
4219 case glslang::EOpNotEqual:
4220 case glslang::EOpVectorEqual:
4221 case glslang::EOpVectorNotEqual:
4222 comparison = true;
4223 break;
4224 default:
4225 break;
4226 }
4227
John Kessenich7c1aa102015-10-15 13:29:11 -06004228 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06004229 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06004230 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07004231 if (builder.isMatrix(left) || builder.isMatrix(right))
John Kessenichead86222018-03-28 18:01:20 -06004232 return createBinaryMatrixOperation(binOp, decorations, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004233
4234 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06004235 if (needMatchingVectors)
John Kessenichead86222018-03-28 18:01:20 -06004236 builder.promoteScalar(decorations.precision, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06004237
qining25262b32016-05-06 17:25:16 -04004238 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004239 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004240 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004241 return builder.setPrecision(result, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004242 }
4243
4244 if (! comparison)
4245 return 0;
4246
John Kessenich7c1aa102015-10-15 13:29:11 -06004247 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06004248
John Kessenich4583b612016-08-07 19:14:22 -06004249 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
John Kessenichead86222018-03-28 18:01:20 -06004250 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
4251 spv::Id result = builder.createCompositeCompare(decorations.precision, left, right, op == glslang::EOpEqual);
John Kessenich5611c6d2018-04-05 11:25:02 -06004252 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004253 return result;
4254 }
John Kessenich140f3df2015-06-26 16:58:36 -06004255
4256 switch (op) {
4257 case glslang::EOpLessThan:
4258 if (isFloat)
4259 binOp = spv::OpFOrdLessThan;
4260 else if (isUnsigned)
4261 binOp = spv::OpULessThan;
4262 else
4263 binOp = spv::OpSLessThan;
4264 break;
4265 case glslang::EOpGreaterThan:
4266 if (isFloat)
4267 binOp = spv::OpFOrdGreaterThan;
4268 else if (isUnsigned)
4269 binOp = spv::OpUGreaterThan;
4270 else
4271 binOp = spv::OpSGreaterThan;
4272 break;
4273 case glslang::EOpLessThanEqual:
4274 if (isFloat)
4275 binOp = spv::OpFOrdLessThanEqual;
4276 else if (isUnsigned)
4277 binOp = spv::OpULessThanEqual;
4278 else
4279 binOp = spv::OpSLessThanEqual;
4280 break;
4281 case glslang::EOpGreaterThanEqual:
4282 if (isFloat)
4283 binOp = spv::OpFOrdGreaterThanEqual;
4284 else if (isUnsigned)
4285 binOp = spv::OpUGreaterThanEqual;
4286 else
4287 binOp = spv::OpSGreaterThanEqual;
4288 break;
4289 case glslang::EOpEqual:
4290 case glslang::EOpVectorEqual:
4291 if (isFloat)
4292 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004293 else if (isBool)
4294 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004295 else
4296 binOp = spv::OpIEqual;
4297 break;
4298 case glslang::EOpNotEqual:
4299 case glslang::EOpVectorNotEqual:
4300 if (isFloat)
4301 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08004302 else if (isBool)
4303 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06004304 else
4305 binOp = spv::OpINotEqual;
4306 break;
4307 default:
4308 break;
4309 }
4310
qining25262b32016-05-06 17:25:16 -04004311 if (binOp != spv::OpNop) {
4312 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004313 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004314 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004315 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004316 }
John Kessenich140f3df2015-06-26 16:58:36 -06004317
4318 return 0;
4319}
4320
John Kessenich04bb8a02015-12-12 12:28:14 -07004321//
4322// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
4323// These can be any of:
4324//
4325// matrix * scalar
4326// scalar * matrix
4327// matrix * matrix linear algebraic
4328// matrix * vector
4329// vector * matrix
4330// matrix * matrix componentwise
4331// matrix op matrix op in {+, -, /}
4332// matrix op scalar op in {+, -, /}
4333// scalar op matrix op in {+, -, /}
4334//
John Kessenichead86222018-03-28 18:01:20 -06004335spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4336 spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07004337{
4338 bool firstClass = true;
4339
4340 // First, handle first-class matrix operations (* and matrix/scalar)
4341 switch (op) {
4342 case spv::OpFDiv:
4343 if (builder.isMatrix(left) && builder.isScalar(right)) {
4344 // turn matrix / scalar into a multiply...
Neil Robertseddb1312018-03-13 10:57:59 +01004345 spv::Id resultType = builder.getTypeId(right);
4346 right = builder.createBinOp(spv::OpFDiv, resultType, builder.makeFpConstant(resultType, 1.0), right);
John Kessenich04bb8a02015-12-12 12:28:14 -07004347 op = spv::OpMatrixTimesScalar;
4348 } else
4349 firstClass = false;
4350 break;
4351 case spv::OpMatrixTimesScalar:
4352 if (builder.isMatrix(right))
4353 std::swap(left, right);
4354 assert(builder.isScalar(right));
4355 break;
4356 case spv::OpVectorTimesMatrix:
4357 assert(builder.isVector(left));
4358 assert(builder.isMatrix(right));
4359 break;
4360 case spv::OpMatrixTimesVector:
4361 assert(builder.isMatrix(left));
4362 assert(builder.isVector(right));
4363 break;
4364 case spv::OpMatrixTimesMatrix:
4365 assert(builder.isMatrix(left));
4366 assert(builder.isMatrix(right));
4367 break;
4368 default:
4369 firstClass = false;
4370 break;
4371 }
4372
qining25262b32016-05-06 17:25:16 -04004373 if (firstClass) {
4374 spv::Id result = builder.createBinOp(op, typeId, left, right);
John Kessenichead86222018-03-28 18:01:20 -06004375 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004376 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004377 return builder.setPrecision(result, decorations.precision);
qining25262b32016-05-06 17:25:16 -04004378 }
John Kessenich04bb8a02015-12-12 12:28:14 -07004379
LoopDawg592860c2016-06-09 08:57:35 -06004380 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07004381 // The result type of all of them is the same type as the (a) matrix operand.
4382 // The algorithm is to:
4383 // - break the matrix(es) into vectors
4384 // - smear any scalar to a vector
4385 // - do vector operations
4386 // - make a matrix out the vector results
4387 switch (op) {
4388 case spv::OpFAdd:
4389 case spv::OpFSub:
4390 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06004391 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07004392 case spv::OpFMul:
4393 {
4394 // one time set up...
4395 bool leftMat = builder.isMatrix(left);
4396 bool rightMat = builder.isMatrix(right);
4397 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4398 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4399 spv::Id scalarType = builder.getScalarTypeId(typeId);
4400 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4401 std::vector<spv::Id> results;
4402 spv::Id smearVec = spv::NoResult;
4403 if (builder.isScalar(left))
John Kessenichead86222018-03-28 18:01:20 -06004404 smearVec = builder.smearScalar(decorations.precision, left, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004405 else if (builder.isScalar(right))
John Kessenichead86222018-03-28 18:01:20 -06004406 smearVec = builder.smearScalar(decorations.precision, right, vecType);
John Kessenich04bb8a02015-12-12 12:28:14 -07004407
4408 // do each vector op
4409 for (unsigned int c = 0; c < numCols; ++c) {
4410 std::vector<unsigned int> indexes;
4411 indexes.push_back(c);
4412 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4413 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004414 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
John Kessenichead86222018-03-28 18:01:20 -06004415 builder.addDecoration(result, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004416 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004417 results.push_back(builder.setPrecision(result, decorations.precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004418 }
4419
4420 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004421 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004422 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004423 return result;
John Kessenich04bb8a02015-12-12 12:28:14 -07004424 }
4425 default:
4426 assert(0);
4427 return spv::NoResult;
4428 }
4429}
4430
John Kessenichead86222018-03-28 18:01:20 -06004431spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, OpDecorations& decorations, spv::Id typeId,
4432 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004433{
4434 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004435 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004436 int libCall = -1;
John Kessenich66011cb2018-03-06 16:12:04 -07004437 bool isUnsigned = isTypeUnsignedInt(typeProxy);
4438 bool isFloat = isTypeFloat(typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004439
4440 switch (op) {
4441 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004442 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004443 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004444 if (builder.isMatrixType(typeId))
John Kessenichead86222018-03-28 18:01:20 -06004445 return createUnaryMatrixOperation(unaryOp, decorations, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004446 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004447 unaryOp = spv::OpSNegate;
4448 break;
4449
4450 case glslang::EOpLogicalNot:
4451 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004452 unaryOp = spv::OpLogicalNot;
4453 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004454 case glslang::EOpBitwiseNot:
4455 unaryOp = spv::OpNot;
4456 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004457
John Kessenich140f3df2015-06-26 16:58:36 -06004458 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004459 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004460 break;
4461 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004462 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004463 break;
4464 case glslang::EOpTranspose:
4465 unaryOp = spv::OpTranspose;
4466 break;
4467
4468 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004469 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004470 break;
4471 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004472 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004473 break;
4474 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004475 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004476 break;
4477 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004478 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004479 break;
4480 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004481 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004482 break;
4483 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004484 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004485 break;
4486 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004487 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004488 break;
4489 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004490 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004491 break;
4492
4493 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004494 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004495 break;
4496 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004497 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004498 break;
4499 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004500 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004501 break;
4502 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004503 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004504 break;
4505 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004506 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004507 break;
4508 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004509 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004510 break;
4511
4512 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004513 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004514 break;
4515 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004516 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004517 break;
4518
4519 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004520 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004521 break;
4522 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004523 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004524 break;
4525 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004526 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004527 break;
4528 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004529 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004530 break;
4531 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004532 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004533 break;
4534 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004535 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004536 break;
4537
4538 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004539 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004540 break;
4541 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004542 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004543 break;
4544 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004545 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004546 break;
4547 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004548 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004549 break;
4550 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004551 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004552 break;
4553 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004554 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004555 break;
4556
4557 case glslang::EOpIsNan:
4558 unaryOp = spv::OpIsNan;
4559 break;
4560 case glslang::EOpIsInf:
4561 unaryOp = spv::OpIsInf;
4562 break;
LoopDawg592860c2016-06-09 08:57:35 -06004563 case glslang::EOpIsFinite:
4564 unaryOp = spv::OpIsFinite;
4565 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004566
Rex Xucbc426e2015-12-15 16:03:10 +08004567 case glslang::EOpFloatBitsToInt:
4568 case glslang::EOpFloatBitsToUint:
4569 case glslang::EOpIntBitsToFloat:
4570 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004571 case glslang::EOpDoubleBitsToInt64:
4572 case glslang::EOpDoubleBitsToUint64:
4573 case glslang::EOpInt64BitsToDouble:
4574 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004575 case glslang::EOpFloat16BitsToInt16:
4576 case glslang::EOpFloat16BitsToUint16:
4577 case glslang::EOpInt16BitsToFloat16:
4578 case glslang::EOpUint16BitsToFloat16:
Rex Xucbc426e2015-12-15 16:03:10 +08004579 unaryOp = spv::OpBitcast;
4580 break;
4581
John Kessenich140f3df2015-06-26 16:58:36 -06004582 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004583 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004584 break;
4585 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004586 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004587 break;
4588 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004589 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004590 break;
4591 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004592 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004593 break;
4594 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004595 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004596 break;
4597 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004598 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004599 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004600 case glslang::EOpPackSnorm4x8:
4601 libCall = spv::GLSLstd450PackSnorm4x8;
4602 break;
4603 case glslang::EOpUnpackSnorm4x8:
4604 libCall = spv::GLSLstd450UnpackSnorm4x8;
4605 break;
4606 case glslang::EOpPackUnorm4x8:
4607 libCall = spv::GLSLstd450PackUnorm4x8;
4608 break;
4609 case glslang::EOpUnpackUnorm4x8:
4610 libCall = spv::GLSLstd450UnpackUnorm4x8;
4611 break;
4612 case glslang::EOpPackDouble2x32:
4613 libCall = spv::GLSLstd450PackDouble2x32;
4614 break;
4615 case glslang::EOpUnpackDouble2x32:
4616 libCall = spv::GLSLstd450UnpackDouble2x32;
4617 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004618
Rex Xu8ff43de2016-04-22 16:51:45 +08004619 case glslang::EOpPackInt2x32:
4620 case glslang::EOpUnpackInt2x32:
4621 case glslang::EOpPackUint2x32:
4622 case glslang::EOpUnpackUint2x32:
John Kessenich66011cb2018-03-06 16:12:04 -07004623 case glslang::EOpPack16:
4624 case glslang::EOpPack32:
4625 case glslang::EOpPack64:
4626 case glslang::EOpUnpack32:
4627 case glslang::EOpUnpack16:
4628 case glslang::EOpUnpack8:
Rex Xucabbb782017-03-24 13:41:14 +08004629 case glslang::EOpPackInt2x16:
4630 case glslang::EOpUnpackInt2x16:
4631 case glslang::EOpPackUint2x16:
4632 case glslang::EOpUnpackUint2x16:
4633 case glslang::EOpPackInt4x16:
4634 case glslang::EOpUnpackInt4x16:
4635 case glslang::EOpPackUint4x16:
4636 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004637 case glslang::EOpPackFloat2x16:
4638 case glslang::EOpUnpackFloat2x16:
4639 unaryOp = spv::OpBitcast;
4640 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004641
John Kessenich140f3df2015-06-26 16:58:36 -06004642 case glslang::EOpDPdx:
4643 unaryOp = spv::OpDPdx;
4644 break;
4645 case glslang::EOpDPdy:
4646 unaryOp = spv::OpDPdy;
4647 break;
4648 case glslang::EOpFwidth:
4649 unaryOp = spv::OpFwidth;
4650 break;
4651 case glslang::EOpDPdxFine:
4652 unaryOp = spv::OpDPdxFine;
4653 break;
4654 case glslang::EOpDPdyFine:
4655 unaryOp = spv::OpDPdyFine;
4656 break;
4657 case glslang::EOpFwidthFine:
4658 unaryOp = spv::OpFwidthFine;
4659 break;
4660 case glslang::EOpDPdxCoarse:
4661 unaryOp = spv::OpDPdxCoarse;
4662 break;
4663 case glslang::EOpDPdyCoarse:
4664 unaryOp = spv::OpDPdyCoarse;
4665 break;
4666 case glslang::EOpFwidthCoarse:
4667 unaryOp = spv::OpFwidthCoarse;
4668 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004669 case glslang::EOpInterpolateAtCentroid:
Rex Xub4a2a6c2018-05-17 13:51:28 +08004670#ifdef AMD_EXTENSIONS
4671 if (typeProxy == glslang::EbtFloat16)
4672 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
4673#endif
Rex Xu7a26c172015-12-08 17:12:09 +08004674 libCall = spv::GLSLstd450InterpolateAtCentroid;
4675 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004676 case glslang::EOpAny:
4677 unaryOp = spv::OpAny;
4678 break;
4679 case glslang::EOpAll:
4680 unaryOp = spv::OpAll;
4681 break;
4682
4683 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004684 if (isFloat)
4685 libCall = spv::GLSLstd450FAbs;
4686 else
4687 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004688 break;
4689 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004690 if (isFloat)
4691 libCall = spv::GLSLstd450FSign;
4692 else
4693 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004694 break;
4695
John Kessenichfc51d282015-08-19 13:34:18 -06004696 case glslang::EOpAtomicCounterIncrement:
4697 case glslang::EOpAtomicCounterDecrement:
4698 case glslang::EOpAtomicCounter:
4699 {
4700 // Handle all of the atomics in one place, in createAtomicOperation()
4701 std::vector<spv::Id> operands;
4702 operands.push_back(operand);
John Kessenichead86222018-03-28 18:01:20 -06004703 return createAtomicOperation(op, decorations.precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004704 }
4705
John Kessenichfc51d282015-08-19 13:34:18 -06004706 case glslang::EOpBitFieldReverse:
4707 unaryOp = spv::OpBitReverse;
4708 break;
4709 case glslang::EOpBitCount:
4710 unaryOp = spv::OpBitCount;
4711 break;
4712 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004713 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004714 break;
4715 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004716 if (isUnsigned)
4717 libCall = spv::GLSLstd450FindUMsb;
4718 else
4719 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004720 break;
4721
Rex Xu574ab042016-04-14 16:53:07 +08004722 case glslang::EOpBallot:
4723 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004724 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004725 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004726 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004727#ifdef AMD_EXTENSIONS
4728 case glslang::EOpMinInvocations:
4729 case glslang::EOpMaxInvocations:
4730 case glslang::EOpAddInvocations:
4731 case glslang::EOpMinInvocationsNonUniform:
4732 case glslang::EOpMaxInvocationsNonUniform:
4733 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004734 case glslang::EOpMinInvocationsInclusiveScan:
4735 case glslang::EOpMaxInvocationsInclusiveScan:
4736 case glslang::EOpAddInvocationsInclusiveScan:
4737 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4738 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4739 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4740 case glslang::EOpMinInvocationsExclusiveScan:
4741 case glslang::EOpMaxInvocationsExclusiveScan:
4742 case glslang::EOpAddInvocationsExclusiveScan:
4743 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4744 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4745 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004746#endif
Rex Xu51596642016-09-21 18:56:12 +08004747 {
4748 std::vector<spv::Id> operands;
4749 operands.push_back(operand);
4750 return createInvocationsOperation(op, typeId, operands, typeProxy);
4751 }
John Kessenich66011cb2018-03-06 16:12:04 -07004752 case glslang::EOpSubgroupAll:
4753 case glslang::EOpSubgroupAny:
4754 case glslang::EOpSubgroupAllEqual:
4755 case glslang::EOpSubgroupBroadcastFirst:
4756 case glslang::EOpSubgroupBallot:
4757 case glslang::EOpSubgroupInverseBallot:
4758 case glslang::EOpSubgroupBallotBitCount:
4759 case glslang::EOpSubgroupBallotInclusiveBitCount:
4760 case glslang::EOpSubgroupBallotExclusiveBitCount:
4761 case glslang::EOpSubgroupBallotFindLSB:
4762 case glslang::EOpSubgroupBallotFindMSB:
4763 case glslang::EOpSubgroupAdd:
4764 case glslang::EOpSubgroupMul:
4765 case glslang::EOpSubgroupMin:
4766 case glslang::EOpSubgroupMax:
4767 case glslang::EOpSubgroupAnd:
4768 case glslang::EOpSubgroupOr:
4769 case glslang::EOpSubgroupXor:
4770 case glslang::EOpSubgroupInclusiveAdd:
4771 case glslang::EOpSubgroupInclusiveMul:
4772 case glslang::EOpSubgroupInclusiveMin:
4773 case glslang::EOpSubgroupInclusiveMax:
4774 case glslang::EOpSubgroupInclusiveAnd:
4775 case glslang::EOpSubgroupInclusiveOr:
4776 case glslang::EOpSubgroupInclusiveXor:
4777 case glslang::EOpSubgroupExclusiveAdd:
4778 case glslang::EOpSubgroupExclusiveMul:
4779 case glslang::EOpSubgroupExclusiveMin:
4780 case glslang::EOpSubgroupExclusiveMax:
4781 case glslang::EOpSubgroupExclusiveAnd:
4782 case glslang::EOpSubgroupExclusiveOr:
4783 case glslang::EOpSubgroupExclusiveXor:
4784 case glslang::EOpSubgroupQuadSwapHorizontal:
4785 case glslang::EOpSubgroupQuadSwapVertical:
4786 case glslang::EOpSubgroupQuadSwapDiagonal: {
4787 std::vector<spv::Id> operands;
4788 operands.push_back(operand);
4789 return createSubgroupOperation(op, typeId, operands, typeProxy);
4790 }
Rex Xu9d93a232016-05-05 12:30:44 +08004791#ifdef AMD_EXTENSIONS
4792 case glslang::EOpMbcnt:
4793 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4794 libCall = spv::MbcntAMD;
4795 break;
4796
4797 case glslang::EOpCubeFaceIndex:
4798 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4799 libCall = spv::CubeFaceIndexAMD;
4800 break;
4801
4802 case glslang::EOpCubeFaceCoord:
4803 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4804 libCall = spv::CubeFaceCoordAMD;
4805 break;
4806#endif
Jeff Bolz2abe9a42018-03-29 22:52:17 -05004807#ifdef NV_EXTENSIONS
4808 case glslang::EOpSubgroupPartition:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05004809 unaryOp = spv::OpGroupNonUniformPartitionNV;
4810 break;
4811#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004812 default:
4813 return 0;
4814 }
4815
4816 spv::Id id;
4817 if (libCall >= 0) {
4818 std::vector<spv::Id> args;
4819 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004820 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004821 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004822 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004823 }
John Kessenich140f3df2015-06-26 16:58:36 -06004824
John Kessenichead86222018-03-28 18:01:20 -06004825 builder.addDecoration(id, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004826 builder.addDecoration(id, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004827 return builder.setPrecision(id, decorations.precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004828}
4829
John Kessenich7a53f762016-01-20 11:19:27 -07004830// Create a unary operation on a matrix
John Kessenichead86222018-03-28 18:01:20 -06004831spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, OpDecorations& decorations, spv::Id typeId,
4832 spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07004833{
4834 // Handle unary operations vector by vector.
4835 // The result type is the same type as the original type.
4836 // The algorithm is to:
4837 // - break the matrix into vectors
4838 // - apply the operation to each vector
4839 // - make a matrix out the vector results
4840
4841 // get the types sorted out
4842 int numCols = builder.getNumColumns(operand);
4843 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004844 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4845 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004846 std::vector<spv::Id> results;
4847
4848 // do each vector op
4849 for (int c = 0; c < numCols; ++c) {
4850 std::vector<unsigned int> indexes;
4851 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004852 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4853 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
John Kessenichead86222018-03-28 18:01:20 -06004854 builder.addDecoration(destVec, decorations.noContraction);
John Kessenich5611c6d2018-04-05 11:25:02 -06004855 builder.addDecoration(destVec, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004856 results.push_back(builder.setPrecision(destVec, decorations.precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004857 }
4858
4859 // put the pieces together
John Kessenichead86222018-03-28 18:01:20 -06004860 spv::Id result = builder.setPrecision(builder.createCompositeConstruct(typeId, results), decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06004861 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06004862 return result;
John Kessenich7a53f762016-01-20 11:19:27 -07004863}
4864
John Kessenichad7645f2018-06-04 19:11:25 -06004865// For converting integers where both the bitwidth and the signedness could
4866// change, but only do the width change here. The caller is still responsible
4867// for the signedness conversion.
4868spv::Id TGlslangToSpvTraverser::createIntWidthConversion(glslang::TOperator op, spv::Id operand, int vectorSize)
John Kessenich66011cb2018-03-06 16:12:04 -07004869{
John Kessenichad7645f2018-06-04 19:11:25 -06004870 // Get the result type width, based on the type to convert to.
4871 int width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07004872 switch(op) {
John Kessenichad7645f2018-06-04 19:11:25 -06004873 case glslang::EOpConvInt16ToUint8:
4874 case glslang::EOpConvIntToUint8:
4875 case glslang::EOpConvInt64ToUint8:
4876 case glslang::EOpConvUint16ToInt8:
4877 case glslang::EOpConvUintToInt8:
4878 case glslang::EOpConvUint64ToInt8:
4879 width = 8;
4880 break;
John Kessenich66011cb2018-03-06 16:12:04 -07004881 case glslang::EOpConvInt8ToUint16:
John Kessenichad7645f2018-06-04 19:11:25 -06004882 case glslang::EOpConvIntToUint16:
4883 case glslang::EOpConvInt64ToUint16:
4884 case glslang::EOpConvUint8ToInt16:
4885 case glslang::EOpConvUintToInt16:
4886 case glslang::EOpConvUint64ToInt16:
4887 width = 16;
John Kessenich66011cb2018-03-06 16:12:04 -07004888 break;
4889 case glslang::EOpConvInt8ToUint:
John Kessenichad7645f2018-06-04 19:11:25 -06004890 case glslang::EOpConvInt16ToUint:
4891 case glslang::EOpConvInt64ToUint:
4892 case glslang::EOpConvUint8ToInt:
4893 case glslang::EOpConvUint16ToInt:
4894 case glslang::EOpConvUint64ToInt:
4895 width = 32;
John Kessenich66011cb2018-03-06 16:12:04 -07004896 break;
4897 case glslang::EOpConvInt8ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07004898 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07004899 case glslang::EOpConvIntToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07004900 case glslang::EOpConvUint8ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07004901 case glslang::EOpConvUint16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07004902 case glslang::EOpConvUintToInt64:
John Kessenichad7645f2018-06-04 19:11:25 -06004903 width = 64;
John Kessenich66011cb2018-03-06 16:12:04 -07004904 break;
4905
4906 default:
4907 assert(false && "Default missing");
4908 break;
4909 }
4910
John Kessenichad7645f2018-06-04 19:11:25 -06004911 // Get the conversion operation and result type,
4912 // based on the target width, but the source type.
4913 spv::Id type = spv::NoType;
4914 spv::Op convOp = spv::OpNop;
4915 switch(op) {
4916 case glslang::EOpConvInt8ToUint16:
4917 case glslang::EOpConvInt8ToUint:
4918 case glslang::EOpConvInt8ToUint64:
4919 case glslang::EOpConvInt16ToUint8:
4920 case glslang::EOpConvInt16ToUint:
4921 case glslang::EOpConvInt16ToUint64:
4922 case glslang::EOpConvIntToUint8:
4923 case glslang::EOpConvIntToUint16:
4924 case glslang::EOpConvIntToUint64:
4925 case glslang::EOpConvInt64ToUint8:
4926 case glslang::EOpConvInt64ToUint16:
4927 case glslang::EOpConvInt64ToUint:
4928 convOp = spv::OpSConvert;
4929 type = builder.makeIntType(width);
4930 break;
4931 default:
4932 convOp = spv::OpUConvert;
4933 type = builder.makeUintType(width);
4934 break;
4935 }
4936
John Kessenich66011cb2018-03-06 16:12:04 -07004937 if (vectorSize > 0)
4938 type = builder.makeVectorType(type, vectorSize);
4939
John Kessenichad7645f2018-06-04 19:11:25 -06004940 return builder.createUnaryOp(convOp, type, operand);
John Kessenich66011cb2018-03-06 16:12:04 -07004941}
4942
John Kessenichead86222018-03-28 18:01:20 -06004943spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, OpDecorations& decorations, spv::Id destType,
4944 spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004945{
4946 spv::Op convOp = spv::OpNop;
4947 spv::Id zero = 0;
4948 spv::Id one = 0;
4949
4950 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4951
4952 switch (op) {
John Kessenich66011cb2018-03-06 16:12:04 -07004953 case glslang::EOpConvInt8ToBool:
4954 case glslang::EOpConvUint8ToBool:
4955 zero = builder.makeUint8Constant(0);
4956 zero = makeSmearedConstant(zero, vectorSize);
4957 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
Rex Xucabbb782017-03-24 13:41:14 +08004958 case glslang::EOpConvInt16ToBool:
4959 case glslang::EOpConvUint16ToBool:
John Kessenich66011cb2018-03-06 16:12:04 -07004960 zero = builder.makeUint16Constant(0);
4961 zero = makeSmearedConstant(zero, vectorSize);
4962 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4963 case glslang::EOpConvIntToBool:
4964 case glslang::EOpConvUintToBool:
4965 zero = builder.makeUintConstant(0);
4966 zero = makeSmearedConstant(zero, vectorSize);
4967 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4968 case glslang::EOpConvInt64ToBool:
4969 case glslang::EOpConvUint64ToBool:
4970 zero = builder.makeUint64Constant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004971 zero = makeSmearedConstant(zero, vectorSize);
4972 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4973
4974 case glslang::EOpConvFloatToBool:
4975 zero = builder.makeFloatConstant(0.0F);
4976 zero = makeSmearedConstant(zero, vectorSize);
4977 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4978
4979 case glslang::EOpConvDoubleToBool:
4980 zero = builder.makeDoubleConstant(0.0);
4981 zero = makeSmearedConstant(zero, vectorSize);
4982 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4983
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004984 case glslang::EOpConvFloat16ToBool:
4985 zero = builder.makeFloat16Constant(0.0F);
4986 zero = makeSmearedConstant(zero, vectorSize);
4987 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004988
John Kessenich140f3df2015-06-26 16:58:36 -06004989 case glslang::EOpConvBoolToFloat:
4990 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004991 zero = builder.makeFloatConstant(0.0F);
4992 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004993 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004994
John Kessenich140f3df2015-06-26 16:58:36 -06004995 case glslang::EOpConvBoolToDouble:
4996 convOp = spv::OpSelect;
4997 zero = builder.makeDoubleConstant(0.0);
4998 one = builder.makeDoubleConstant(1.0);
4999 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005000
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005001 case glslang::EOpConvBoolToFloat16:
5002 convOp = spv::OpSelect;
5003 zero = builder.makeFloat16Constant(0.0F);
5004 one = builder.makeFloat16Constant(1.0F);
5005 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005006
5007 case glslang::EOpConvBoolToInt8:
5008 zero = builder.makeInt8Constant(0);
5009 one = builder.makeInt8Constant(1);
5010 convOp = spv::OpSelect;
5011 break;
5012
5013 case glslang::EOpConvBoolToUint8:
5014 zero = builder.makeUint8Constant(0);
5015 one = builder.makeUint8Constant(1);
5016 convOp = spv::OpSelect;
5017 break;
5018
5019 case glslang::EOpConvBoolToInt16:
5020 zero = builder.makeInt16Constant(0);
5021 one = builder.makeInt16Constant(1);
5022 convOp = spv::OpSelect;
5023 break;
5024
5025 case glslang::EOpConvBoolToUint16:
5026 zero = builder.makeUint16Constant(0);
5027 one = builder.makeUint16Constant(1);
5028 convOp = spv::OpSelect;
5029 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005030
John Kessenich140f3df2015-06-26 16:58:36 -06005031 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005032 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005033 if (op == glslang::EOpConvBoolToInt64)
5034 zero = builder.makeInt64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005035 else
5036 zero = builder.makeIntConstant(0);
5037
5038 if (op == glslang::EOpConvBoolToInt64)
5039 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005040 else
5041 one = builder.makeIntConstant(1);
5042
John Kessenich140f3df2015-06-26 16:58:36 -06005043 convOp = spv::OpSelect;
5044 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005045
John Kessenich140f3df2015-06-26 16:58:36 -06005046 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005047 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08005048 if (op == glslang::EOpConvBoolToUint64)
5049 zero = builder.makeUint64Constant(0);
Rex Xucabbb782017-03-24 13:41:14 +08005050 else
5051 zero = builder.makeUintConstant(0);
5052
5053 if (op == glslang::EOpConvBoolToUint64)
5054 one = builder.makeUint64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08005055 else
5056 one = builder.makeUintConstant(1);
5057
John Kessenich140f3df2015-06-26 16:58:36 -06005058 convOp = spv::OpSelect;
5059 break;
5060
John Kessenich66011cb2018-03-06 16:12:04 -07005061 case glslang::EOpConvInt8ToFloat16:
5062 case glslang::EOpConvInt8ToFloat:
5063 case glslang::EOpConvInt8ToDouble:
5064 case glslang::EOpConvInt16ToFloat16:
5065 case glslang::EOpConvInt16ToFloat:
5066 case glslang::EOpConvInt16ToDouble:
5067 case glslang::EOpConvIntToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005068 case glslang::EOpConvIntToFloat:
5069 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005070 case glslang::EOpConvInt64ToFloat:
5071 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005072 case glslang::EOpConvInt64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005073 convOp = spv::OpConvertSToF;
5074 break;
5075
John Kessenich66011cb2018-03-06 16:12:04 -07005076 case glslang::EOpConvUint8ToFloat16:
5077 case glslang::EOpConvUint8ToFloat:
5078 case glslang::EOpConvUint8ToDouble:
5079 case glslang::EOpConvUint16ToFloat16:
5080 case glslang::EOpConvUint16ToFloat:
5081 case glslang::EOpConvUint16ToDouble:
5082 case glslang::EOpConvUintToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005083 case glslang::EOpConvUintToFloat:
5084 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08005085 case glslang::EOpConvUint64ToFloat:
5086 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005087 case glslang::EOpConvUint64ToFloat16:
John Kessenich140f3df2015-06-26 16:58:36 -06005088 convOp = spv::OpConvertUToF;
5089 break;
5090
5091 case glslang::EOpConvDoubleToFloat:
5092 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005093 case glslang::EOpConvDoubleToFloat16:
5094 case glslang::EOpConvFloat16ToDouble:
5095 case glslang::EOpConvFloatToFloat16:
5096 case glslang::EOpConvFloat16ToFloat:
John Kessenich140f3df2015-06-26 16:58:36 -06005097 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08005098 if (builder.isMatrixType(destType))
John Kessenichead86222018-03-28 18:01:20 -06005099 return createUnaryMatrixOperation(convOp, decorations, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06005100 break;
5101
John Kessenich66011cb2018-03-06 16:12:04 -07005102 case glslang::EOpConvFloat16ToInt8:
5103 case glslang::EOpConvFloatToInt8:
5104 case glslang::EOpConvDoubleToInt8:
5105 case glslang::EOpConvFloat16ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005106 case glslang::EOpConvFloatToInt16:
5107 case glslang::EOpConvDoubleToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005108 case glslang::EOpConvFloat16ToInt:
John Kessenich66011cb2018-03-06 16:12:04 -07005109 case glslang::EOpConvFloatToInt:
5110 case glslang::EOpConvDoubleToInt:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005111 case glslang::EOpConvFloat16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005112 case glslang::EOpConvFloatToInt64:
5113 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06005114 convOp = spv::OpConvertFToS;
5115 break;
5116
John Kessenich66011cb2018-03-06 16:12:04 -07005117 case glslang::EOpConvUint8ToInt8:
5118 case glslang::EOpConvInt8ToUint8:
5119 case glslang::EOpConvUint16ToInt16:
5120 case glslang::EOpConvInt16ToUint16:
John Kessenich140f3df2015-06-26 16:58:36 -06005121 case glslang::EOpConvUintToInt:
5122 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005123 case glslang::EOpConvUint64ToInt64:
5124 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04005125 if (builder.isInSpecConstCodeGenMode()) {
5126 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005127 if(op == glslang::EOpConvUint8ToInt8 || op == glslang::EOpConvInt8ToUint8) {
5128 zero = builder.makeUint8Constant(0);
5129 } else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16) {
Rex Xucabbb782017-03-24 13:41:14 +08005130 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005131 } else if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64) {
5132 zero = builder.makeUint64Constant(0);
5133 } else {
Rex Xucabbb782017-03-24 13:41:14 +08005134 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005135 }
qining189b2032016-04-12 23:16:20 -04005136 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04005137 // Use OpIAdd, instead of OpBitcast to do the conversion when
5138 // generating for OpSpecConstantOp instruction.
5139 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5140 }
5141 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06005142 convOp = spv::OpBitcast;
5143 break;
5144
John Kessenich66011cb2018-03-06 16:12:04 -07005145 case glslang::EOpConvFloat16ToUint8:
5146 case glslang::EOpConvFloatToUint8:
5147 case glslang::EOpConvDoubleToUint8:
5148 case glslang::EOpConvFloat16ToUint16:
5149 case glslang::EOpConvFloatToUint16:
5150 case glslang::EOpConvDoubleToUint16:
5151 case glslang::EOpConvFloat16ToUint:
John Kessenich140f3df2015-06-26 16:58:36 -06005152 case glslang::EOpConvFloatToUint:
5153 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005154 case glslang::EOpConvFloatToUint64:
5155 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005156 case glslang::EOpConvFloat16ToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06005157 convOp = spv::OpConvertFToU;
5158 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005159
John Kessenich66011cb2018-03-06 16:12:04 -07005160 case glslang::EOpConvInt8ToInt16:
5161 case glslang::EOpConvInt8ToInt:
5162 case glslang::EOpConvInt8ToInt64:
5163 case glslang::EOpConvInt16ToInt8:
Rex Xucabbb782017-03-24 13:41:14 +08005164 case glslang::EOpConvInt16ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005165 case glslang::EOpConvInt16ToInt64:
John Kessenich66011cb2018-03-06 16:12:04 -07005166 case glslang::EOpConvIntToInt8:
5167 case glslang::EOpConvIntToInt16:
5168 case glslang::EOpConvIntToInt64:
5169 case glslang::EOpConvInt64ToInt8:
5170 case glslang::EOpConvInt64ToInt16:
5171 case glslang::EOpConvInt64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005172 convOp = spv::OpSConvert;
5173 break;
5174
John Kessenich66011cb2018-03-06 16:12:04 -07005175 case glslang::EOpConvUint8ToUint16:
5176 case glslang::EOpConvUint8ToUint:
5177 case glslang::EOpConvUint8ToUint64:
5178 case glslang::EOpConvUint16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005179 case glslang::EOpConvUint16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005180 case glslang::EOpConvUint16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005181 case glslang::EOpConvUintToUint8:
5182 case glslang::EOpConvUintToUint16:
5183 case glslang::EOpConvUintToUint64:
5184 case glslang::EOpConvUint64ToUint8:
5185 case glslang::EOpConvUint64ToUint16:
5186 case glslang::EOpConvUint64ToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08005187 convOp = spv::OpUConvert;
5188 break;
5189
John Kessenich66011cb2018-03-06 16:12:04 -07005190 case glslang::EOpConvInt8ToUint16:
5191 case glslang::EOpConvInt8ToUint:
5192 case glslang::EOpConvInt8ToUint64:
5193 case glslang::EOpConvInt16ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005194 case glslang::EOpConvInt16ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08005195 case glslang::EOpConvInt16ToUint64:
John Kessenich66011cb2018-03-06 16:12:04 -07005196 case glslang::EOpConvIntToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005197 case glslang::EOpConvIntToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005198 case glslang::EOpConvIntToUint64:
5199 case glslang::EOpConvInt64ToUint8:
Rex Xucabbb782017-03-24 13:41:14 +08005200 case glslang::EOpConvInt64ToUint16:
John Kessenich66011cb2018-03-06 16:12:04 -07005201 case glslang::EOpConvInt64ToUint:
5202 case glslang::EOpConvUint8ToInt16:
5203 case glslang::EOpConvUint8ToInt:
5204 case glslang::EOpConvUint8ToInt64:
5205 case glslang::EOpConvUint16ToInt8:
5206 case glslang::EOpConvUint16ToInt:
5207 case glslang::EOpConvUint16ToInt64:
5208 case glslang::EOpConvUintToInt8:
5209 case glslang::EOpConvUintToInt16:
5210 case glslang::EOpConvUintToInt64:
5211 case glslang::EOpConvUint64ToInt8:
5212 case glslang::EOpConvUint64ToInt16:
5213 case glslang::EOpConvUint64ToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08005214 // OpSConvert/OpUConvert + OpBitCast
John Kessenichad7645f2018-06-04 19:11:25 -06005215 operand = createIntWidthConversion(op, operand, vectorSize);
Rex Xu8ff43de2016-04-22 16:51:45 +08005216
5217 if (builder.isInSpecConstCodeGenMode()) {
5218 // Build zero scalar or vector for OpIAdd.
John Kessenich66011cb2018-03-06 16:12:04 -07005219 switch(op) {
5220 case glslang::EOpConvInt16ToUint8:
5221 case glslang::EOpConvIntToUint8:
5222 case glslang::EOpConvInt64ToUint8:
5223 case glslang::EOpConvUint16ToInt8:
5224 case glslang::EOpConvUintToInt8:
5225 case glslang::EOpConvUint64ToInt8:
5226 zero = builder.makeUint8Constant(0);
5227 break;
5228 case glslang::EOpConvInt8ToUint16:
5229 case glslang::EOpConvIntToUint16:
5230 case glslang::EOpConvInt64ToUint16:
5231 case glslang::EOpConvUint8ToInt16:
5232 case glslang::EOpConvUintToInt16:
5233 case glslang::EOpConvUint64ToInt16:
Rex Xucabbb782017-03-24 13:41:14 +08005234 zero = builder.makeUint16Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005235 break;
5236 case glslang::EOpConvInt8ToUint:
5237 case glslang::EOpConvInt16ToUint:
5238 case glslang::EOpConvInt64ToUint:
5239 case glslang::EOpConvUint8ToInt:
5240 case glslang::EOpConvUint16ToInt:
5241 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08005242 zero = builder.makeUintConstant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005243 break;
5244 case glslang::EOpConvInt8ToUint64:
5245 case glslang::EOpConvInt16ToUint64:
5246 case glslang::EOpConvIntToUint64:
5247 case glslang::EOpConvUint8ToInt64:
5248 case glslang::EOpConvUint16ToInt64:
5249 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08005250 zero = builder.makeUint64Constant(0);
John Kessenich66011cb2018-03-06 16:12:04 -07005251 break;
5252 default:
5253 assert(false && "Default missing");
5254 break;
5255 }
Rex Xu8ff43de2016-04-22 16:51:45 +08005256 zero = makeSmearedConstant(zero, vectorSize);
5257 // Use OpIAdd, instead of OpBitcast to do the conversion when
5258 // generating for OpSpecConstantOp instruction.
5259 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
5260 }
5261 // For normal run-time conversion instruction, use OpBitcast.
5262 convOp = spv::OpBitcast;
5263 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005264 default:
5265 break;
5266 }
5267
5268 spv::Id result = 0;
5269 if (convOp == spv::OpNop)
5270 return result;
5271
5272 if (convOp == spv::OpSelect) {
5273 zero = makeSmearedConstant(zero, vectorSize);
5274 one = makeSmearedConstant(one, vectorSize);
5275 result = builder.createTriOp(convOp, destType, operand, one, zero);
5276 } else
5277 result = builder.createUnaryOp(convOp, destType, operand);
5278
John Kessenichead86222018-03-28 18:01:20 -06005279 result = builder.setPrecision(result, decorations.precision);
John Kessenich5611c6d2018-04-05 11:25:02 -06005280 builder.addDecoration(result, decorations.nonUniform);
John Kessenichead86222018-03-28 18:01:20 -06005281 return result;
John Kessenich140f3df2015-06-26 16:58:36 -06005282}
5283
5284spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
5285{
5286 if (vectorSize == 0)
5287 return constant;
5288
5289 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
5290 std::vector<spv::Id> components;
5291 for (int c = 0; c < vectorSize; ++c)
5292 components.push_back(constant);
5293 return builder.makeCompositeConstant(vectorTypeId, components);
5294}
5295
John Kessenich426394d2015-07-23 10:22:48 -06005296// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07005297spv::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 -06005298{
5299 spv::Op opCode = spv::OpNop;
5300
5301 switch (op) {
5302 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08005303 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005304 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06005305 opCode = spv::OpAtomicIAdd;
5306 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06005307 case glslang::EOpAtomicCounterSubtract:
5308 opCode = spv::OpAtomicISub;
5309 break;
John Kessenich426394d2015-07-23 10:22:48 -06005310 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08005311 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005312 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08005313 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06005314 break;
5315 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08005316 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005317 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08005318 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06005319 break;
5320 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08005321 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005322 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06005323 opCode = spv::OpAtomicAnd;
5324 break;
5325 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08005326 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005327 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06005328 opCode = spv::OpAtomicOr;
5329 break;
5330 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08005331 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005332 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06005333 opCode = spv::OpAtomicXor;
5334 break;
5335 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08005336 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005337 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06005338 opCode = spv::OpAtomicExchange;
5339 break;
5340 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08005341 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06005342 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06005343 opCode = spv::OpAtomicCompareExchange;
5344 break;
5345 case glslang::EOpAtomicCounterIncrement:
5346 opCode = spv::OpAtomicIIncrement;
5347 break;
5348 case glslang::EOpAtomicCounterDecrement:
5349 opCode = spv::OpAtomicIDecrement;
5350 break;
5351 case glslang::EOpAtomicCounter:
5352 opCode = spv::OpAtomicLoad;
5353 break;
5354 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005355 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06005356 break;
5357 }
5358
Rex Xue8fe8b02017-09-26 15:42:56 +08005359 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
5360 builder.addCapability(spv::CapabilityInt64Atomics);
5361
John Kessenich426394d2015-07-23 10:22:48 -06005362 // Sort out the operands
5363 // - mapping from glslang -> SPV
5364 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06005365 // - compare-exchange swaps the value and comparator
5366 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06005367 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06005368 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
5369 auto opIt = operands.begin(); // walk the glslang operands
5370 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08005371 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
5372 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
5373 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08005374 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
5375 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08005376 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06005377 spvAtomicOperands.push_back(*(opIt + 1));
5378 spvAtomicOperands.push_back(*opIt);
5379 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08005380 }
John Kessenich426394d2015-07-23 10:22:48 -06005381
John Kessenich3e60a6f2015-09-14 22:45:16 -06005382 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06005383 for (; opIt != operands.end(); ++opIt)
5384 spvAtomicOperands.push_back(*opIt);
5385
John Kessenich48d6e792017-10-06 21:21:48 -06005386 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
5387
5388 // GLSL and HLSL atomic-counter decrement return post-decrement value,
5389 // while SPIR-V returns pre-decrement value. Translate between these semantics.
5390 if (op == glslang::EOpAtomicCounterDecrement)
5391 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
5392
5393 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06005394}
5395
John Kessenich91cef522016-05-05 16:45:40 -06005396// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08005397spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06005398{
Corentin Walleze7061422018-08-08 15:20:15 +02005399#ifdef AMD_EXTENSIONS
John Kessenich66011cb2018-03-06 16:12:04 -07005400 bool isUnsigned = isTypeUnsignedInt(typeProxy);
5401 bool isFloat = isTypeFloat(typeProxy);
Corentin Walleze7061422018-08-08 15:20:15 +02005402#endif
Rex Xu9d93a232016-05-05 12:30:44 +08005403
Rex Xu51596642016-09-21 18:56:12 +08005404 spv::Op opCode = spv::OpNop;
John Kessenich149afc32018-08-14 13:31:43 -06005405 std::vector<spv::IdImmediate> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08005406 spv::GroupOperation groupOperation = spv::GroupOperationMax;
5407
chaocf200da82016-12-20 12:44:35 -08005408 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
5409 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08005410 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
5411 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005412 } else if (op == glslang::EOpAnyInvocation ||
5413 op == glslang::EOpAllInvocations ||
5414 op == glslang::EOpAllInvocationsEqual) {
5415 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
5416 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08005417 } else {
5418 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04005419#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08005420 if (op == glslang::EOpMinInvocationsNonUniform ||
5421 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08005422 op == glslang::EOpAddInvocationsNonUniform ||
5423 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5424 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5425 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
5426 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
5427 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
5428 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08005429 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04005430#endif
Rex Xu51596642016-09-21 18:56:12 +08005431
Rex Xu9d93a232016-05-05 12:30:44 +08005432#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08005433 switch (op) {
5434 case glslang::EOpMinInvocations:
5435 case glslang::EOpMaxInvocations:
5436 case glslang::EOpAddInvocations:
5437 case glslang::EOpMinInvocationsNonUniform:
5438 case glslang::EOpMaxInvocationsNonUniform:
5439 case glslang::EOpAddInvocationsNonUniform:
5440 groupOperation = spv::GroupOperationReduce;
Rex Xu430ef402016-10-14 17:22:23 +08005441 break;
5442 case glslang::EOpMinInvocationsInclusiveScan:
5443 case glslang::EOpMaxInvocationsInclusiveScan:
5444 case glslang::EOpAddInvocationsInclusiveScan:
5445 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5446 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5447 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5448 groupOperation = spv::GroupOperationInclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005449 break;
5450 case glslang::EOpMinInvocationsExclusiveScan:
5451 case glslang::EOpMaxInvocationsExclusiveScan:
5452 case glslang::EOpAddInvocationsExclusiveScan:
5453 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5454 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5455 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5456 groupOperation = spv::GroupOperationExclusiveScan;
Rex Xu430ef402016-10-14 17:22:23 +08005457 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07005458 default:
5459 break;
Rex Xu430ef402016-10-14 17:22:23 +08005460 }
John Kessenich149afc32018-08-14 13:31:43 -06005461 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5462 spvGroupOperands.push_back(scope);
5463 if (groupOperation != spv::GroupOperationMax) {
5464 spv::IdImmediate groupOp = { false, groupOperation };
5465 spvGroupOperands.push_back(groupOp);
5466 }
Rex Xu9d93a232016-05-05 12:30:44 +08005467#endif
Rex Xu51596642016-09-21 18:56:12 +08005468 }
5469
John Kessenich149afc32018-08-14 13:31:43 -06005470 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt) {
5471 spv::IdImmediate op = { true, *opIt };
5472 spvGroupOperands.push_back(op);
5473 }
John Kessenich91cef522016-05-05 16:45:40 -06005474
5475 switch (op) {
5476 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005477 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08005478 break;
John Kessenich91cef522016-05-05 16:45:40 -06005479 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005480 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08005481 break;
John Kessenich91cef522016-05-05 16:45:40 -06005482 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08005483 opCode = spv::OpSubgroupAllEqualKHR;
5484 break;
Rex Xu51596642016-09-21 18:56:12 +08005485 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08005486 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08005487 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005488 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005489 break;
5490 case glslang::EOpReadFirstInvocation:
5491 opCode = spv::OpSubgroupFirstInvocationKHR;
5492 break;
5493 case glslang::EOpBallot:
5494 {
5495 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
5496 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
5497 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
5498 //
5499 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
5500 //
5501 spv::Id uintType = builder.makeUintType(32);
5502 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
5503 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
5504
5505 std::vector<spv::Id> components;
5506 components.push_back(builder.createCompositeExtract(result, uintType, 0));
5507 components.push_back(builder.createCompositeExtract(result, uintType, 1));
5508
5509 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
5510 return builder.createUnaryOp(spv::OpBitcast, typeId,
5511 builder.createCompositeConstruct(uvec2Type, components));
5512 }
5513
Rex Xu9d93a232016-05-05 12:30:44 +08005514#ifdef AMD_EXTENSIONS
5515 case glslang::EOpMinInvocations:
5516 case glslang::EOpMaxInvocations:
5517 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005518 case glslang::EOpMinInvocationsInclusiveScan:
5519 case glslang::EOpMaxInvocationsInclusiveScan:
5520 case glslang::EOpAddInvocationsInclusiveScan:
5521 case glslang::EOpMinInvocationsExclusiveScan:
5522 case glslang::EOpMaxInvocationsExclusiveScan:
5523 case glslang::EOpAddInvocationsExclusiveScan:
5524 if (op == glslang::EOpMinInvocations ||
5525 op == glslang::EOpMinInvocationsInclusiveScan ||
5526 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005527 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005528 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005529 else {
5530 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005531 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005532 else
Rex Xu51596642016-09-21 18:56:12 +08005533 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005534 }
Rex Xu430ef402016-10-14 17:22:23 +08005535 } else if (op == glslang::EOpMaxInvocations ||
5536 op == glslang::EOpMaxInvocationsInclusiveScan ||
5537 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005538 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005539 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005540 else {
5541 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005542 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005543 else
Rex Xu51596642016-09-21 18:56:12 +08005544 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005545 }
5546 } else {
5547 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005548 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005549 else
Rex Xu51596642016-09-21 18:56:12 +08005550 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005551 }
5552
Rex Xu2bbbe062016-08-23 15:41:05 +08005553 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005554 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005555
5556 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005557 case glslang::EOpMinInvocationsNonUniform:
5558 case glslang::EOpMaxInvocationsNonUniform:
5559 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005560 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5561 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5562 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5563 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5564 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5565 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5566 if (op == glslang::EOpMinInvocationsNonUniform ||
5567 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5568 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005569 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005570 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005571 else {
5572 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005573 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005574 else
Rex Xu51596642016-09-21 18:56:12 +08005575 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005576 }
5577 }
Rex Xu430ef402016-10-14 17:22:23 +08005578 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5579 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5580 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005581 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005582 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005583 else {
5584 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005585 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005586 else
Rex Xu51596642016-09-21 18:56:12 +08005587 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005588 }
5589 }
5590 else {
5591 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005592 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005593 else
Rex Xu51596642016-09-21 18:56:12 +08005594 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005595 }
5596
Rex Xu2bbbe062016-08-23 15:41:05 +08005597 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005598 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005599
5600 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005601#endif
John Kessenich91cef522016-05-05 16:45:40 -06005602 default:
5603 logger->missingFunctionality("invocation operation");
5604 return spv::NoResult;
5605 }
Rex Xu51596642016-09-21 18:56:12 +08005606
5607 assert(opCode != spv::OpNop);
5608 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005609}
5610
Rex Xu2bbbe062016-08-23 15:41:05 +08005611// Create group invocation operations on a vector
John Kessenich149afc32018-08-14 13:31:43 -06005612spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation,
5613 spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005614{
Rex Xub7072052016-09-26 15:53:40 +08005615#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005616 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5617 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005618 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005619 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005620 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5621 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5622 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005623#else
5624 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5625 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005626 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5627 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005628#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005629
5630 // Handle group invocation operations scalar by scalar.
5631 // The result type is the same type as the original type.
5632 // The algorithm is to:
5633 // - break the vector into scalars
5634 // - apply the operation to each scalar
5635 // - make a vector out the scalar results
5636
5637 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005638 int numComponents = builder.getNumComponents(operands[0]);
5639 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005640 std::vector<spv::Id> results;
5641
5642 // do each scalar op
5643 for (int comp = 0; comp < numComponents; ++comp) {
5644 std::vector<unsigned int> indexes;
5645 indexes.push_back(comp);
John Kessenich149afc32018-08-14 13:31:43 -06005646 spv::IdImmediate scalar = { true, builder.createCompositeExtract(operands[0], scalarType, indexes) };
5647 std::vector<spv::IdImmediate> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005648 if (op == spv::OpSubgroupReadInvocationKHR) {
5649 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06005650 spv::IdImmediate operand = { true, operands[1] };
5651 spvGroupOperands.push_back(operand);
chaocf200da82016-12-20 12:44:35 -08005652 } else if (op == spv::OpGroupBroadcast) {
John Kessenich149afc32018-08-14 13:31:43 -06005653 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5654 spvGroupOperands.push_back(scope);
Rex Xub7072052016-09-26 15:53:40 +08005655 spvGroupOperands.push_back(scalar);
John Kessenich149afc32018-08-14 13:31:43 -06005656 spv::IdImmediate operand = { true, operands[1] };
5657 spvGroupOperands.push_back(operand);
Rex Xub7072052016-09-26 15:53:40 +08005658 } else {
John Kessenich149afc32018-08-14 13:31:43 -06005659 spv::IdImmediate scope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
5660 spvGroupOperands.push_back(scope);
5661 spv::IdImmediate groupOp = { false, groupOperation };
5662 spvGroupOperands.push_back(groupOp);
Rex Xub7072052016-09-26 15:53:40 +08005663 spvGroupOperands.push_back(scalar);
5664 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005665
Rex Xub7072052016-09-26 15:53:40 +08005666 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005667 }
5668
5669 // put the pieces together
5670 return builder.createCompositeConstruct(typeId, results);
5671}
Rex Xu2bbbe062016-08-23 15:41:05 +08005672
John Kessenich66011cb2018-03-06 16:12:04 -07005673// Create subgroup invocation operations.
John Kessenich149afc32018-08-14 13:31:43 -06005674spv::Id TGlslangToSpvTraverser::createSubgroupOperation(glslang::TOperator op, spv::Id typeId,
5675 std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich66011cb2018-03-06 16:12:04 -07005676{
5677 // Add the required capabilities.
5678 switch (op) {
5679 case glslang::EOpSubgroupElect:
5680 builder.addCapability(spv::CapabilityGroupNonUniform);
5681 break;
5682 case glslang::EOpSubgroupAll:
5683 case glslang::EOpSubgroupAny:
5684 case glslang::EOpSubgroupAllEqual:
5685 builder.addCapability(spv::CapabilityGroupNonUniform);
5686 builder.addCapability(spv::CapabilityGroupNonUniformVote);
5687 break;
5688 case glslang::EOpSubgroupBroadcast:
5689 case glslang::EOpSubgroupBroadcastFirst:
5690 case glslang::EOpSubgroupBallot:
5691 case glslang::EOpSubgroupInverseBallot:
5692 case glslang::EOpSubgroupBallotBitExtract:
5693 case glslang::EOpSubgroupBallotBitCount:
5694 case glslang::EOpSubgroupBallotInclusiveBitCount:
5695 case glslang::EOpSubgroupBallotExclusiveBitCount:
5696 case glslang::EOpSubgroupBallotFindLSB:
5697 case glslang::EOpSubgroupBallotFindMSB:
5698 builder.addCapability(spv::CapabilityGroupNonUniform);
5699 builder.addCapability(spv::CapabilityGroupNonUniformBallot);
5700 break;
5701 case glslang::EOpSubgroupShuffle:
5702 case glslang::EOpSubgroupShuffleXor:
5703 builder.addCapability(spv::CapabilityGroupNonUniform);
5704 builder.addCapability(spv::CapabilityGroupNonUniformShuffle);
5705 break;
5706 case glslang::EOpSubgroupShuffleUp:
5707 case glslang::EOpSubgroupShuffleDown:
5708 builder.addCapability(spv::CapabilityGroupNonUniform);
5709 builder.addCapability(spv::CapabilityGroupNonUniformShuffleRelative);
5710 break;
5711 case glslang::EOpSubgroupAdd:
5712 case glslang::EOpSubgroupMul:
5713 case glslang::EOpSubgroupMin:
5714 case glslang::EOpSubgroupMax:
5715 case glslang::EOpSubgroupAnd:
5716 case glslang::EOpSubgroupOr:
5717 case glslang::EOpSubgroupXor:
5718 case glslang::EOpSubgroupInclusiveAdd:
5719 case glslang::EOpSubgroupInclusiveMul:
5720 case glslang::EOpSubgroupInclusiveMin:
5721 case glslang::EOpSubgroupInclusiveMax:
5722 case glslang::EOpSubgroupInclusiveAnd:
5723 case glslang::EOpSubgroupInclusiveOr:
5724 case glslang::EOpSubgroupInclusiveXor:
5725 case glslang::EOpSubgroupExclusiveAdd:
5726 case glslang::EOpSubgroupExclusiveMul:
5727 case glslang::EOpSubgroupExclusiveMin:
5728 case glslang::EOpSubgroupExclusiveMax:
5729 case glslang::EOpSubgroupExclusiveAnd:
5730 case glslang::EOpSubgroupExclusiveOr:
5731 case glslang::EOpSubgroupExclusiveXor:
5732 builder.addCapability(spv::CapabilityGroupNonUniform);
5733 builder.addCapability(spv::CapabilityGroupNonUniformArithmetic);
5734 break;
5735 case glslang::EOpSubgroupClusteredAdd:
5736 case glslang::EOpSubgroupClusteredMul:
5737 case glslang::EOpSubgroupClusteredMin:
5738 case glslang::EOpSubgroupClusteredMax:
5739 case glslang::EOpSubgroupClusteredAnd:
5740 case glslang::EOpSubgroupClusteredOr:
5741 case glslang::EOpSubgroupClusteredXor:
5742 builder.addCapability(spv::CapabilityGroupNonUniform);
5743 builder.addCapability(spv::CapabilityGroupNonUniformClustered);
5744 break;
5745 case glslang::EOpSubgroupQuadBroadcast:
5746 case glslang::EOpSubgroupQuadSwapHorizontal:
5747 case glslang::EOpSubgroupQuadSwapVertical:
5748 case glslang::EOpSubgroupQuadSwapDiagonal:
5749 builder.addCapability(spv::CapabilityGroupNonUniform);
5750 builder.addCapability(spv::CapabilityGroupNonUniformQuad);
5751 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005752#ifdef NV_EXTENSIONS
5753 case glslang::EOpSubgroupPartitionedAdd:
5754 case glslang::EOpSubgroupPartitionedMul:
5755 case glslang::EOpSubgroupPartitionedMin:
5756 case glslang::EOpSubgroupPartitionedMax:
5757 case glslang::EOpSubgroupPartitionedAnd:
5758 case glslang::EOpSubgroupPartitionedOr:
5759 case glslang::EOpSubgroupPartitionedXor:
5760 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5761 case glslang::EOpSubgroupPartitionedInclusiveMul:
5762 case glslang::EOpSubgroupPartitionedInclusiveMin:
5763 case glslang::EOpSubgroupPartitionedInclusiveMax:
5764 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5765 case glslang::EOpSubgroupPartitionedInclusiveOr:
5766 case glslang::EOpSubgroupPartitionedInclusiveXor:
5767 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5768 case glslang::EOpSubgroupPartitionedExclusiveMul:
5769 case glslang::EOpSubgroupPartitionedExclusiveMin:
5770 case glslang::EOpSubgroupPartitionedExclusiveMax:
5771 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5772 case glslang::EOpSubgroupPartitionedExclusiveOr:
5773 case glslang::EOpSubgroupPartitionedExclusiveXor:
5774 builder.addExtension(spv::E_SPV_NV_shader_subgroup_partitioned);
5775 builder.addCapability(spv::CapabilityGroupNonUniformPartitionedNV);
5776 break;
5777#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005778 default: assert(0 && "Unhandled subgroup operation!");
5779 }
5780
5781 const bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
5782 const bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
5783 const bool isBool = typeProxy == glslang::EbtBool;
5784
5785 spv::Op opCode = spv::OpNop;
5786
5787 // Figure out which opcode to use.
5788 switch (op) {
5789 case glslang::EOpSubgroupElect: opCode = spv::OpGroupNonUniformElect; break;
5790 case glslang::EOpSubgroupAll: opCode = spv::OpGroupNonUniformAll; break;
5791 case glslang::EOpSubgroupAny: opCode = spv::OpGroupNonUniformAny; break;
5792 case glslang::EOpSubgroupAllEqual: opCode = spv::OpGroupNonUniformAllEqual; break;
5793 case glslang::EOpSubgroupBroadcast: opCode = spv::OpGroupNonUniformBroadcast; break;
5794 case glslang::EOpSubgroupBroadcastFirst: opCode = spv::OpGroupNonUniformBroadcastFirst; break;
5795 case glslang::EOpSubgroupBallot: opCode = spv::OpGroupNonUniformBallot; break;
5796 case glslang::EOpSubgroupInverseBallot: opCode = spv::OpGroupNonUniformInverseBallot; break;
5797 case glslang::EOpSubgroupBallotBitExtract: opCode = spv::OpGroupNonUniformBallotBitExtract; break;
5798 case glslang::EOpSubgroupBallotBitCount:
5799 case glslang::EOpSubgroupBallotInclusiveBitCount:
5800 case glslang::EOpSubgroupBallotExclusiveBitCount: opCode = spv::OpGroupNonUniformBallotBitCount; break;
5801 case glslang::EOpSubgroupBallotFindLSB: opCode = spv::OpGroupNonUniformBallotFindLSB; break;
5802 case glslang::EOpSubgroupBallotFindMSB: opCode = spv::OpGroupNonUniformBallotFindMSB; break;
5803 case glslang::EOpSubgroupShuffle: opCode = spv::OpGroupNonUniformShuffle; break;
5804 case glslang::EOpSubgroupShuffleXor: opCode = spv::OpGroupNonUniformShuffleXor; break;
5805 case glslang::EOpSubgroupShuffleUp: opCode = spv::OpGroupNonUniformShuffleUp; break;
5806 case glslang::EOpSubgroupShuffleDown: opCode = spv::OpGroupNonUniformShuffleDown; break;
5807 case glslang::EOpSubgroupAdd:
5808 case glslang::EOpSubgroupInclusiveAdd:
5809 case glslang::EOpSubgroupExclusiveAdd:
5810 case glslang::EOpSubgroupClusteredAdd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005811#ifdef NV_EXTENSIONS
5812 case glslang::EOpSubgroupPartitionedAdd:
5813 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5814 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5815#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005816 if (isFloat) {
5817 opCode = spv::OpGroupNonUniformFAdd;
5818 } else {
5819 opCode = spv::OpGroupNonUniformIAdd;
5820 }
5821 break;
5822 case glslang::EOpSubgroupMul:
5823 case glslang::EOpSubgroupInclusiveMul:
5824 case glslang::EOpSubgroupExclusiveMul:
5825 case glslang::EOpSubgroupClusteredMul:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005826#ifdef NV_EXTENSIONS
5827 case glslang::EOpSubgroupPartitionedMul:
5828 case glslang::EOpSubgroupPartitionedInclusiveMul:
5829 case glslang::EOpSubgroupPartitionedExclusiveMul:
5830#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005831 if (isFloat) {
5832 opCode = spv::OpGroupNonUniformFMul;
5833 } else {
5834 opCode = spv::OpGroupNonUniformIMul;
5835 }
5836 break;
5837 case glslang::EOpSubgroupMin:
5838 case glslang::EOpSubgroupInclusiveMin:
5839 case glslang::EOpSubgroupExclusiveMin:
5840 case glslang::EOpSubgroupClusteredMin:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005841#ifdef NV_EXTENSIONS
5842 case glslang::EOpSubgroupPartitionedMin:
5843 case glslang::EOpSubgroupPartitionedInclusiveMin:
5844 case glslang::EOpSubgroupPartitionedExclusiveMin:
5845#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005846 if (isFloat) {
5847 opCode = spv::OpGroupNonUniformFMin;
5848 } else if (isUnsigned) {
5849 opCode = spv::OpGroupNonUniformUMin;
5850 } else {
5851 opCode = spv::OpGroupNonUniformSMin;
5852 }
5853 break;
5854 case glslang::EOpSubgroupMax:
5855 case glslang::EOpSubgroupInclusiveMax:
5856 case glslang::EOpSubgroupExclusiveMax:
5857 case glslang::EOpSubgroupClusteredMax:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005858#ifdef NV_EXTENSIONS
5859 case glslang::EOpSubgroupPartitionedMax:
5860 case glslang::EOpSubgroupPartitionedInclusiveMax:
5861 case glslang::EOpSubgroupPartitionedExclusiveMax:
5862#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005863 if (isFloat) {
5864 opCode = spv::OpGroupNonUniformFMax;
5865 } else if (isUnsigned) {
5866 opCode = spv::OpGroupNonUniformUMax;
5867 } else {
5868 opCode = spv::OpGroupNonUniformSMax;
5869 }
5870 break;
5871 case glslang::EOpSubgroupAnd:
5872 case glslang::EOpSubgroupInclusiveAnd:
5873 case glslang::EOpSubgroupExclusiveAnd:
5874 case glslang::EOpSubgroupClusteredAnd:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005875#ifdef NV_EXTENSIONS
5876 case glslang::EOpSubgroupPartitionedAnd:
5877 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5878 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5879#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005880 if (isBool) {
5881 opCode = spv::OpGroupNonUniformLogicalAnd;
5882 } else {
5883 opCode = spv::OpGroupNonUniformBitwiseAnd;
5884 }
5885 break;
5886 case glslang::EOpSubgroupOr:
5887 case glslang::EOpSubgroupInclusiveOr:
5888 case glslang::EOpSubgroupExclusiveOr:
5889 case glslang::EOpSubgroupClusteredOr:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005890#ifdef NV_EXTENSIONS
5891 case glslang::EOpSubgroupPartitionedOr:
5892 case glslang::EOpSubgroupPartitionedInclusiveOr:
5893 case glslang::EOpSubgroupPartitionedExclusiveOr:
5894#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005895 if (isBool) {
5896 opCode = spv::OpGroupNonUniformLogicalOr;
5897 } else {
5898 opCode = spv::OpGroupNonUniformBitwiseOr;
5899 }
5900 break;
5901 case glslang::EOpSubgroupXor:
5902 case glslang::EOpSubgroupInclusiveXor:
5903 case glslang::EOpSubgroupExclusiveXor:
5904 case glslang::EOpSubgroupClusteredXor:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005905#ifdef NV_EXTENSIONS
5906 case glslang::EOpSubgroupPartitionedXor:
5907 case glslang::EOpSubgroupPartitionedInclusiveXor:
5908 case glslang::EOpSubgroupPartitionedExclusiveXor:
5909#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005910 if (isBool) {
5911 opCode = spv::OpGroupNonUniformLogicalXor;
5912 } else {
5913 opCode = spv::OpGroupNonUniformBitwiseXor;
5914 }
5915 break;
5916 case glslang::EOpSubgroupQuadBroadcast: opCode = spv::OpGroupNonUniformQuadBroadcast; break;
5917 case glslang::EOpSubgroupQuadSwapHorizontal:
5918 case glslang::EOpSubgroupQuadSwapVertical:
5919 case glslang::EOpSubgroupQuadSwapDiagonal: opCode = spv::OpGroupNonUniformQuadSwap; break;
5920 default: assert(0 && "Unhandled subgroup operation!");
5921 }
5922
John Kessenich149afc32018-08-14 13:31:43 -06005923 // get the right Group Operation
5924 spv::GroupOperation groupOperation = spv::GroupOperationMax;
John Kessenich66011cb2018-03-06 16:12:04 -07005925 switch (op) {
John Kessenich149afc32018-08-14 13:31:43 -06005926 default:
5927 break;
John Kessenich66011cb2018-03-06 16:12:04 -07005928 case glslang::EOpSubgroupBallotBitCount:
5929 case glslang::EOpSubgroupAdd:
5930 case glslang::EOpSubgroupMul:
5931 case glslang::EOpSubgroupMin:
5932 case glslang::EOpSubgroupMax:
5933 case glslang::EOpSubgroupAnd:
5934 case glslang::EOpSubgroupOr:
5935 case glslang::EOpSubgroupXor:
John Kessenich149afc32018-08-14 13:31:43 -06005936 groupOperation = spv::GroupOperationReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07005937 break;
5938 case glslang::EOpSubgroupBallotInclusiveBitCount:
5939 case glslang::EOpSubgroupInclusiveAdd:
5940 case glslang::EOpSubgroupInclusiveMul:
5941 case glslang::EOpSubgroupInclusiveMin:
5942 case glslang::EOpSubgroupInclusiveMax:
5943 case glslang::EOpSubgroupInclusiveAnd:
5944 case glslang::EOpSubgroupInclusiveOr:
5945 case glslang::EOpSubgroupInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06005946 groupOperation = spv::GroupOperationInclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07005947 break;
5948 case glslang::EOpSubgroupBallotExclusiveBitCount:
5949 case glslang::EOpSubgroupExclusiveAdd:
5950 case glslang::EOpSubgroupExclusiveMul:
5951 case glslang::EOpSubgroupExclusiveMin:
5952 case glslang::EOpSubgroupExclusiveMax:
5953 case glslang::EOpSubgroupExclusiveAnd:
5954 case glslang::EOpSubgroupExclusiveOr:
5955 case glslang::EOpSubgroupExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06005956 groupOperation = spv::GroupOperationExclusiveScan;
John Kessenich66011cb2018-03-06 16:12:04 -07005957 break;
5958 case glslang::EOpSubgroupClusteredAdd:
5959 case glslang::EOpSubgroupClusteredMul:
5960 case glslang::EOpSubgroupClusteredMin:
5961 case glslang::EOpSubgroupClusteredMax:
5962 case glslang::EOpSubgroupClusteredAnd:
5963 case glslang::EOpSubgroupClusteredOr:
5964 case glslang::EOpSubgroupClusteredXor:
John Kessenich149afc32018-08-14 13:31:43 -06005965 groupOperation = spv::GroupOperationClusteredReduce;
John Kessenich66011cb2018-03-06 16:12:04 -07005966 break;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005967#ifdef NV_EXTENSIONS
5968 case glslang::EOpSubgroupPartitionedAdd:
5969 case glslang::EOpSubgroupPartitionedMul:
5970 case glslang::EOpSubgroupPartitionedMin:
5971 case glslang::EOpSubgroupPartitionedMax:
5972 case glslang::EOpSubgroupPartitionedAnd:
5973 case glslang::EOpSubgroupPartitionedOr:
5974 case glslang::EOpSubgroupPartitionedXor:
John Kessenich149afc32018-08-14 13:31:43 -06005975 groupOperation = spv::GroupOperationPartitionedReduceNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005976 break;
5977 case glslang::EOpSubgroupPartitionedInclusiveAdd:
5978 case glslang::EOpSubgroupPartitionedInclusiveMul:
5979 case glslang::EOpSubgroupPartitionedInclusiveMin:
5980 case glslang::EOpSubgroupPartitionedInclusiveMax:
5981 case glslang::EOpSubgroupPartitionedInclusiveAnd:
5982 case glslang::EOpSubgroupPartitionedInclusiveOr:
5983 case glslang::EOpSubgroupPartitionedInclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06005984 groupOperation = spv::GroupOperationPartitionedInclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005985 break;
5986 case glslang::EOpSubgroupPartitionedExclusiveAdd:
5987 case glslang::EOpSubgroupPartitionedExclusiveMul:
5988 case glslang::EOpSubgroupPartitionedExclusiveMin:
5989 case glslang::EOpSubgroupPartitionedExclusiveMax:
5990 case glslang::EOpSubgroupPartitionedExclusiveAnd:
5991 case glslang::EOpSubgroupPartitionedExclusiveOr:
5992 case glslang::EOpSubgroupPartitionedExclusiveXor:
John Kessenich149afc32018-08-14 13:31:43 -06005993 groupOperation = spv::GroupOperationPartitionedExclusiveScanNV;
Jeff Bolz2abe9a42018-03-29 22:52:17 -05005994 break;
5995#endif
John Kessenich66011cb2018-03-06 16:12:04 -07005996 }
5997
John Kessenich149afc32018-08-14 13:31:43 -06005998 // build the instruction
5999 std::vector<spv::IdImmediate> spvGroupOperands;
6000
6001 // Every operation begins with the Execution Scope operand.
6002 spv::IdImmediate executionScope = { true, builder.makeUintConstant(spv::ScopeSubgroup) };
6003 spvGroupOperands.push_back(executionScope);
6004
6005 // Next, for all operations that use a Group Operation, push that as an operand.
6006 if (groupOperation != spv::GroupOperationMax) {
6007 spv::IdImmediate groupOperand = { false, groupOperation };
6008 spvGroupOperands.push_back(groupOperand);
6009 }
6010
John Kessenich66011cb2018-03-06 16:12:04 -07006011 // Push back the operands next.
John Kessenich149afc32018-08-14 13:31:43 -06006012 for (auto opIt = operands.cbegin(); opIt != operands.cend(); ++opIt) {
6013 spv::IdImmediate operand = { true, *opIt };
6014 spvGroupOperands.push_back(operand);
John Kessenich66011cb2018-03-06 16:12:04 -07006015 }
6016
6017 // Some opcodes have additional operands.
John Kessenich149afc32018-08-14 13:31:43 -06006018 spv::Id directionId = spv::NoResult;
John Kessenich66011cb2018-03-06 16:12:04 -07006019 switch (op) {
6020 default: break;
John Kessenich149afc32018-08-14 13:31:43 -06006021 case glslang::EOpSubgroupQuadSwapHorizontal: directionId = builder.makeUintConstant(0); break;
6022 case glslang::EOpSubgroupQuadSwapVertical: directionId = builder.makeUintConstant(1); break;
6023 case glslang::EOpSubgroupQuadSwapDiagonal: directionId = builder.makeUintConstant(2); break;
6024 }
6025 if (directionId != spv::NoResult) {
6026 spv::IdImmediate direction = { true, directionId };
6027 spvGroupOperands.push_back(direction);
John Kessenich66011cb2018-03-06 16:12:04 -07006028 }
6029
6030 return builder.createOp(opCode, typeId, spvGroupOperands);
6031}
6032
John Kessenich5e4b1242015-08-06 22:53:06 -06006033spv::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 -06006034{
John Kessenich66011cb2018-03-06 16:12:04 -07006035 bool isUnsigned = isTypeUnsignedInt(typeProxy);
6036 bool isFloat = isTypeFloat(typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -06006037
John Kessenich140f3df2015-06-26 16:58:36 -06006038 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08006039 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06006040 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05006041 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07006042 spv::Id typeId0 = 0;
6043 if (consumedOperands > 0)
6044 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08006045 spv::Id typeId1 = 0;
6046 if (consumedOperands > 1)
6047 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07006048 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06006049
6050 switch (op) {
6051 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06006052 if (isFloat)
6053 libCall = spv::GLSLstd450FMin;
6054 else if (isUnsigned)
6055 libCall = spv::GLSLstd450UMin;
6056 else
6057 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006058 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006059 break;
6060 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06006061 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06006062 break;
6063 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06006064 if (isFloat)
6065 libCall = spv::GLSLstd450FMax;
6066 else if (isUnsigned)
6067 libCall = spv::GLSLstd450UMax;
6068 else
6069 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006070 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006071 break;
6072 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06006073 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06006074 break;
6075 case glslang::EOpDot:
6076 opCode = spv::OpDot;
6077 break;
6078 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06006079 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06006080 break;
6081
6082 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06006083 if (isFloat)
6084 libCall = spv::GLSLstd450FClamp;
6085 else if (isUnsigned)
6086 libCall = spv::GLSLstd450UClamp;
6087 else
6088 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006089 builder.promoteScalar(precision, operands.front(), operands[1]);
6090 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006091 break;
6092 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08006093 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
6094 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07006095 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08006096 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07006097 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08006098 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07006099 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07006100 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006101 break;
6102 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006103 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006104 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06006105 break;
6106 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06006107 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07006108 builder.promoteScalar(precision, operands[0], operands[2]);
6109 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06006110 break;
6111
6112 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06006113 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06006114 break;
6115 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06006116 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06006117 break;
6118 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06006119 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06006120 break;
6121 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06006122 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06006123 break;
6124 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06006125 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06006126 break;
Rex Xu7a26c172015-12-08 17:12:09 +08006127 case glslang::EOpInterpolateAtSample:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006128#ifdef AMD_EXTENSIONS
6129 if (typeProxy == glslang::EbtFloat16)
6130 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6131#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006132 libCall = spv::GLSLstd450InterpolateAtSample;
6133 break;
6134 case glslang::EOpInterpolateAtOffset:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006135#ifdef AMD_EXTENSIONS
6136 if (typeProxy == glslang::EbtFloat16)
6137 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
6138#endif
Rex Xu7a26c172015-12-08 17:12:09 +08006139 libCall = spv::GLSLstd450InterpolateAtOffset;
6140 break;
John Kessenich55e7d112015-11-15 21:33:39 -07006141 case glslang::EOpAddCarry:
6142 opCode = spv::OpIAddCarry;
6143 typeId = builder.makeStructResultType(typeId0, typeId0);
6144 consumedOperands = 2;
6145 break;
6146 case glslang::EOpSubBorrow:
6147 opCode = spv::OpISubBorrow;
6148 typeId = builder.makeStructResultType(typeId0, typeId0);
6149 consumedOperands = 2;
6150 break;
6151 case glslang::EOpUMulExtended:
6152 opCode = spv::OpUMulExtended;
6153 typeId = builder.makeStructResultType(typeId0, typeId0);
6154 consumedOperands = 2;
6155 break;
6156 case glslang::EOpIMulExtended:
6157 opCode = spv::OpSMulExtended;
6158 typeId = builder.makeStructResultType(typeId0, typeId0);
6159 consumedOperands = 2;
6160 break;
6161 case glslang::EOpBitfieldExtract:
6162 if (isUnsigned)
6163 opCode = spv::OpBitFieldUExtract;
6164 else
6165 opCode = spv::OpBitFieldSExtract;
6166 break;
6167 case glslang::EOpBitfieldInsert:
6168 opCode = spv::OpBitFieldInsert;
6169 break;
6170
6171 case glslang::EOpFma:
6172 libCall = spv::GLSLstd450Fma;
6173 break;
6174 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006175 {
6176 libCall = spv::GLSLstd450FrexpStruct;
6177 assert(builder.isPointerType(typeId1));
6178 typeId1 = builder.getContainedTypeId(typeId1);
Rex Xu470026f2017-03-29 17:12:40 +08006179 int width = builder.getScalarTypeWidth(typeId1);
Rex Xu7c88aff2018-04-11 16:56:50 +08006180#ifdef AMD_EXTENSIONS
6181 if (width == 16)
6182 // Using 16-bit exp operand, enable extension SPV_AMD_gpu_shader_int16
6183 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
6184#endif
Rex Xu470026f2017-03-29 17:12:40 +08006185 if (builder.getNumComponents(operands[0]) == 1)
6186 frexpIntType = builder.makeIntegerType(width, true);
6187 else
6188 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
6189 typeId = builder.makeStructResultType(typeId0, frexpIntType);
6190 consumedOperands = 1;
6191 }
John Kessenich55e7d112015-11-15 21:33:39 -07006192 break;
6193 case glslang::EOpLdexp:
6194 libCall = spv::GLSLstd450Ldexp;
6195 break;
6196
Rex Xu574ab042016-04-14 16:53:07 +08006197 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08006198 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08006199
John Kessenich66011cb2018-03-06 16:12:04 -07006200 case glslang::EOpSubgroupBroadcast:
6201 case glslang::EOpSubgroupBallotBitExtract:
6202 case glslang::EOpSubgroupShuffle:
6203 case glslang::EOpSubgroupShuffleXor:
6204 case glslang::EOpSubgroupShuffleUp:
6205 case glslang::EOpSubgroupShuffleDown:
6206 case glslang::EOpSubgroupClusteredAdd:
6207 case glslang::EOpSubgroupClusteredMul:
6208 case glslang::EOpSubgroupClusteredMin:
6209 case glslang::EOpSubgroupClusteredMax:
6210 case glslang::EOpSubgroupClusteredAnd:
6211 case glslang::EOpSubgroupClusteredOr:
6212 case glslang::EOpSubgroupClusteredXor:
6213 case glslang::EOpSubgroupQuadBroadcast:
Jeff Bolz2abe9a42018-03-29 22:52:17 -05006214#ifdef NV_EXTENSIONS
6215 case glslang::EOpSubgroupPartitionedAdd:
6216 case glslang::EOpSubgroupPartitionedMul:
6217 case glslang::EOpSubgroupPartitionedMin:
6218 case glslang::EOpSubgroupPartitionedMax:
6219 case glslang::EOpSubgroupPartitionedAnd:
6220 case glslang::EOpSubgroupPartitionedOr:
6221 case glslang::EOpSubgroupPartitionedXor:
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:
6229 case glslang::EOpSubgroupPartitionedExclusiveAdd:
6230 case glslang::EOpSubgroupPartitionedExclusiveMul:
6231 case glslang::EOpSubgroupPartitionedExclusiveMin:
6232 case glslang::EOpSubgroupPartitionedExclusiveMax:
6233 case glslang::EOpSubgroupPartitionedExclusiveAnd:
6234 case glslang::EOpSubgroupPartitionedExclusiveOr:
6235 case glslang::EOpSubgroupPartitionedExclusiveXor:
6236#endif
John Kessenich66011cb2018-03-06 16:12:04 -07006237 return createSubgroupOperation(op, typeId, operands, typeProxy);
6238
Rex Xu9d93a232016-05-05 12:30:44 +08006239#ifdef AMD_EXTENSIONS
6240 case glslang::EOpSwizzleInvocations:
6241 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6242 libCall = spv::SwizzleInvocationsAMD;
6243 break;
6244 case glslang::EOpSwizzleInvocationsMasked:
6245 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6246 libCall = spv::SwizzleInvocationsMaskedAMD;
6247 break;
6248 case glslang::EOpWriteInvocation:
6249 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
6250 libCall = spv::WriteInvocationAMD;
6251 break;
6252
6253 case glslang::EOpMin3:
6254 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6255 if (isFloat)
6256 libCall = spv::FMin3AMD;
6257 else {
6258 if (isUnsigned)
6259 libCall = spv::UMin3AMD;
6260 else
6261 libCall = spv::SMin3AMD;
6262 }
6263 break;
6264 case glslang::EOpMax3:
6265 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6266 if (isFloat)
6267 libCall = spv::FMax3AMD;
6268 else {
6269 if (isUnsigned)
6270 libCall = spv::UMax3AMD;
6271 else
6272 libCall = spv::SMax3AMD;
6273 }
6274 break;
6275 case glslang::EOpMid3:
6276 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
6277 if (isFloat)
6278 libCall = spv::FMid3AMD;
6279 else {
6280 if (isUnsigned)
6281 libCall = spv::UMid3AMD;
6282 else
6283 libCall = spv::SMid3AMD;
6284 }
6285 break;
6286
6287 case glslang::EOpInterpolateAtVertex:
Rex Xub4a2a6c2018-05-17 13:51:28 +08006288 if (typeProxy == glslang::EbtFloat16)
6289 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xu9d93a232016-05-05 12:30:44 +08006290 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
6291 libCall = spv::InterpolateAtVertexAMD;
6292 break;
6293#endif
6294
John Kessenich140f3df2015-06-26 16:58:36 -06006295 default:
6296 return 0;
6297 }
6298
6299 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07006300 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05006301 // Use an extended instruction from the standard library.
6302 // Construct the call arguments, without modifying the original operands vector.
6303 // We might need the remaining arguments, e.g. in the EOpFrexp case.
6304 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08006305 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07006306 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07006307 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06006308 case 0:
6309 // should all be handled by visitAggregate and createNoArgOperation
6310 assert(0);
6311 return 0;
6312 case 1:
6313 // should all be handled by createUnaryOperation
6314 assert(0);
6315 return 0;
6316 case 2:
6317 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
6318 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006319 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006320 // anything 3 or over doesn't have l-value operands, so all should be consumed
6321 assert(consumedOperands == operands.size());
6322 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06006323 break;
6324 }
6325 }
6326
John Kessenich55e7d112015-11-15 21:33:39 -07006327 // Decode the return types that were structures
6328 switch (op) {
6329 case glslang::EOpAddCarry:
6330 case glslang::EOpSubBorrow:
6331 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6332 id = builder.createCompositeExtract(id, typeId0, 0);
6333 break;
6334 case glslang::EOpUMulExtended:
6335 case glslang::EOpIMulExtended:
6336 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
6337 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
6338 break;
6339 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08006340 {
6341 assert(operands.size() == 2);
6342 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
6343 // "exp" is floating-point type (from HLSL intrinsic)
6344 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
6345 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
6346 builder.createStore(member1, operands[1]);
6347 } else
6348 // "exp" is integer type (from GLSL built-in function)
6349 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
6350 id = builder.createCompositeExtract(id, typeId0, 0);
6351 }
John Kessenich55e7d112015-11-15 21:33:39 -07006352 break;
6353 default:
6354 break;
6355 }
6356
John Kessenich32cfd492016-02-02 12:37:46 -07006357 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06006358}
6359
Rex Xu9d93a232016-05-05 12:30:44 +08006360// Intrinsics with no arguments (or no return value, and no precision).
6361spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06006362{
6363 // TODO: get the barrier operands correct
6364
6365 switch (op) {
6366 case glslang::EOpEmitVertex:
6367 builder.createNoResultOp(spv::OpEmitVertex);
6368 return 0;
6369 case glslang::EOpEndPrimitive:
6370 builder.createNoResultOp(spv::OpEndPrimitive);
6371 return 0;
6372 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006373 if (glslangIntermediate->getStage() == EShLangTessControl) {
6374 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
6375 // TODO: prefer the following, when available:
6376 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
6377 // spv::MemorySemanticsPatchMask |
6378 // spv::MemorySemanticsAcquireReleaseMask);
6379 } else {
6380 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6381 spv::MemorySemanticsWorkgroupMemoryMask |
6382 spv::MemorySemanticsAcquireReleaseMask);
6383 }
John Kessenich140f3df2015-06-26 16:58:36 -06006384 return 0;
6385 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006386 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
6387 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006388 return 0;
6389 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07006390 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
6391 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006392 return 0;
6393 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07006394 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6395 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006396 return 0;
6397 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07006398 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
6399 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006400 return 0;
6401 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07006402 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
6403 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006404 return 0;
6405 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07006406 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
6407 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06006408 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06006409 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006410 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07006411 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07006412 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006413 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07006414 case glslang::EOpDeviceMemoryBarrier:
6415 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6416 spv::MemorySemanticsImageMemoryMask |
6417 spv::MemorySemanticsAcquireReleaseMask);
6418 return 0;
6419 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
6420 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
6421 spv::MemorySemanticsImageMemoryMask |
6422 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006423 return 0;
6424 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07006425 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6426 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006427 return 0;
6428 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07006429 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
6430 spv::MemorySemanticsWorkgroupMemoryMask |
6431 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06006432 return 0;
John Kessenich66011cb2018-03-06 16:12:04 -07006433 case glslang::EOpSubgroupBarrier:
6434 builder.createControlBarrier(spv::ScopeSubgroup, spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6435 spv::MemorySemanticsAcquireReleaseMask);
6436 return spv::NoResult;
6437 case glslang::EOpSubgroupMemoryBarrier:
6438 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsAllMemory |
6439 spv::MemorySemanticsAcquireReleaseMask);
6440 return spv::NoResult;
6441 case glslang::EOpSubgroupMemoryBarrierBuffer:
6442 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsUniformMemoryMask |
6443 spv::MemorySemanticsAcquireReleaseMask);
6444 return spv::NoResult;
6445 case glslang::EOpSubgroupMemoryBarrierImage:
6446 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsImageMemoryMask |
6447 spv::MemorySemanticsAcquireReleaseMask);
6448 return spv::NoResult;
6449 case glslang::EOpSubgroupMemoryBarrierShared:
6450 builder.createMemoryBarrier(spv::ScopeSubgroup, spv::MemorySemanticsWorkgroupMemoryMask |
6451 spv::MemorySemanticsAcquireReleaseMask);
6452 return spv::NoResult;
6453 case glslang::EOpSubgroupElect: {
6454 std::vector<spv::Id> operands;
6455 return createSubgroupOperation(op, typeId, operands, glslang::EbtVoid);
6456 }
Rex Xu9d93a232016-05-05 12:30:44 +08006457#ifdef AMD_EXTENSIONS
6458 case glslang::EOpTime:
6459 {
6460 std::vector<spv::Id> args; // Dummy arguments
6461 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
6462 return builder.setPrecision(id, precision);
6463 }
6464#endif
John Kessenich140f3df2015-06-26 16:58:36 -06006465 default:
Lei Zhang17535f72016-05-04 15:55:59 -04006466 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06006467 return 0;
6468 }
6469}
6470
6471spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
6472{
John Kessenich2f273362015-07-18 22:34:27 -06006473 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06006474 spv::Id id;
6475 if (symbolValues.end() != iter) {
6476 id = iter->second;
6477 return id;
6478 }
6479
6480 // it was not found, create it
6481 id = createSpvVariable(symbol);
6482 symbolValues[symbol->getId()] = id;
6483
Rex Xuc884b4a2016-06-29 15:03:44 +08006484 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006485 builder.addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
6486 builder.addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
6487 builder.addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07006488 if (symbol->getType().getQualifier().hasSpecConstantId())
John Kessenich5d610ee2018-03-07 18:05:55 -07006489 builder.addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06006490 if (symbol->getQualifier().hasIndex())
6491 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
6492 if (symbol->getQualifier().hasComponent())
6493 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06006494 // atomic counters use this:
6495 if (symbol->getQualifier().hasOffset())
6496 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006497 }
6498
scygan2c864272016-05-18 18:09:17 +02006499 if (symbol->getQualifier().hasLocation())
6500 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kessenich5d610ee2018-03-07 18:05:55 -07006501 builder.addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07006502 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07006503 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06006504 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07006505 }
John Kessenich140f3df2015-06-26 16:58:36 -06006506 if (symbol->getQualifier().hasSet())
6507 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07006508 else if (IsDescriptorResource(symbol->getType())) {
6509 // default to 0
6510 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
6511 }
John Kessenich140f3df2015-06-26 16:58:36 -06006512 if (symbol->getQualifier().hasBinding())
6513 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07006514 if (symbol->getQualifier().hasAttachment())
6515 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06006516 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07006517 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06006518 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06006519 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07006520 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06006521 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07006522 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
6523 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
6524 builder.addDecoration(id, spv::DecorationXfbStride, stride);
6525 }
6526 if (symbol->getQualifier().hasXfbOffset())
6527 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06006528 }
6529
Rex Xu1da878f2016-02-21 20:59:01 +08006530 if (symbol->getType().isImage()) {
6531 std::vector<spv::Decoration> memory;
6532 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
6533 for (unsigned int i = 0; i < memory.size(); ++i)
John Kessenich5d610ee2018-03-07 18:05:55 -07006534 builder.addDecoration(id, memory[i]);
Rex Xu1da878f2016-02-21 20:59:01 +08006535 }
6536
John Kessenich140f3df2015-06-26 16:58:36 -06006537 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06006538 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06006539 if (builtIn != spv::BuiltInMax)
John Kessenich5d610ee2018-03-07 18:05:55 -07006540 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06006541
John Kessenich5611c6d2018-04-05 11:25:02 -06006542 // nonuniform
6543 builder.addDecoration(id, TranslateNonUniformDecoration(symbol->getType().getQualifier()));
6544
John Kessenichecba76f2017-01-06 00:34:48 -07006545#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08006546 if (builtIn == spv::BuiltInSampleMask) {
6547 spv::Decoration decoration;
6548 // GL_NV_sample_mask_override_coverage extension
6549 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08006550 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08006551 else
6552 decoration = (spv::Decoration)spv::DecorationMax;
John Kessenich5d610ee2018-03-07 18:05:55 -07006553 builder.addDecoration(id, decoration);
chaoc0ad6a4e2016-12-19 16:29:34 -08006554 if (decoration != spv::DecorationMax) {
6555 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
6556 }
6557 }
chaoc771d89f2017-01-13 01:10:53 -08006558 else if (builtIn == spv::BuiltInLayer) {
6559 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06006560 if (symbol->getQualifier().layoutViewportRelative) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006561 builder.addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
chaoc771d89f2017-01-13 01:10:53 -08006562 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
6563 builder.addExtension(spv::E_SPV_NV_viewport_array2);
6564 }
John Kessenichb41bff62017-08-11 13:07:17 -06006565 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006566 builder.addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV,
6567 symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
chaoc771d89f2017-01-13 01:10:53 -08006568 builder.addCapability(spv::CapabilityShaderStereoViewNV);
6569 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
6570 }
6571 }
6572
chaoc6e5acae2016-12-20 13:28:52 -08006573 if (symbol->getQualifier().layoutPassthrough) {
John Kessenich5d610ee2018-03-07 18:05:55 -07006574 builder.addDecoration(id, spv::DecorationPassthroughNV);
chaoc771d89f2017-01-13 01:10:53 -08006575 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08006576 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
6577 }
chaoc0ad6a4e2016-12-19 16:29:34 -08006578#endif
6579
John Kessenich5d610ee2018-03-07 18:05:55 -07006580 if (glslangIntermediate->getHlslFunctionality1() && symbol->getType().getQualifier().semanticName != nullptr) {
6581 builder.addExtension("SPV_GOOGLE_hlsl_functionality1");
6582 builder.addDecoration(id, (spv::Decoration)spv::DecorationHlslSemanticGOOGLE,
6583 symbol->getType().getQualifier().semanticName);
6584 }
6585
John Kessenich140f3df2015-06-26 16:58:36 -06006586 return id;
6587}
6588
John Kessenich55e7d112015-11-15 21:33:39 -07006589// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07006590// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07006591//
6592// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
6593//
6594// Recursively walk the nodes. The nodes form a tree whose leaves are
6595// regular constants, which themselves are trees that createSpvConstant()
6596// recursively walks. So, this function walks the "top" of the tree:
6597// - emit specialization constant-building instructions for specConstant
6598// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04006599spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07006600{
John Kessenich7cc0e282016-03-20 00:46:02 -06006601 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07006602
qining4f4bb812016-04-03 23:55:17 -04006603 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07006604 if (! node.getQualifier().specConstant) {
6605 // hand off to the non-spec-constant path
6606 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
6607 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04006608 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07006609 nextConst, false);
6610 }
6611
6612 // We now know we have a specialization constant to build
6613
John Kessenichd94c0032016-05-30 19:29:40 -06006614 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04006615 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
6616 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
6617 std::vector<spv::Id> dimConstId;
6618 for (int dim = 0; dim < 3; ++dim) {
6619 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
6620 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
John Kessenich5d610ee2018-03-07 18:05:55 -07006621 if (specConst) {
6622 builder.addDecoration(dimConstId.back(), spv::DecorationSpecId,
6623 glslangIntermediate->getLocalSizeSpecId(dim));
6624 }
qining4f4bb812016-04-03 23:55:17 -04006625 }
6626 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
6627 }
6628
6629 // An AST node labelled as specialization constant should be a symbol node.
6630 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
6631 if (auto* sn = node.getAsSymbolNode()) {
6632 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04006633 // Traverse the constant constructor sub tree like generating normal run-time instructions.
6634 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
6635 // will set the builder into spec constant op instruction generating mode.
6636 sub_tree->traverse(this);
6637 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04006638 } else if (auto* const_union_array = &sn->getConstArray()){
6639 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01006640 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
6641 builder.addName(id, sn->getName().c_str());
6642 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07006643 }
6644 }
qining4f4bb812016-04-03 23:55:17 -04006645
6646 // Neither a front-end constant node, nor a specialization constant node with constant union array or
6647 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04006648 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04006649 exit(1);
6650 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07006651}
6652
John Kessenich140f3df2015-06-26 16:58:36 -06006653// Use 'consts' as the flattened glslang source of scalar constants to recursively
6654// build the aggregate SPIR-V constant.
6655//
6656// If there are not enough elements present in 'consts', 0 will be substituted;
6657// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
6658//
qining08408382016-03-21 09:51:37 -04006659spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06006660{
6661 // vector of constants for SPIR-V
6662 std::vector<spv::Id> spvConsts;
6663
6664 // Type is used for struct and array constants
6665 spv::Id typeId = convertGlslangToSpvType(glslangType);
6666
6667 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006668 glslang::TType elementType(glslangType, 0);
6669 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04006670 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006671 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06006672 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06006673 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04006674 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06006675 } else if (glslangType.getStruct()) {
6676 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
6677 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04006678 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06006679 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06006680 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
6681 bool zero = nextConst >= consts.size();
6682 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006683 case glslang::EbtInt8:
6684 spvConsts.push_back(builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const()));
6685 break;
6686 case glslang::EbtUint8:
6687 spvConsts.push_back(builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const()));
6688 break;
6689 case glslang::EbtInt16:
6690 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const()));
6691 break;
6692 case glslang::EbtUint16:
6693 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const()));
6694 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006695 case glslang::EbtInt:
6696 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
6697 break;
6698 case glslang::EbtUint:
6699 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
6700 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006701 case glslang::EbtInt64:
6702 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
6703 break;
6704 case glslang::EbtUint64:
6705 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
6706 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006707 case glslang::EbtFloat:
6708 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6709 break;
6710 case glslang::EbtDouble:
6711 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
6712 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006713 case glslang::EbtFloat16:
6714 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
6715 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006716 case glslang::EbtBool:
6717 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
6718 break;
6719 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006720 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006721 break;
6722 }
6723 ++nextConst;
6724 }
6725 } else {
6726 // we have a non-aggregate (scalar) constant
6727 bool zero = nextConst >= consts.size();
6728 spv::Id scalar = 0;
6729 switch (glslangType.getBasicType()) {
John Kessenich66011cb2018-03-06 16:12:04 -07006730 case glslang::EbtInt8:
6731 scalar = builder.makeInt8Constant(zero ? 0 : consts[nextConst].getI8Const(), specConstant);
6732 break;
6733 case glslang::EbtUint8:
6734 scalar = builder.makeUint8Constant(zero ? 0 : consts[nextConst].getU8Const(), specConstant);
6735 break;
6736 case glslang::EbtInt16:
6737 scalar = builder.makeInt16Constant(zero ? 0 : consts[nextConst].getI16Const(), specConstant);
6738 break;
6739 case glslang::EbtUint16:
6740 scalar = builder.makeUint16Constant(zero ? 0 : consts[nextConst].getU16Const(), specConstant);
6741 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006742 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07006743 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006744 break;
6745 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07006746 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006747 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08006748 case glslang::EbtInt64:
6749 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
6750 break;
6751 case glslang::EbtUint64:
6752 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
6753 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006754 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07006755 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006756 break;
6757 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07006758 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006759 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08006760 case glslang::EbtFloat16:
6761 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
6762 break;
John Kessenich140f3df2015-06-26 16:58:36 -06006763 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07006764 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06006765 break;
6766 default:
John Kessenich55e7d112015-11-15 21:33:39 -07006767 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06006768 break;
6769 }
6770 ++nextConst;
6771 return scalar;
6772 }
6773
6774 return builder.makeCompositeConstant(typeId, spvConsts);
6775}
6776
John Kessenich7c1aa102015-10-15 13:29:11 -06006777// Return true if the node is a constant or symbol whose reading has no
6778// non-trivial observable cost or effect.
6779bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
6780{
6781 // don't know what this is
6782 if (node == nullptr)
6783 return false;
6784
6785 // a constant is safe
6786 if (node->getAsConstantUnion() != nullptr)
6787 return true;
6788
6789 // not a symbol means non-trivial
6790 if (node->getAsSymbolNode() == nullptr)
6791 return false;
6792
6793 // a symbol, depends on what's being read
6794 switch (node->getType().getQualifier().storage) {
6795 case glslang::EvqTemporary:
6796 case glslang::EvqGlobal:
6797 case glslang::EvqIn:
6798 case glslang::EvqInOut:
6799 case glslang::EvqConst:
6800 case glslang::EvqConstReadOnly:
6801 case glslang::EvqUniform:
6802 return true;
6803 default:
6804 return false;
6805 }
qining25262b32016-05-06 17:25:16 -04006806}
John Kessenich7c1aa102015-10-15 13:29:11 -06006807
6808// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06006809// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06006810// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06006811// Return true if trivial.
6812bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
6813{
6814 if (node == nullptr)
6815 return false;
6816
John Kessenich84cc15f2017-05-24 16:44:47 -06006817 // count non scalars as trivial, as well as anything coming from HLSL
6818 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06006819 return true;
6820
John Kessenich7c1aa102015-10-15 13:29:11 -06006821 // symbols and constants are trivial
6822 if (isTrivialLeaf(node))
6823 return true;
6824
6825 // otherwise, it needs to be a simple operation or one or two leaf nodes
6826
6827 // not a simple operation
6828 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
6829 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
6830 if (binaryNode == nullptr && unaryNode == nullptr)
6831 return false;
6832
6833 // not on leaf nodes
6834 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
6835 return false;
6836
6837 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
6838 return false;
6839 }
6840
6841 switch (node->getAsOperator()->getOp()) {
6842 case glslang::EOpLogicalNot:
6843 case glslang::EOpConvIntToBool:
6844 case glslang::EOpConvUintToBool:
6845 case glslang::EOpConvFloatToBool:
6846 case glslang::EOpConvDoubleToBool:
6847 case glslang::EOpEqual:
6848 case glslang::EOpNotEqual:
6849 case glslang::EOpLessThan:
6850 case glslang::EOpGreaterThan:
6851 case glslang::EOpLessThanEqual:
6852 case glslang::EOpGreaterThanEqual:
6853 case glslang::EOpIndexDirect:
6854 case glslang::EOpIndexDirectStruct:
6855 case glslang::EOpLogicalXor:
6856 case glslang::EOpAny:
6857 case glslang::EOpAll:
6858 return true;
6859 default:
6860 return false;
6861 }
6862}
6863
6864// Emit short-circuiting code, where 'right' is never evaluated unless
6865// the left side is true (for &&) or false (for ||).
6866spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
6867{
6868 spv::Id boolTypeId = builder.makeBoolType();
6869
6870 // emit left operand
6871 builder.clearAccessChain();
6872 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006873 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006874
6875 // Operands to accumulate OpPhi operands
6876 std::vector<spv::Id> phiOperands;
6877 // accumulate left operand's phi information
6878 phiOperands.push_back(leftId);
6879 phiOperands.push_back(builder.getBuildPoint()->getId());
6880
6881 // Make the two kinds of operation symmetric with a "!"
6882 // || => emit "if (! left) result = right"
6883 // && => emit "if ( left) result = right"
6884 //
6885 // TODO: this runtime "not" for || could be avoided by adding functionality
6886 // to 'builder' to have an "else" without an "then"
6887 if (op == glslang::EOpLogicalOr)
6888 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
6889
6890 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08006891 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06006892
6893 // emit right operand as the "then" part of the "if"
6894 builder.clearAccessChain();
6895 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08006896 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06006897
6898 // accumulate left operand's phi information
6899 phiOperands.push_back(rightId);
6900 phiOperands.push_back(builder.getBuildPoint()->getId());
6901
6902 // finish the "if"
6903 ifBuilder.makeEndIf();
6904
6905 // phi together the two results
6906 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
6907}
6908
Frank Henigman541f7bb2018-01-16 00:18:26 -05006909#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08006910// Return type Id of the imported set of extended instructions corresponds to the name.
6911// Import this set if it has not been imported yet.
6912spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
6913{
6914 if (extBuiltinMap.find(name) != extBuiltinMap.end())
6915 return extBuiltinMap[name];
6916 else {
Rex Xu51596642016-09-21 18:56:12 +08006917 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08006918 spv::Id extBuiltins = builder.import(name);
6919 extBuiltinMap[name] = extBuiltins;
6920 return extBuiltins;
6921 }
6922}
Frank Henigman541f7bb2018-01-16 00:18:26 -05006923#endif
Rex Xu9d93a232016-05-05 12:30:44 +08006924
John Kessenich140f3df2015-06-26 16:58:36 -06006925}; // end anonymous namespace
6926
6927namespace glslang {
6928
John Kessenich68d78fd2015-07-12 19:28:10 -06006929void GetSpirvVersion(std::string& version)
6930{
John Kessenich9e55f632015-07-15 10:03:39 -06006931 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06006932 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07006933 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06006934 version = buf;
6935}
6936
John Kessenicha372a3e2017-11-02 22:32:14 -06006937// For low-order part of the generator's magic number. Bump up
6938// when there is a change in the style (e.g., if SSA form changes,
6939// or a different instruction sequence to do something gets used).
6940int GetSpirvGeneratorVersion()
6941{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07006942 // return 1; // start
6943 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07006944 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
John Kessenich0216f242018-03-03 11:47:07 -07006945 // return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenichac370792018-03-07 11:24:50 -07006946 // return 5; // make OpArrayLength result type be an int with signedness of 0
John Kessenichd6c97552018-06-04 15:33:31 -06006947 // return 6; // revert version 5 change, which makes a different (new) kind of incorrect code,
6948 // versions 4 and 6 each generate OpArrayLength as it has long been done
6949 return 7; // GLSL volatile keyword maps to both SPIR-V decorations Volatile and Coherent
John Kessenicha372a3e2017-11-02 22:32:14 -06006950}
6951
John Kessenich140f3df2015-06-26 16:58:36 -06006952// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006953void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06006954{
6955 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06006956 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006957 if (out.fail())
6958 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06006959 for (int i = 0; i < (int)spirv.size(); ++i) {
6960 unsigned int word = spirv[i];
6961 out.write((const char*)&word, 4);
6962 }
6963 out.close();
6964}
6965
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006966// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08006967void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006968{
6969 std::ofstream out;
6970 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006971 if (out.fail())
6972 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenichc6c80a62018-03-05 22:23:17 -07006973 out << "\t// " <<
6974 glslang::GetSpirvGeneratorVersion() << "." << GLSLANG_MINOR_VERSION << "." << GLSLANG_PATCH_LEVEL <<
6975 std::endl;
Flavio15017db2017-02-15 14:29:33 -08006976 if (varName != nullptr) {
6977 out << "\t #pragma once" << std::endl;
6978 out << "const uint32_t " << varName << "[] = {" << std::endl;
6979 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006980 const int WORDS_PER_LINE = 8;
6981 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
6982 out << "\t";
6983 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6984 const unsigned int word = spirv[i + j];
6985 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6986 if (i + j + 1 < (int)spirv.size()) {
6987 out << ",";
6988 }
6989 }
6990 out << std::endl;
6991 }
Flavio15017db2017-02-15 14:29:33 -08006992 if (varName != nullptr) {
6993 out << "};";
6994 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006995 out.close();
6996}
6997
John Kessenich140f3df2015-06-26 16:58:36 -06006998//
6999// Set up the glslang traversal
7000//
John Kessenich121853f2017-05-31 17:11:16 -06007001void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06007002{
Lei Zhang17535f72016-05-04 15:55:59 -04007003 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06007004 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04007005}
7006
John Kessenich121853f2017-05-31 17:11:16 -06007007void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
7008 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04007009{
John Kessenich140f3df2015-06-26 16:58:36 -06007010 TIntermNode* root = intermediate.getTreeRoot();
7011
7012 if (root == 0)
7013 return;
7014
John Kessenich121853f2017-05-31 17:11:16 -06007015 glslang::SpvOptions defaultOptions;
7016 if (options == nullptr)
7017 options = &defaultOptions;
7018
John Kessenich140f3df2015-06-26 16:58:36 -06007019 glslang::GetThreadPoolAllocator().push();
7020
John Kessenich2b5ea9f2018-01-31 18:35:56 -07007021 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06007022 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07007023 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06007024 it.dumpSpv(spirv);
7025
GregFfb03a552018-03-29 11:49:14 -06007026#if ENABLE_OPT
GregFcd1f1692017-09-21 18:40:22 -06007027 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
7028 // eg. forward and remove memory writes of opaque types.
7029 if ((intermediate.getSource() == EShSourceHlsl ||
7030 options->optimizeSize) &&
7031 !options->disableOptimizer) {
7032 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
7033
7034 spvtools::Optimizer optimizer(target_env);
7035 optimizer.SetMessageConsumer([](spv_message_level_t level,
7036 const char* source,
7037 const spv_position_t& position,
7038 const char* message) {
7039 std::cerr << StringifyMessage(level, source, position, message)
7040 << std::endl;
7041 });
7042
GregFeecb8742018-03-26 12:11:55 -06007043 optimizer.RegisterPass(CreateMergeReturnPass());
GregFcd1f1692017-09-21 18:40:22 -06007044 optimizer.RegisterPass(CreateInlineExhaustivePass());
GregFe0639282017-12-21 10:55:57 -07007045 optimizer.RegisterPass(CreateEliminateDeadFunctionsPass());
7046 optimizer.RegisterPass(CreateScalarReplacementPass());
GregFcd1f1692017-09-21 18:40:22 -06007047 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
7048 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
7049 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
GregFb0c42b22018-05-31 16:17:18 -06007050 optimizer.RegisterPass(CreateSimplificationPass());
GregFeecb8742018-03-26 12:11:55 -06007051 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFb0c42b22018-05-31 16:17:18 -06007052 optimizer.RegisterPass(CreateVectorDCEPass());
GregF8a4848f2018-02-07 16:04:42 -07007053 optimizer.RegisterPass(CreateDeadInsertElimPass());
GregFcd1f1692017-09-21 18:40:22 -06007054 optimizer.RegisterPass(CreateAggressiveDCEPass());
7055 optimizer.RegisterPass(CreateDeadBranchElimPass());
7056 optimizer.RegisterPass(CreateBlockMergePass());
7057 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
GregFb0c42b22018-05-31 16:17:18 -06007058 optimizer.RegisterPass(CreateIfConversionPass());
7059 optimizer.RegisterPass(CreateSimplificationPass());
GregFeecb8742018-03-26 12:11:55 -06007060 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFb0c42b22018-05-31 16:17:18 -06007061 optimizer.RegisterPass(CreateVectorDCEPass());
GregF8a4848f2018-02-07 16:04:42 -07007062 optimizer.RegisterPass(CreateDeadInsertElimPass());
7063 if (options->optimizeSize) {
7064 optimizer.RegisterPass(CreateRedundancyEliminationPass());
7065 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
7066 // optimizer.RegisterPass(CreateCommonUniformElimPass());
7067 }
GregFcd1f1692017-09-21 18:40:22 -06007068 optimizer.RegisterPass(CreateAggressiveDCEPass());
GregFb0c42b22018-05-31 16:17:18 -06007069 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06007070
7071 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
7072 return;
GregFcd1f1692017-09-21 18:40:22 -06007073 }
7074#endif
7075
John Kessenich140f3df2015-06-26 16:58:36 -06007076 glslang::GetThreadPoolAllocator().pop();
7077}
7078
7079}; // end namespace glslang