blob: 1e1d29d0bc94840ebeeb873b8db17532f8000a16 [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 Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
John Kessenich927608b2017-01-06 12:34:14 -070023// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060035
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070047 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080048#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080049 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080050#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080051#ifdef NV_EXTENSIONS
52 #include "GLSL.ext.NV.h"
53#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060054}
John Kessenich140f3df2015-06-26 16:58:36 -060055
GregFcd1f1692017-09-21 18:40:22 -060056#ifdef ENABLE_OPT
57 #include "spirv-tools/optimizer.hpp"
58 #include "message.h"
59 #include "SPVRemapper.h"
60#endif
61
62#ifdef ENABLE_OPT
63using 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};
101}
102
John Kessenich140f3df2015-06-26 16:58:36 -0600103//
104// The main holder of information for translating glslang to SPIR-V.
105//
106// Derives from the AST walking base class.
107//
108class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
109public:
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700110 TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate*, spv::SpvBuildLogger* logger,
111 glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700112 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600113
114 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
115 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
116 void visitConstantUnion(glslang::TIntermConstantUnion*);
117 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
118 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
119 void visitSymbol(glslang::TIntermSymbol* symbol);
120 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
121 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
122 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
123
John Kessenichfca82622016-11-26 13:23:20 -0700124 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700125 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600126
127protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800128 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800129 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100130 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700131 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kesseniche18fd202018-01-30 11:01:39 -0700132 spv::SelectionControlMask TranslateSelectionControl(const glslang::TIntermSelection&) const;
133 spv::SelectionControlMask TranslateSwitchControl(const glslang::TIntermSwitch&) const;
John Kessenicha2858d92018-01-31 08:11:18 -0700134 spv::LoopControlMask TranslateLoopControl(const glslang::TIntermLoop&, unsigned int& dependencyLength) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600135 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600136 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
137 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600138 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
139 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
140 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600141 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700142 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600143 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600144 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
145 glslang::TLayoutPacking, const glslang::TQualifier&);
146 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
147 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700148 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700149 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800150 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600151 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700152 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700153 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
154 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
155 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100156 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600157
John Kessenich6fccb3c2016-09-19 16:01:41 -0600158 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd41993d2017-09-10 15:21:05 -0600159 bool writableParam(glslang::TStorageQualifier);
160 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600161 void makeFunctions(const glslang::TIntermSequence&);
162 void makeGlobalInitializers(const glslang::TIntermSequence&);
163 void visitFunctions(const glslang::TIntermSequence&);
164 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800165 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600166 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
167 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600168 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
169
qining25262b32016-05-06 17:25:16 -0400170 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
171 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
172 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800173 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800174 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600175 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800176 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 +0800177 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800178 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600179 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 +0800180 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600181 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
182 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700183 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600184 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700185 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400186 spv::Id createSpvConstant(const glslang::TIntermTyped&);
187 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600188 bool isTrivialLeaf(const glslang::TIntermTyped* node);
189 bool isTrivial(const glslang::TIntermTyped* node);
190 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500191#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +0800192 spv::Id getExtBuiltins(const char* name);
Frank Henigman541f7bb2018-01-16 00:18:26 -0500193#endif
John Kessenich140f3df2015-06-26 16:58:36 -0600194
John Kessenich121853f2017-05-31 17:11:16 -0600195 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600196 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600197 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700198 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600199 int sequenceDepth;
200
Lei Zhang17535f72016-05-04 15:55:59 -0400201 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400202
John Kessenich140f3df2015-06-26 16:58:36 -0600203 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
204 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700205 bool inEntryPoint;
206 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700207 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 -0700208 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600209 const glslang::TIntermediate* glslangIntermediate;
210 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800211 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600212
John Kessenich2f273362015-07-18 22:34:27 -0600213 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600214 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600215 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700216 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600217 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600218 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600219};
220
221//
222// Helper functions for translating glslang representations to SPIR-V enumerants.
223//
224
225// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700226spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600227{
John Kessenich66e2faf2016-03-12 18:34:36 -0700228 switch (source) {
229 case glslang::EShSourceGlsl:
230 switch (profile) {
231 case ENoProfile:
232 case ECoreProfile:
233 case ECompatibilityProfile:
234 return spv::SourceLanguageGLSL;
235 case EEsProfile:
236 return spv::SourceLanguageESSL;
237 default:
238 return spv::SourceLanguageUnknown;
239 }
240 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600241 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600242 default:
243 return spv::SourceLanguageUnknown;
244 }
245}
246
247// Translate glslang language (stage) to SPIR-V execution model.
248spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
249{
250 switch (stage) {
251 case EShLangVertex: return spv::ExecutionModelVertex;
252 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
253 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
254 case EShLangGeometry: return spv::ExecutionModelGeometry;
255 case EShLangFragment: return spv::ExecutionModelFragment;
256 case EShLangCompute: return spv::ExecutionModelGLCompute;
257 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700258 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600259 return spv::ExecutionModelFragment;
260 }
261}
262
John Kessenich140f3df2015-06-26 16:58:36 -0600263// Translate glslang sampler type to SPIR-V dimensionality.
264spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
265{
266 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700267 case glslang::Esd1D: return spv::Dim1D;
268 case glslang::Esd2D: return spv::Dim2D;
269 case glslang::Esd3D: return spv::Dim3D;
270 case glslang::EsdCube: return spv::DimCube;
271 case glslang::EsdRect: return spv::DimRect;
272 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700273 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600274 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700275 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600276 return spv::Dim2D;
277 }
278}
279
John Kessenichf6640762016-08-01 19:44:00 -0600280// Translate glslang precision to SPIR-V precision decorations.
281spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600282{
John Kessenichf6640762016-08-01 19:44:00 -0600283 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700284 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600285 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600286 default:
287 return spv::NoPrecision;
288 }
289}
290
John Kessenichf6640762016-08-01 19:44:00 -0600291// Translate glslang type to SPIR-V precision decorations.
292spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
293{
294 return TranslatePrecisionDecoration(type.getQualifier().precision);
295}
296
John Kessenich140f3df2015-06-26 16:58:36 -0600297// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600298spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600299{
300 if (type.getBasicType() == glslang::EbtBlock) {
301 switch (type.getQualifier().storage) {
302 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600303 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600304 case glslang::EvqVaryingIn: return spv::DecorationBlock;
305 case glslang::EvqVaryingOut: return spv::DecorationBlock;
306 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700307 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600308 break;
309 }
310 }
311
John Kessenich4016e382016-07-15 11:53:56 -0600312 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600313}
314
Rex Xu1da878f2016-02-21 20:59:01 +0800315// Translate glslang type to SPIR-V memory decorations.
316void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
317{
318 if (qualifier.coherent)
319 memory.push_back(spv::DecorationCoherent);
320 if (qualifier.volatil)
321 memory.push_back(spv::DecorationVolatile);
322 if (qualifier.restrict)
323 memory.push_back(spv::DecorationRestrict);
324 if (qualifier.readonly)
325 memory.push_back(spv::DecorationNonWritable);
326 if (qualifier.writeonly)
327 memory.push_back(spv::DecorationNonReadable);
328}
329
John Kessenich140f3df2015-06-26 16:58:36 -0600330// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700331spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600332{
333 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700334 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600335 case glslang::ElmRowMajor:
336 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700337 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600338 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700339 default:
340 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600341 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 }
343 } else {
344 switch (type.getBasicType()) {
345 default:
John Kessenich4016e382016-07-15 11:53:56 -0600346 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600347 break;
348 case glslang::EbtBlock:
349 switch (type.getQualifier().storage) {
350 case glslang::EvqUniform:
351 case glslang::EvqBuffer:
352 switch (type.getQualifier().layoutPacking) {
353 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600354 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
355 default:
John Kessenich4016e382016-07-15 11:53:56 -0600356 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600357 }
358 case glslang::EvqVaryingIn:
359 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700360 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600361 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600362 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700363 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600364 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600365 }
366 }
367 }
368}
369
370// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600371// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700372// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800373spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600374{
Rex Xubbceed72016-05-21 09:40:44 +0800375 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700376 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800378 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700379 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700380 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600381 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800382#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800383 else if (qualifier.explicitInterp) {
384 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800385 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800386 }
Rex Xu9d93a232016-05-05 12:30:44 +0800387#endif
Rex Xubbceed72016-05-21 09:40:44 +0800388 else
John Kessenich4016e382016-07-15 11:53:56 -0600389 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800390}
391
392// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600393// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800394// should be applied.
395spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
396{
397 if (qualifier.patch)
398 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700399 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600400 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700401 else if (qualifier.sample) {
402 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600403 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700404 } else
John Kessenich4016e382016-07-15 11:53:56 -0600405 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600406}
407
John Kessenich92187592016-02-01 13:45:25 -0700408// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700409spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600410{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700411 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600412 return spv::DecorationInvariant;
413 else
John Kessenich4016e382016-07-15 11:53:56 -0600414 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600415}
416
qining9220dbb2016-05-04 17:34:38 -0400417// If glslang type is noContraction, return SPIR-V NoContraction decoration.
418spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
419{
420 if (qualifier.noContraction)
421 return spv::DecorationNoContraction;
422 else
John Kessenich4016e382016-07-15 11:53:56 -0600423 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400424}
425
David Netoa901ffe2016-06-08 14:11:40 +0100426// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
427// associated capabilities when required. For some built-in variables, a capability
428// is generated only when using the variable in an executable instruction, but not when
429// just declaring a struct member variable with it. This is true for PointSize,
430// ClipDistance, and CullDistance.
431spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600432{
433 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700434 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600435 // Defer adding the capability until the built-in is actually used.
436 if (! memberDeclaration) {
437 switch (glslangIntermediate->getStage()) {
438 case EShLangGeometry:
439 builder.addCapability(spv::CapabilityGeometryPointSize);
440 break;
441 case EShLangTessControl:
442 case EShLangTessEvaluation:
443 builder.addCapability(spv::CapabilityTessellationPointSize);
444 break;
445 default:
446 break;
447 }
John Kessenich92187592016-02-01 13:45:25 -0700448 }
449 return spv::BuiltInPointSize;
450
John Kessenichebb50532016-05-16 19:22:05 -0600451 // These *Distance capabilities logically belong here, but if the member is declared and
452 // then never used, consumers of SPIR-V prefer the capability not be declared.
453 // They are now generated when used, rather than here when declared.
454 // Potentially, the specification should be more clear what the minimum
455 // use needed is to trigger the capability.
456 //
John Kessenich92187592016-02-01 13:45:25 -0700457 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100458 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800459 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700460 return spv::BuiltInClipDistance;
461
462 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100463 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800464 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700465 return spv::BuiltInCullDistance;
466
467 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600468 builder.addCapability(spv::CapabilityMultiViewport);
469 if (glslangIntermediate->getStage() == EShLangVertex ||
470 glslangIntermediate->getStage() == EShLangTessControl ||
471 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800472
John Kessenichba6a3c22017-09-13 13:22:50 -0600473 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
474 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800475 }
John Kessenich92187592016-02-01 13:45:25 -0700476 return spv::BuiltInViewportIndex;
477
John Kessenich5e801132016-02-15 11:09:46 -0700478 case glslang::EbvSampleId:
479 builder.addCapability(spv::CapabilitySampleRateShading);
480 return spv::BuiltInSampleId;
481
482 case glslang::EbvSamplePosition:
483 builder.addCapability(spv::CapabilitySampleRateShading);
484 return spv::BuiltInSamplePosition;
485
486 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700487 return spv::BuiltInSampleMask;
488
John Kessenich78a45572016-07-08 14:05:15 -0600489 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600490 builder.addCapability(spv::CapabilityGeometry);
491 if (glslangIntermediate->getStage() == EShLangVertex ||
492 glslangIntermediate->getStage() == EShLangTessControl ||
493 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800494
John Kessenichba6a3c22017-09-13 13:22:50 -0600495 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
496 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800497 }
John Kessenich78a45572016-07-08 14:05:15 -0600498 return spv::BuiltInLayer;
499
John Kessenich140f3df2015-06-26 16:58:36 -0600500 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600501 case glslang::EbvVertexId: return spv::BuiltInVertexId;
502 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700503 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
504 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800505
John Kessenichda581a22015-10-14 14:10:30 -0600506 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800507 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
508 builder.addCapability(spv::CapabilityDrawParameters);
509 return spv::BuiltInBaseVertex;
510
John Kessenichda581a22015-10-14 14:10:30 -0600511 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800512 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
513 builder.addCapability(spv::CapabilityDrawParameters);
514 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200515
John Kessenichda581a22015-10-14 14:10:30 -0600516 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800517 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
518 builder.addCapability(spv::CapabilityDrawParameters);
519 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200520
521 case glslang::EbvPrimitiveId:
522 if (glslangIntermediate->getStage() == EShLangFragment)
523 builder.addCapability(spv::CapabilityGeometry);
524 return spv::BuiltInPrimitiveId;
525
Rex Xu37cdcee2017-06-29 17:46:34 +0800526 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800527 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
528 builder.addCapability(spv::CapabilityStencilExportEXT);
529 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800530
John Kessenich140f3df2015-06-26 16:58:36 -0600531 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600532 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
533 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
534 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
535 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
536 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
537 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
538 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600539 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
540 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
541 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
542 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
543 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
544 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
545 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
546 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800547
Rex Xu574ab042016-04-14 16:53:07 +0800548 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800549 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800550 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
551 return spv::BuiltInSubgroupSize;
552
Rex Xu574ab042016-04-14 16:53:07 +0800553 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800554 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800555 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
556 return spv::BuiltInSubgroupLocalInvocationId;
557
Rex Xu574ab042016-04-14 16:53:07 +0800558 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800559 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
560 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
561 return spv::BuiltInSubgroupEqMaskKHR;
562
Rex Xu574ab042016-04-14 16:53:07 +0800563 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800564 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
565 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
566 return spv::BuiltInSubgroupGeMaskKHR;
567
Rex Xu574ab042016-04-14 16:53:07 +0800568 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800569 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
570 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
571 return spv::BuiltInSubgroupGtMaskKHR;
572
Rex Xu574ab042016-04-14 16:53:07 +0800573 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800574 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
575 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
576 return spv::BuiltInSubgroupLeMaskKHR;
577
Rex Xu574ab042016-04-14 16:53:07 +0800578 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800579 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
580 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
581 return spv::BuiltInSubgroupLtMaskKHR;
582
Rex Xu9d93a232016-05-05 12:30:44 +0800583#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800584 case glslang::EbvBaryCoordNoPersp:
585 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
586 return spv::BuiltInBaryCoordNoPerspAMD;
587
588 case glslang::EbvBaryCoordNoPerspCentroid:
589 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
590 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
591
592 case glslang::EbvBaryCoordNoPerspSample:
593 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
594 return spv::BuiltInBaryCoordNoPerspSampleAMD;
595
596 case glslang::EbvBaryCoordSmooth:
597 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
598 return spv::BuiltInBaryCoordSmoothAMD;
599
600 case glslang::EbvBaryCoordSmoothCentroid:
601 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
602 return spv::BuiltInBaryCoordSmoothCentroidAMD;
603
604 case glslang::EbvBaryCoordSmoothSample:
605 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
606 return spv::BuiltInBaryCoordSmoothSampleAMD;
607
608 case glslang::EbvBaryCoordPullModel:
609 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
610 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800611#endif
chaoc771d89f2017-01-13 01:10:53 -0800612
John Kessenich6c8aaac2017-02-27 01:20:51 -0700613 case glslang::EbvDeviceIndex:
614 builder.addExtension(spv::E_SPV_KHR_device_group);
615 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700616 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700617
618 case glslang::EbvViewIndex:
619 builder.addExtension(spv::E_SPV_KHR_multiview);
620 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700621 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700622
chaoc771d89f2017-01-13 01:10:53 -0800623#ifdef NV_EXTENSIONS
624 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800625 if (!memberDeclaration) {
626 builder.addExtension(spv::E_SPV_NV_viewport_array2);
627 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
628 }
chaoc771d89f2017-01-13 01:10:53 -0800629 return spv::BuiltInViewportMaskNV;
630 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800631 if (!memberDeclaration) {
632 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
633 builder.addCapability(spv::CapabilityShaderStereoViewNV);
634 }
chaoc771d89f2017-01-13 01:10:53 -0800635 return spv::BuiltInSecondaryPositionNV;
636 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800637 if (!memberDeclaration) {
638 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
639 builder.addCapability(spv::CapabilityShaderStereoViewNV);
640 }
chaoc771d89f2017-01-13 01:10:53 -0800641 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800642 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800643 if (!memberDeclaration) {
644 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
645 builder.addCapability(spv::CapabilityPerViewAttributesNV);
646 }
chaocdf3956c2017-02-14 14:52:34 -0800647 return spv::BuiltInPositionPerViewNV;
648 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800649 if (!memberDeclaration) {
650 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
651 builder.addCapability(spv::CapabilityPerViewAttributesNV);
652 }
chaocdf3956c2017-02-14 14:52:34 -0800653 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700654 case glslang::EbvFragFullyCoveredNV:
655 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
656 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
657 return spv::BuiltInFullyCoveredEXT;
chaoc771d89f2017-01-13 01:10:53 -0800658#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800659 default:
660 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600661 }
662}
663
Rex Xufc618912015-09-09 16:42:49 +0800664// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700665spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800666{
667 assert(type.getBasicType() == glslang::EbtSampler);
668
John Kessenich5d0fa972016-02-15 11:57:00 -0700669 // Check for capabilities
670 switch (type.getQualifier().layoutFormat) {
671 case glslang::ElfRg32f:
672 case glslang::ElfRg16f:
673 case glslang::ElfR11fG11fB10f:
674 case glslang::ElfR16f:
675 case glslang::ElfRgba16:
676 case glslang::ElfRgb10A2:
677 case glslang::ElfRg16:
678 case glslang::ElfRg8:
679 case glslang::ElfR16:
680 case glslang::ElfR8:
681 case glslang::ElfRgba16Snorm:
682 case glslang::ElfRg16Snorm:
683 case glslang::ElfRg8Snorm:
684 case glslang::ElfR16Snorm:
685 case glslang::ElfR8Snorm:
686
687 case glslang::ElfRg32i:
688 case glslang::ElfRg16i:
689 case glslang::ElfRg8i:
690 case glslang::ElfR16i:
691 case glslang::ElfR8i:
692
693 case glslang::ElfRgb10a2ui:
694 case glslang::ElfRg32ui:
695 case glslang::ElfRg16ui:
696 case glslang::ElfRg8ui:
697 case glslang::ElfR16ui:
698 case glslang::ElfR8ui:
699 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
700 break;
701
702 default:
703 break;
704 }
705
706 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800707 switch (type.getQualifier().layoutFormat) {
708 case glslang::ElfNone: return spv::ImageFormatUnknown;
709 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
710 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
711 case glslang::ElfR32f: return spv::ImageFormatR32f;
712 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
713 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
714 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
715 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
716 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
717 case glslang::ElfR16f: return spv::ImageFormatR16f;
718 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
719 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
720 case glslang::ElfRg16: return spv::ImageFormatRg16;
721 case glslang::ElfRg8: return spv::ImageFormatRg8;
722 case glslang::ElfR16: return spv::ImageFormatR16;
723 case glslang::ElfR8: return spv::ImageFormatR8;
724 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
725 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
726 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
727 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
728 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
729 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
730 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
731 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
732 case glslang::ElfR32i: return spv::ImageFormatR32i;
733 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
734 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
735 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
736 case glslang::ElfR16i: return spv::ImageFormatR16i;
737 case glslang::ElfR8i: return spv::ImageFormatR8i;
738 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
739 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
740 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
741 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
742 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
743 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
744 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
745 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
746 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
747 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600748 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800749 }
750}
751
John Kesseniche18fd202018-01-30 11:01:39 -0700752spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(const glslang::TIntermSelection& selectionNode) const
Rex Xu57e65922017-07-04 23:23:40 +0800753{
John Kesseniche18fd202018-01-30 11:01:39 -0700754 if (selectionNode.getFlatten())
755 return spv::SelectionControlFlattenMask;
756 if (selectionNode.getDontFlatten())
757 return spv::SelectionControlDontFlattenMask;
758 return spv::SelectionControlMaskNone;
Rex Xu57e65922017-07-04 23:23:40 +0800759}
760
John Kesseniche18fd202018-01-30 11:01:39 -0700761spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSwitchControl(const glslang::TIntermSwitch& switchNode) const
steve-lunargf1709e72017-05-02 20:14:50 -0600762{
John Kesseniche18fd202018-01-30 11:01:39 -0700763 if (switchNode.getFlatten())
764 return spv::SelectionControlFlattenMask;
765 if (switchNode.getDontFlatten())
766 return spv::SelectionControlDontFlattenMask;
767 return spv::SelectionControlMaskNone;
768}
769
John Kessenicha2858d92018-01-31 08:11:18 -0700770// return a non-0 dependency if the dependency argument must be set
771spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(const glslang::TIntermLoop& loopNode,
772 unsigned int& dependencyLength) const
John Kesseniche18fd202018-01-30 11:01:39 -0700773{
774 spv::LoopControlMask control = spv::LoopControlMaskNone;
775
776 if (loopNode.getDontUnroll())
777 control = control | spv::LoopControlDontUnrollMask;
778 if (loopNode.getUnroll())
779 control = control | spv::LoopControlUnrollMask;
John Kessenicha2858d92018-01-31 08:11:18 -0700780 if (loopNode.getLoopDependency() == glslang::TIntermLoop::dependencyInfinite)
781 control = control | spv::LoopControlDependencyInfiniteMask;
782 else if (loopNode.getLoopDependency() > 0) {
783 control = control | spv::LoopControlDependencyLengthMask;
784 dependencyLength = loopNode.getLoopDependency();
785 }
John Kesseniche18fd202018-01-30 11:01:39 -0700786
787 return control;
steve-lunargf1709e72017-05-02 20:14:50 -0600788}
789
John Kessenicha5c5fb62017-05-05 05:09:58 -0600790// Translate glslang type to SPIR-V storage class.
791spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
792{
793 if (type.getQualifier().isPipeInput())
794 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600795 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600796 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600797
798 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
799 type.getQualifier().storage == glslang::EvqUniform) {
800 if (type.getBasicType() == glslang::EbtAtomicUint)
801 return spv::StorageClassAtomicCounter;
802 if (type.containsOpaque())
803 return spv::StorageClassUniformConstant;
804 }
805
806 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600807 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
808 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600809 }
810
811 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600812 if (type.getQualifier().layoutPushConstant)
813 return spv::StorageClassPushConstant;
814 if (type.getBasicType() == glslang::EbtBlock)
815 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600816 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600817 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600818
819 switch (type.getQualifier().storage) {
820 case glslang::EvqShared: return spv::StorageClassWorkgroup;
821 case glslang::EvqGlobal: return spv::StorageClassPrivate;
822 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
823 case glslang::EvqTemporary: return spv::StorageClassFunction;
824 default:
825 assert(0);
826 break;
827 }
828
829 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600830}
831
qining25262b32016-05-06 17:25:16 -0400832// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700833// descriptor set.
834bool IsDescriptorResource(const glslang::TType& type)
835{
John Kessenichf7497e22016-03-08 21:36:22 -0700836 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700837 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700838 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700839
840 // non block...
841 // basically samplerXXX/subpass/sampler/texture are all included
842 // if they are the global-scope-class, not the function parameter
843 // (or local, if they ever exist) class.
844 if (type.getBasicType() == glslang::EbtSampler)
845 return type.getQualifier().isUniformOrBuffer();
846
847 // None of the above.
848 return false;
849}
850
John Kesseniche0b6cad2015-12-24 10:30:13 -0700851void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
852{
853 if (child.layoutMatrix == glslang::ElmNone)
854 child.layoutMatrix = parent.layoutMatrix;
855
856 if (parent.invariant)
857 child.invariant = true;
858 if (parent.nopersp)
859 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800860#ifdef AMD_EXTENSIONS
861 if (parent.explicitInterp)
862 child.explicitInterp = true;
863#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700864 if (parent.flat)
865 child.flat = true;
866 if (parent.centroid)
867 child.centroid = true;
868 if (parent.patch)
869 child.patch = true;
870 if (parent.sample)
871 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800872 if (parent.coherent)
873 child.coherent = true;
874 if (parent.volatil)
875 child.volatil = true;
876 if (parent.restrict)
877 child.restrict = true;
878 if (parent.readonly)
879 child.readonly = true;
880 if (parent.writeonly)
881 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700882}
883
John Kessenichf2b7f332016-09-01 17:05:23 -0600884bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700885{
John Kessenich7b9fa252016-01-21 18:56:57 -0700886 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600887 // - struct members might inherit from a struct declaration
888 // (note that non-block structs don't explicitly inherit,
889 // only implicitly, meaning no decoration involved)
890 // - affect decorations on the struct members
891 // (note smooth does not, and expecting something like volatile
892 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700893 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600894 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700895}
896
John Kessenich140f3df2015-06-26 16:58:36 -0600897//
898// Implement the TGlslangToSpvTraverser class.
899//
900
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700901TGlslangToSpvTraverser::TGlslangToSpvTraverser(unsigned int spvVersion, const glslang::TIntermediate* glslangIntermediate,
John Kessenich121853f2017-05-31 17:11:16 -0600902 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
903 : TIntermTraverser(true, false, true),
904 options(options),
905 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600906 sequenceDepth(0), logger(buildLogger),
John Kessenich2b5ea9f2018-01-31 18:35:56 -0700907 builder(spvVersion, (glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700908 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600909 glslangIntermediate(glslangIntermediate)
910{
911 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
912
913 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600914 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
915 glslangIntermediate->getVersion());
916
John Kessenich121853f2017-05-31 17:11:16 -0600917 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600918 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600919 builder.setSourceFile(glslangIntermediate->getSourceFile());
920
921 // Set the source shader's text. If for SPV version 1.0, include
922 // a preamble in comments stating the OpModuleProcessed instructions.
923 // Otherwise, emit those as actual instructions.
924 std::string text;
925 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
926 for (int p = 0; p < (int)processes.size(); ++p) {
927 if (glslangIntermediate->getSpv().spv < 0x00010100) {
928 text.append("// OpModuleProcessed ");
929 text.append(processes[p]);
930 text.append("\n");
931 } else
932 builder.addModuleProcessed(processes[p]);
933 }
934 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
935 text.append("#line 1\n");
936 text.append(glslangIntermediate->getSourceText());
937 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600938 }
John Kessenich140f3df2015-06-26 16:58:36 -0600939 stdBuiltins = builder.import("GLSL.std.450");
940 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600941 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
942 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600943
944 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600945 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
946 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600947 builder.addSourceExtension(it->c_str());
948
949 // Add the top-level modes for this shader.
950
John Kessenich92187592016-02-01 13:45:25 -0700951 if (glslangIntermediate->getXfbMode()) {
952 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600953 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700954 }
John Kessenich140f3df2015-06-26 16:58:36 -0600955
956 unsigned int mode;
957 switch (glslangIntermediate->getStage()) {
958 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600959 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600960 break;
961
steve-lunarge7412492017-03-23 11:56:07 -0600962 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600963 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600964 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600965
steve-lunarge7412492017-03-23 11:56:07 -0600966 glslang::TLayoutGeometry primitive;
967
968 if (glslangIntermediate->getStage() == EShLangTessControl) {
969 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
970 primitive = glslangIntermediate->getOutputPrimitive();
971 } else {
972 primitive = glslangIntermediate->getInputPrimitive();
973 }
974
975 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700976 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
977 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
978 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600979 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600980 }
John Kessenich4016e382016-07-15 11:53:56 -0600981 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600982 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
983
John Kesseniche6903322015-10-13 16:29:02 -0600984 switch (glslangIntermediate->getVertexSpacing()) {
985 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
986 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
987 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600988 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600989 }
John Kessenich4016e382016-07-15 11:53:56 -0600990 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600991 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
992
993 switch (glslangIntermediate->getVertexOrder()) {
994 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
995 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600996 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600997 }
John Kessenich4016e382016-07-15 11:53:56 -0600998 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600999 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1000
1001 if (glslangIntermediate->getPointMode())
1002 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -06001003 break;
1004
1005 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -06001006 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -06001007 switch (glslangIntermediate->getInputPrimitive()) {
1008 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
1009 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
1010 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -07001011 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001012 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -06001013 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001014 }
John Kessenich4016e382016-07-15 11:53:56 -06001015 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001016 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -06001017
John Kessenich140f3df2015-06-26 16:58:36 -06001018 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
1019
1020 switch (glslangIntermediate->getOutputPrimitive()) {
1021 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1022 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1023 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001024 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001025 }
John Kessenich4016e382016-07-15 11:53:56 -06001026 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001027 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1028 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1029 break;
1030
1031 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001032 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001033 if (glslangIntermediate->getPixelCenterInteger())
1034 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001035
John Kessenich140f3df2015-06-26 16:58:36 -06001036 if (glslangIntermediate->getOriginUpperLeft())
1037 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001038 else
1039 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001040
1041 if (glslangIntermediate->getEarlyFragmentTests())
1042 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1043
chaocc1204522017-06-30 17:14:30 -07001044 if (glslangIntermediate->getPostDepthCoverage()) {
1045 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1046 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1047 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1048 }
1049
John Kesseniche6903322015-10-13 16:29:02 -06001050 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001051 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1052 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001053 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001054 }
John Kessenich4016e382016-07-15 11:53:56 -06001055 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001056 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1057
1058 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1059 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001060 break;
1061
1062 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001063 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001064 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1065 glslangIntermediate->getLocalSize(1),
1066 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001067 break;
1068
1069 default:
1070 break;
1071 }
John Kessenich140f3df2015-06-26 16:58:36 -06001072}
1073
John Kessenichfca82622016-11-26 13:23:20 -07001074// Finish creating SPV, after the traversal is complete.
1075void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001076{
John Kessenich517fe7a2016-11-26 13:31:47 -07001077 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001078 builder.setBuildPoint(shaderEntry->getLastBlock());
1079 builder.leaveFunction();
1080 }
1081
John Kessenich7ba63412015-12-20 17:37:07 -07001082 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001083 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1084 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001085
qiningda397332016-03-09 19:54:03 -05001086 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001087}
1088
John Kessenichfca82622016-11-26 13:23:20 -07001089// Write the SPV into 'out'.
1090void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001091{
John Kessenichfca82622016-11-26 13:23:20 -07001092 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001093}
1094
1095//
1096// Implement the traversal functions.
1097//
1098// Return true from interior nodes to have the external traversal
1099// continue on to children. Return false if children were
1100// already processed.
1101//
1102
1103//
qining25262b32016-05-06 17:25:16 -04001104// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001105// - uniform/input reads
1106// - output writes
1107// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1108// - something simple that degenerates into the last bullet
1109//
1110void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1111{
qining75d1d802016-04-06 14:42:01 -04001112 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1113 if (symbol->getType().getQualifier().isSpecConstant())
1114 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1115
John Kessenich140f3df2015-06-26 16:58:36 -06001116 // getSymbolId() will set up all the IO decorations on the first call.
1117 // Formal function parameters were mapped during makeFunctions().
1118 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001119
1120 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1121 if (builder.isPointer(id)) {
1122 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001123 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1124 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1125 iOSet.insert(id);
1126 }
John Kessenich7ba63412015-12-20 17:37:07 -07001127 }
1128
1129 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001130 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001131 // Prepare to generate code for the access
1132
1133 // L-value chains will be computed left to right. We're on the symbol now,
1134 // which is the left-most part of the access chain, so now is "clear" time,
1135 // followed by setting the base.
1136 builder.clearAccessChain();
1137
1138 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001139 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001140 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001141 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001142 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001143 // These are also pure R-values.
1144 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001145 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001146 builder.setAccessChainRValue(id);
1147 else
1148 builder.setAccessChainLValue(id);
1149 }
1150}
1151
1152bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1153{
John Kesseniche485c7a2017-05-31 18:50:53 -06001154 builder.setLine(node->getLoc().line);
1155
qining40887662016-04-03 22:20:42 -04001156 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1157 if (node->getType().getQualifier().isSpecConstant())
1158 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1159
John Kessenich140f3df2015-06-26 16:58:36 -06001160 // First, handle special cases
1161 switch (node->getOp()) {
1162 case glslang::EOpAssign:
1163 case glslang::EOpAddAssign:
1164 case glslang::EOpSubAssign:
1165 case glslang::EOpMulAssign:
1166 case glslang::EOpVectorTimesMatrixAssign:
1167 case glslang::EOpVectorTimesScalarAssign:
1168 case glslang::EOpMatrixTimesScalarAssign:
1169 case glslang::EOpMatrixTimesMatrixAssign:
1170 case glslang::EOpDivAssign:
1171 case glslang::EOpModAssign:
1172 case glslang::EOpAndAssign:
1173 case glslang::EOpInclusiveOrAssign:
1174 case glslang::EOpExclusiveOrAssign:
1175 case glslang::EOpLeftShiftAssign:
1176 case glslang::EOpRightShiftAssign:
1177 // A bin-op assign "a += b" means the same thing as "a = a + b"
1178 // where a is evaluated before b. For a simple assignment, GLSL
1179 // says to evaluate the left before the right. So, always, left
1180 // node then right node.
1181 {
1182 // get the left l-value, save it away
1183 builder.clearAccessChain();
1184 node->getLeft()->traverse(this);
1185 spv::Builder::AccessChain lValue = builder.getAccessChain();
1186
1187 // evaluate the right
1188 builder.clearAccessChain();
1189 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001190 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001191
1192 if (node->getOp() != glslang::EOpAssign) {
1193 // the left is also an r-value
1194 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001195 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001196
1197 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001198 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001199 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001200 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1201 node->getType().getBasicType());
1202
1203 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001204 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001205 }
1206
1207 // store the result
1208 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001209 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001210
1211 // assignments are expressions having an rValue after they are evaluated...
1212 builder.clearAccessChain();
1213 builder.setAccessChainRValue(rValue);
1214 }
1215 return false;
1216 case glslang::EOpIndexDirect:
1217 case glslang::EOpIndexDirectStruct:
1218 {
1219 // Get the left part of the access chain.
1220 node->getLeft()->traverse(this);
1221
1222 // Add the next element in the chain
1223
David Netoa901ffe2016-06-08 14:11:40 +01001224 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001225 if (! node->getLeft()->getType().isArray() &&
1226 node->getLeft()->getType().isVector() &&
1227 node->getOp() == glslang::EOpIndexDirect) {
1228 // This is essentially a hard-coded vector swizzle of size 1,
1229 // so short circuit the access-chain stuff with a swizzle.
1230 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001231 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001232 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001233 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001234 int spvIndex = glslangIndex;
1235 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1236 node->getOp() == glslang::EOpIndexDirectStruct)
1237 {
1238 // This may be, e.g., an anonymous block-member selection, which generally need
1239 // index remapping due to hidden members in anonymous blocks.
1240 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1241 assert(remapper.size() > 0);
1242 spvIndex = remapper[glslangIndex];
1243 }
John Kessenichebb50532016-05-16 19:22:05 -06001244
David Netoa901ffe2016-06-08 14:11:40 +01001245 // normal case for indexing array or structure or block
1246 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1247
1248 // Add capabilities here for accessing PointSize and clip/cull distance.
1249 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001250 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001251 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001252 }
1253 }
1254 return false;
1255 case glslang::EOpIndexIndirect:
1256 {
1257 // Structure or array or vector indirection.
1258 // Will use native SPIR-V access-chain for struct and array indirection;
1259 // matrices are arrays of vectors, so will also work for a matrix.
1260 // Will use the access chain's 'component' for variable index into a vector.
1261
1262 // This adapter is building access chains left to right.
1263 // Set up the access chain to the left.
1264 node->getLeft()->traverse(this);
1265
1266 // save it so that computing the right side doesn't trash it
1267 spv::Builder::AccessChain partial = builder.getAccessChain();
1268
1269 // compute the next index in the chain
1270 builder.clearAccessChain();
1271 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001272 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001273
1274 // restore the saved access chain
1275 builder.setAccessChain(partial);
1276
1277 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001278 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001279 else
John Kessenichfa668da2015-09-13 14:46:30 -06001280 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001281 }
1282 return false;
1283 case glslang::EOpVectorSwizzle:
1284 {
1285 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001286 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001287 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001288 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001289 }
1290 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001291 case glslang::EOpMatrixSwizzle:
1292 logger->missingFunctionality("matrix swizzle");
1293 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001294 case glslang::EOpLogicalOr:
1295 case glslang::EOpLogicalAnd:
1296 {
1297
1298 // These may require short circuiting, but can sometimes be done as straight
1299 // binary operations. The right operand must be short circuited if it has
1300 // side effects, and should probably be if it is complex.
1301 if (isTrivial(node->getRight()->getAsTyped()))
1302 break; // handle below as a normal binary operation
1303 // otherwise, we need to do dynamic short circuiting on the right operand
1304 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1305 builder.clearAccessChain();
1306 builder.setAccessChainRValue(result);
1307 }
1308 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001309 default:
1310 break;
1311 }
1312
1313 // Assume generic binary op...
1314
John Kessenich32cfd492016-02-02 12:37:46 -07001315 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001316 builder.clearAccessChain();
1317 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001318 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001319
John Kessenich32cfd492016-02-02 12:37:46 -07001320 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001321 builder.clearAccessChain();
1322 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001323 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001324
John Kessenich32cfd492016-02-02 12:37:46 -07001325 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001326 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001327 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001328 convertGlslangToSpvType(node->getType()), left, right,
1329 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001330
John Kessenich50e57562015-12-21 21:21:11 -07001331 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001332 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001333 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001334 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001335 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001336 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001337 return false;
1338 }
John Kessenich140f3df2015-06-26 16:58:36 -06001339}
1340
1341bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1342{
John Kesseniche485c7a2017-05-31 18:50:53 -06001343 builder.setLine(node->getLoc().line);
1344
qining40887662016-04-03 22:20:42 -04001345 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1346 if (node->getType().getQualifier().isSpecConstant())
1347 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1348
John Kessenichfc51d282015-08-19 13:34:18 -06001349 spv::Id result = spv::NoResult;
1350
1351 // try texturing first
1352 result = createImageTextureFunctionCall(node);
1353 if (result != spv::NoResult) {
1354 builder.clearAccessChain();
1355 builder.setAccessChainRValue(result);
1356
1357 return false; // done with this node
1358 }
1359
1360 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001361
1362 if (node->getOp() == glslang::EOpArrayLength) {
1363 // Quite special; won't want to evaluate the operand.
1364
1365 // Normal .length() would have been constant folded by the front-end.
1366 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001367 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001368 assert(node->getOperand()->getType().isRuntimeSizedArray());
1369 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1370 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001371 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1372 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001373
1374 builder.clearAccessChain();
1375 builder.setAccessChainRValue(length);
1376
1377 return false;
1378 }
1379
John Kessenichfc51d282015-08-19 13:34:18 -06001380 // Start by evaluating the operand
1381
John Kessenich8c8505c2016-07-26 12:50:38 -06001382 // Does it need a swizzle inversion? If so, evaluation is inverted;
1383 // operate first on the swizzle base, then apply the swizzle.
1384 spv::Id invertedType = spv::NoType;
1385 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1386 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1387 invertedType = getInvertedSwizzleType(*node->getOperand());
1388
John Kessenich140f3df2015-06-26 16:58:36 -06001389 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001390 if (invertedType != spv::NoType)
1391 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1392 else
1393 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001394
Rex Xufc618912015-09-09 16:42:49 +08001395 spv::Id operand = spv::NoResult;
1396
1397 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1398 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001399 node->getOp() == glslang::EOpAtomicCounter ||
1400 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001401 operand = builder.accessChainGetLValue(); // Special case l-value operands
1402 else
John Kessenich32cfd492016-02-02 12:37:46 -07001403 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001404
John Kessenichf6640762016-08-01 19:44:00 -06001405 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001406 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001407
1408 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001409 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001410 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001411
1412 // if not, then possibly an operation
1413 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001414 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001415
1416 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001417 if (invertedType)
1418 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1419
John Kessenich140f3df2015-06-26 16:58:36 -06001420 builder.clearAccessChain();
1421 builder.setAccessChainRValue(result);
1422
1423 return false; // done with this node
1424 }
1425
1426 // it must be a special case, check...
1427 switch (node->getOp()) {
1428 case glslang::EOpPostIncrement:
1429 case glslang::EOpPostDecrement:
1430 case glslang::EOpPreIncrement:
1431 case glslang::EOpPreDecrement:
1432 {
1433 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001434 spv::Id one = 0;
1435 if (node->getBasicType() == glslang::EbtFloat)
1436 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001437 else if (node->getBasicType() == glslang::EbtDouble)
1438 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001439#ifdef AMD_EXTENSIONS
1440 else if (node->getBasicType() == glslang::EbtFloat16)
1441 one = builder.makeFloat16Constant(1.0F);
1442#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001443 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1444 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001445#ifdef AMD_EXTENSIONS
1446 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1447 one = builder.makeInt16Constant(1);
1448#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001449 else
1450 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001451 glslang::TOperator op;
1452 if (node->getOp() == glslang::EOpPreIncrement ||
1453 node->getOp() == glslang::EOpPostIncrement)
1454 op = glslang::EOpAdd;
1455 else
1456 op = glslang::EOpSub;
1457
John Kessenichf6640762016-08-01 19:44:00 -06001458 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001459 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001460 convertGlslangToSpvType(node->getType()), operand, one,
1461 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001462 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001463
1464 // The result of operation is always stored, but conditionally the
1465 // consumed result. The consumed result is always an r-value.
1466 builder.accessChainStore(result);
1467 builder.clearAccessChain();
1468 if (node->getOp() == glslang::EOpPreIncrement ||
1469 node->getOp() == glslang::EOpPreDecrement)
1470 builder.setAccessChainRValue(result);
1471 else
1472 builder.setAccessChainRValue(operand);
1473 }
1474
1475 return false;
1476
1477 case glslang::EOpEmitStreamVertex:
1478 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1479 return false;
1480 case glslang::EOpEndStreamPrimitive:
1481 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1482 return false;
1483
1484 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001485 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001486 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001487 }
John Kessenich140f3df2015-06-26 16:58:36 -06001488}
1489
1490bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1491{
qining27e04a02016-04-14 16:40:20 -04001492 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1493 if (node->getType().getQualifier().isSpecConstant())
1494 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1495
John Kessenichfc51d282015-08-19 13:34:18 -06001496 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001497 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1498 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001499
1500 // try texturing
1501 result = createImageTextureFunctionCall(node);
1502 if (result != spv::NoResult) {
1503 builder.clearAccessChain();
1504 builder.setAccessChainRValue(result);
1505
1506 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001507#ifdef AMD_EXTENSIONS
1508 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1509#else
John Kessenich56bab042015-09-16 10:54:31 -06001510 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001511#endif
Rex Xufc618912015-09-09 16:42:49 +08001512 // "imageStore" is a special case, which has no result
1513 return false;
1514 }
John Kessenichfc51d282015-08-19 13:34:18 -06001515
John Kessenich140f3df2015-06-26 16:58:36 -06001516 glslang::TOperator binOp = glslang::EOpNull;
1517 bool reduceComparison = true;
1518 bool isMatrix = false;
1519 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001520 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001521
1522 assert(node->getOp());
1523
John Kessenichf6640762016-08-01 19:44:00 -06001524 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001525
1526 switch (node->getOp()) {
1527 case glslang::EOpSequence:
1528 {
1529 if (preVisit)
1530 ++sequenceDepth;
1531 else
1532 --sequenceDepth;
1533
1534 if (sequenceDepth == 1) {
1535 // If this is the parent node of all the functions, we want to see them
1536 // early, so all call points have actual SPIR-V functions to reference.
1537 // In all cases, still let the traverser visit the children for us.
1538 makeFunctions(node->getAsAggregate()->getSequence());
1539
John Kessenich6fccb3c2016-09-19 16:01:41 -06001540 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001541 // anything else gets there, so visit out of order, doing them all now.
1542 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1543
John Kessenich6a60c2f2016-12-08 21:01:59 -07001544 // 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 -06001545 // so do them manually.
1546 visitFunctions(node->getAsAggregate()->getSequence());
1547
1548 return false;
1549 }
1550
1551 return true;
1552 }
1553 case glslang::EOpLinkerObjects:
1554 {
1555 if (visit == glslang::EvPreVisit)
1556 linkageOnly = true;
1557 else
1558 linkageOnly = false;
1559
1560 return true;
1561 }
1562 case glslang::EOpComma:
1563 {
1564 // processing from left to right naturally leaves the right-most
1565 // lying around in the access chain
1566 glslang::TIntermSequence& glslangOperands = node->getSequence();
1567 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1568 glslangOperands[i]->traverse(this);
1569
1570 return false;
1571 }
1572 case glslang::EOpFunction:
1573 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001574 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001575 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001576 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001577 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001578 } else {
1579 handleFunctionEntry(node);
1580 }
1581 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001582 if (inEntryPoint)
1583 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001584 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001585 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001586 }
1587
1588 return true;
1589 case glslang::EOpParameters:
1590 // Parameters will have been consumed by EOpFunction processing, but not
1591 // the body, so we still visited the function node's children, making this
1592 // child redundant.
1593 return false;
1594 case glslang::EOpFunctionCall:
1595 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001596 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001597 if (node->isUserDefined())
1598 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001599 // 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 -07001600 if (result) {
1601 builder.clearAccessChain();
1602 builder.setAccessChainRValue(result);
1603 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001604 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001605
1606 return false;
1607 }
1608 case glslang::EOpConstructMat2x2:
1609 case glslang::EOpConstructMat2x3:
1610 case glslang::EOpConstructMat2x4:
1611 case glslang::EOpConstructMat3x2:
1612 case glslang::EOpConstructMat3x3:
1613 case glslang::EOpConstructMat3x4:
1614 case glslang::EOpConstructMat4x2:
1615 case glslang::EOpConstructMat4x3:
1616 case glslang::EOpConstructMat4x4:
1617 case glslang::EOpConstructDMat2x2:
1618 case glslang::EOpConstructDMat2x3:
1619 case glslang::EOpConstructDMat2x4:
1620 case glslang::EOpConstructDMat3x2:
1621 case glslang::EOpConstructDMat3x3:
1622 case glslang::EOpConstructDMat3x4:
1623 case glslang::EOpConstructDMat4x2:
1624 case glslang::EOpConstructDMat4x3:
1625 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001626 case glslang::EOpConstructIMat2x2:
1627 case glslang::EOpConstructIMat2x3:
1628 case glslang::EOpConstructIMat2x4:
1629 case glslang::EOpConstructIMat3x2:
1630 case glslang::EOpConstructIMat3x3:
1631 case glslang::EOpConstructIMat3x4:
1632 case glslang::EOpConstructIMat4x2:
1633 case glslang::EOpConstructIMat4x3:
1634 case glslang::EOpConstructIMat4x4:
1635 case glslang::EOpConstructUMat2x2:
1636 case glslang::EOpConstructUMat2x3:
1637 case glslang::EOpConstructUMat2x4:
1638 case glslang::EOpConstructUMat3x2:
1639 case glslang::EOpConstructUMat3x3:
1640 case glslang::EOpConstructUMat3x4:
1641 case glslang::EOpConstructUMat4x2:
1642 case glslang::EOpConstructUMat4x3:
1643 case glslang::EOpConstructUMat4x4:
1644 case glslang::EOpConstructBMat2x2:
1645 case glslang::EOpConstructBMat2x3:
1646 case glslang::EOpConstructBMat2x4:
1647 case glslang::EOpConstructBMat3x2:
1648 case glslang::EOpConstructBMat3x3:
1649 case glslang::EOpConstructBMat3x4:
1650 case glslang::EOpConstructBMat4x2:
1651 case glslang::EOpConstructBMat4x3:
1652 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001653#ifdef AMD_EXTENSIONS
1654 case glslang::EOpConstructF16Mat2x2:
1655 case glslang::EOpConstructF16Mat2x3:
1656 case glslang::EOpConstructF16Mat2x4:
1657 case glslang::EOpConstructF16Mat3x2:
1658 case glslang::EOpConstructF16Mat3x3:
1659 case glslang::EOpConstructF16Mat3x4:
1660 case glslang::EOpConstructF16Mat4x2:
1661 case glslang::EOpConstructF16Mat4x3:
1662 case glslang::EOpConstructF16Mat4x4:
1663#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001664 isMatrix = true;
1665 // fall through
1666 case glslang::EOpConstructFloat:
1667 case glslang::EOpConstructVec2:
1668 case glslang::EOpConstructVec3:
1669 case glslang::EOpConstructVec4:
1670 case glslang::EOpConstructDouble:
1671 case glslang::EOpConstructDVec2:
1672 case glslang::EOpConstructDVec3:
1673 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001674#ifdef AMD_EXTENSIONS
1675 case glslang::EOpConstructFloat16:
1676 case glslang::EOpConstructF16Vec2:
1677 case glslang::EOpConstructF16Vec3:
1678 case glslang::EOpConstructF16Vec4:
1679#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001680 case glslang::EOpConstructBool:
1681 case glslang::EOpConstructBVec2:
1682 case glslang::EOpConstructBVec3:
1683 case glslang::EOpConstructBVec4:
1684 case glslang::EOpConstructInt:
1685 case glslang::EOpConstructIVec2:
1686 case glslang::EOpConstructIVec3:
1687 case glslang::EOpConstructIVec4:
1688 case glslang::EOpConstructUint:
1689 case glslang::EOpConstructUVec2:
1690 case glslang::EOpConstructUVec3:
1691 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001692 case glslang::EOpConstructInt64:
1693 case glslang::EOpConstructI64Vec2:
1694 case glslang::EOpConstructI64Vec3:
1695 case glslang::EOpConstructI64Vec4:
1696 case glslang::EOpConstructUint64:
1697 case glslang::EOpConstructU64Vec2:
1698 case glslang::EOpConstructU64Vec3:
1699 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001700#ifdef AMD_EXTENSIONS
1701 case glslang::EOpConstructInt16:
1702 case glslang::EOpConstructI16Vec2:
1703 case glslang::EOpConstructI16Vec3:
1704 case glslang::EOpConstructI16Vec4:
1705 case glslang::EOpConstructUint16:
1706 case glslang::EOpConstructU16Vec2:
1707 case glslang::EOpConstructU16Vec3:
1708 case glslang::EOpConstructU16Vec4:
1709#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001710 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001711 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001712 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001713 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001714 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001715 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001716 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001717 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001718 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001719 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001720 std::vector<spv::Id> constituents;
1721 for (int c = 0; c < (int)arguments.size(); ++c)
1722 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001723 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001724 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001725 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001726 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001727 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001728
1729 builder.clearAccessChain();
1730 builder.setAccessChainRValue(constructed);
1731
1732 return false;
1733 }
1734
1735 // These six are component-wise compares with component-wise results.
1736 // Forward on to createBinaryOperation(), requesting a vector result.
1737 case glslang::EOpLessThan:
1738 case glslang::EOpGreaterThan:
1739 case glslang::EOpLessThanEqual:
1740 case glslang::EOpGreaterThanEqual:
1741 case glslang::EOpVectorEqual:
1742 case glslang::EOpVectorNotEqual:
1743 {
1744 // Map the operation to a binary
1745 binOp = node->getOp();
1746 reduceComparison = false;
1747 switch (node->getOp()) {
1748 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1749 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1750 default: binOp = node->getOp(); break;
1751 }
1752
1753 break;
1754 }
1755 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001756 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001757 binOp = glslang::EOpMul;
1758 break;
1759 case glslang::EOpOuterProduct:
1760 // two vectors multiplied to make a matrix
1761 binOp = glslang::EOpOuterProduct;
1762 break;
1763 case glslang::EOpDot:
1764 {
qining25262b32016-05-06 17:25:16 -04001765 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001766 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001767 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001768 binOp = glslang::EOpMul;
1769 break;
1770 }
1771 case glslang::EOpMod:
1772 // when an aggregate, this is the floating-point mod built-in function,
1773 // which can be emitted by the one in createBinaryOperation()
1774 binOp = glslang::EOpMod;
1775 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001776 case glslang::EOpEmitVertex:
1777 case glslang::EOpEndPrimitive:
1778 case glslang::EOpBarrier:
1779 case glslang::EOpMemoryBarrier:
1780 case glslang::EOpMemoryBarrierAtomicCounter:
1781 case glslang::EOpMemoryBarrierBuffer:
1782 case glslang::EOpMemoryBarrierImage:
1783 case glslang::EOpMemoryBarrierShared:
1784 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07001785 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001786 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07001787 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001788 case glslang::EOpWorkgroupMemoryBarrier:
1789 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001790 noReturnValue = true;
1791 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1792 break;
1793
John Kessenich426394d2015-07-23 10:22:48 -06001794 case glslang::EOpAtomicAdd:
1795 case glslang::EOpAtomicMin:
1796 case glslang::EOpAtomicMax:
1797 case glslang::EOpAtomicAnd:
1798 case glslang::EOpAtomicOr:
1799 case glslang::EOpAtomicXor:
1800 case glslang::EOpAtomicExchange:
1801 case glslang::EOpAtomicCompSwap:
1802 atomic = true;
1803 break;
1804
John Kessenich0d0c6d32017-07-23 16:08:26 -06001805 case glslang::EOpAtomicCounterAdd:
1806 case glslang::EOpAtomicCounterSubtract:
1807 case glslang::EOpAtomicCounterMin:
1808 case glslang::EOpAtomicCounterMax:
1809 case glslang::EOpAtomicCounterAnd:
1810 case glslang::EOpAtomicCounterOr:
1811 case glslang::EOpAtomicCounterXor:
1812 case glslang::EOpAtomicCounterExchange:
1813 case glslang::EOpAtomicCounterCompSwap:
1814 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1815 builder.addCapability(spv::CapabilityAtomicStorageOps);
1816 atomic = true;
1817 break;
1818
John Kessenich140f3df2015-06-26 16:58:36 -06001819 default:
1820 break;
1821 }
1822
1823 //
1824 // See if it maps to a regular operation.
1825 //
John Kessenich140f3df2015-06-26 16:58:36 -06001826 if (binOp != glslang::EOpNull) {
1827 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1828 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1829 assert(left && right);
1830
1831 builder.clearAccessChain();
1832 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001833 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001834
1835 builder.clearAccessChain();
1836 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001837 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001838
John Kesseniche485c7a2017-05-31 18:50:53 -06001839 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001840 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001841 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001842 left->getType().getBasicType(), reduceComparison);
1843
1844 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001845 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001846 builder.clearAccessChain();
1847 builder.setAccessChainRValue(result);
1848
1849 return false;
1850 }
1851
John Kessenich426394d2015-07-23 10:22:48 -06001852 //
1853 // Create the list of operands.
1854 //
John Kessenich140f3df2015-06-26 16:58:36 -06001855 glslang::TIntermSequence& glslangOperands = node->getSequence();
1856 std::vector<spv::Id> operands;
1857 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001858 // special case l-value operands; there are just a few
1859 bool lvalue = false;
1860 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001861 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001862 case glslang::EOpModf:
1863 if (arg == 1)
1864 lvalue = true;
1865 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001866 case glslang::EOpInterpolateAtSample:
1867 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001868#ifdef AMD_EXTENSIONS
1869 case glslang::EOpInterpolateAtVertex:
1870#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001871 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001872 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001873
1874 // Does it need a swizzle inversion? If so, evaluation is inverted;
1875 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001876 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001877 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1878 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1879 }
Rex Xu7a26c172015-12-08 17:12:09 +08001880 break;
Rex Xud4782c12015-09-06 16:30:11 +08001881 case glslang::EOpAtomicAdd:
1882 case glslang::EOpAtomicMin:
1883 case glslang::EOpAtomicMax:
1884 case glslang::EOpAtomicAnd:
1885 case glslang::EOpAtomicOr:
1886 case glslang::EOpAtomicXor:
1887 case glslang::EOpAtomicExchange:
1888 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001889 case glslang::EOpAtomicCounterAdd:
1890 case glslang::EOpAtomicCounterSubtract:
1891 case glslang::EOpAtomicCounterMin:
1892 case glslang::EOpAtomicCounterMax:
1893 case glslang::EOpAtomicCounterAnd:
1894 case glslang::EOpAtomicCounterOr:
1895 case glslang::EOpAtomicCounterXor:
1896 case glslang::EOpAtomicCounterExchange:
1897 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001898 if (arg == 0)
1899 lvalue = true;
1900 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001901 case glslang::EOpAddCarry:
1902 case glslang::EOpSubBorrow:
1903 if (arg == 2)
1904 lvalue = true;
1905 break;
1906 case glslang::EOpUMulExtended:
1907 case glslang::EOpIMulExtended:
1908 if (arg >= 2)
1909 lvalue = true;
1910 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001911 default:
1912 break;
1913 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001914 builder.clearAccessChain();
1915 if (invertedType != spv::NoType && arg == 0)
1916 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1917 else
1918 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001919 if (lvalue)
1920 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001921 else {
1922 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001923 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001924 }
John Kessenich140f3df2015-06-26 16:58:36 -06001925 }
John Kessenich426394d2015-07-23 10:22:48 -06001926
John Kesseniche485c7a2017-05-31 18:50:53 -06001927 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001928 if (atomic) {
1929 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001930 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001931 } else {
1932 // Pass through to generic operations.
1933 switch (glslangOperands.size()) {
1934 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001935 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001936 break;
1937 case 1:
qining25262b32016-05-06 17:25:16 -04001938 result = createUnaryOperation(
1939 node->getOp(), precision,
1940 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001941 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001942 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001943 break;
1944 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001945 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001946 break;
1947 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001948 if (invertedType)
1949 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001950 }
1951
1952 if (noReturnValue)
1953 return false;
1954
1955 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001956 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001957 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001958 } else {
1959 builder.clearAccessChain();
1960 builder.setAccessChainRValue(result);
1961 return false;
1962 }
1963}
1964
John Kessenich433e9ff2017-01-26 20:31:11 -07001965// This path handles both if-then-else and ?:
1966// The if-then-else has a node type of void, while
1967// ?: has either a void or a non-void node type
1968//
1969// Leaving the result, when not void:
1970// GLSL only has r-values as the result of a :?, but
1971// if we have an l-value, that can be more efficient if it will
1972// become the base of a complex r-value expression, because the
1973// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001974bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1975{
John Kessenich433e9ff2017-01-26 20:31:11 -07001976 // See if it simple and safe to generate OpSelect instead of using control flow.
1977 // Crucially, side effects must be avoided, and there are performance trade-offs.
1978 // Return true if good idea (and safe) for OpSelect, false otherwise.
1979 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001980 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1981 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001982 return false;
1983
1984 if (node->getTrueBlock() == nullptr ||
1985 node->getFalseBlock() == nullptr)
1986 return false;
1987
1988 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1989 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1990
1991 // return true if a single operand to ? : is okay for OpSelect
1992 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001993 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001994 };
1995
1996 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1997 operandOkay(node->getFalseBlock()->getAsTyped());
1998 };
1999
2000 // Emit OpSelect for this selection.
2001 const auto handleAsOpSelect = [&]() {
2002 node->getCondition()->traverse(this);
2003 spv::Id condition = accessChainLoad(node->getCondition()->getType());
2004 node->getTrueBlock()->traverse(this);
2005 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2006 node->getFalseBlock()->traverse(this);
2007 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
2008
John Kesseniche485c7a2017-05-31 18:50:53 -06002009 builder.setLine(node->getLoc().line);
2010
John Kesseniche434ad92017-03-30 10:09:28 -06002011 // smear condition to vector, if necessary (AST is always scalar)
2012 if (builder.isVector(trueValue))
2013 condition = builder.smearScalar(spv::NoPrecision, condition,
2014 builder.makeVectorType(builder.makeBoolType(),
2015 builder.getNumComponents(trueValue)));
2016
2017 spv::Id select = builder.createTriOp(spv::OpSelect,
2018 convertGlslangToSpvType(node->getType()), condition,
2019 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07002020 builder.clearAccessChain();
2021 builder.setAccessChainRValue(select);
2022 };
2023
2024 // Try for OpSelect
2025
2026 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002027 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2028 if (node->getType().getQualifier().isSpecConstant())
2029 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2030
John Kessenich433e9ff2017-01-26 20:31:11 -07002031 handleAsOpSelect();
2032 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002033 }
2034
Rex Xu57e65922017-07-04 23:23:40 +08002035 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07002036 // Don't handle results as temporaries, because there will be two names
2037 // and better to leave SSA to later passes.
2038 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
2039 ? spv::NoResult
2040 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2041
John Kessenich140f3df2015-06-26 16:58:36 -06002042 // emit the condition before doing anything with selection
2043 node->getCondition()->traverse(this);
2044
Rex Xu57e65922017-07-04 23:23:40 +08002045 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002046 const spv::SelectionControlMask control = TranslateSelectionControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002047
John Kessenich140f3df2015-06-26 16:58:36 -06002048 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08002049 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06002050
John Kessenich433e9ff2017-01-26 20:31:11 -07002051 // emit the "then" statement
2052 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002053 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002054 if (result != spv::NoResult)
2055 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002056 }
2057
John Kessenich433e9ff2017-01-26 20:31:11 -07002058 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002059 ifBuilder.makeBeginElse();
2060 // emit the "else" statement
2061 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002062 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07002063 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002064 }
2065
John Kessenich433e9ff2017-01-26 20:31:11 -07002066 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06002067 ifBuilder.makeEndIf();
2068
John Kessenich433e9ff2017-01-26 20:31:11 -07002069 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06002070 // GLSL only has r-values as the result of a :?, but
2071 // if we have an l-value, that can be more efficient if it will
2072 // become the base of a complex r-value expression, because the
2073 // next layer copies r-values into memory to use the access-chain mechanism
2074 builder.clearAccessChain();
2075 builder.setAccessChainLValue(result);
2076 }
2077
2078 return false;
2079}
2080
2081bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2082{
2083 // emit and get the condition before doing anything with switch
2084 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002085 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002086
Rex Xu57e65922017-07-04 23:23:40 +08002087 // Selection control:
John Kesseniche18fd202018-01-30 11:01:39 -07002088 const spv::SelectionControlMask control = TranslateSwitchControl(*node);
Rex Xu57e65922017-07-04 23:23:40 +08002089
John Kessenich140f3df2015-06-26 16:58:36 -06002090 // browse the children to sort out code segments
2091 int defaultSegment = -1;
2092 std::vector<TIntermNode*> codeSegments;
2093 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2094 std::vector<int> caseValues;
2095 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2096 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2097 TIntermNode* child = *c;
2098 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002099 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002100 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002101 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002102 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2103 } else
2104 codeSegments.push_back(child);
2105 }
2106
qining25262b32016-05-06 17:25:16 -04002107 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002108 // statements between the last case and the end of the switch statement
2109 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2110 (int)codeSegments.size() == defaultSegment)
2111 codeSegments.push_back(nullptr);
2112
2113 // make the switch statement
2114 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002115 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002116
2117 // emit all the code in the segments
2118 breakForLoop.push(false);
2119 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2120 builder.nextSwitchSegment(segmentBlocks, s);
2121 if (codeSegments[s])
2122 codeSegments[s]->traverse(this);
2123 else
2124 builder.addSwitchBreak();
2125 }
2126 breakForLoop.pop();
2127
2128 builder.endSwitch(segmentBlocks);
2129
2130 return false;
2131}
2132
2133void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2134{
2135 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002136 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002137
2138 builder.clearAccessChain();
2139 builder.setAccessChainRValue(constant);
2140}
2141
2142bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2143{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002144 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002145 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002146
2147 // Loop control:
John Kessenicha2858d92018-01-31 08:11:18 -07002148 unsigned int dependencyLength = glslang::TIntermLoop::dependencyInfinite;
2149 const spv::LoopControlMask control = TranslateLoopControl(*node, dependencyLength);
steve-lunargf1709e72017-05-02 20:14:50 -06002150
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002151 // Spec requires back edges to target header blocks, and every header block
2152 // must dominate its merge block. Make a header block first to ensure these
2153 // conditions are met. By definition, it will contain OpLoopMerge, followed
2154 // by a block-ending branch. But we don't want to put any other body/test
2155 // instructions in it, since the body/test may have arbitrary instructions,
2156 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002157 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002158 builder.setBuildPoint(&blocks.head);
John Kessenicha2858d92018-01-31 08:11:18 -07002159 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control, dependencyLength);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002160 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002161 spv::Block& test = builder.makeNewBlock();
2162 builder.createBranch(&test);
2163
2164 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002165 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002166 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002167 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2168
2169 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002170 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002171 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002172 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002173 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002174 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002175
2176 builder.setBuildPoint(&blocks.continue_target);
2177 if (node->getTerminal())
2178 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002179 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002180 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002181 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002182 builder.createBranch(&blocks.body);
2183
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002184 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002185 builder.setBuildPoint(&blocks.body);
2186 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002187 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002188 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002189 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002190
2191 builder.setBuildPoint(&blocks.continue_target);
2192 if (node->getTerminal())
2193 node->getTerminal()->traverse(this);
2194 if (node->getTest()) {
2195 node->getTest()->traverse(this);
2196 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002197 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002198 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002199 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002200 // TODO: unless there was a break/return/discard instruction
2201 // somewhere in the body, this is an infinite loop, so we should
2202 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002203 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002204 }
John Kessenich140f3df2015-06-26 16:58:36 -06002205 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002206 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002207 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002208 return false;
2209}
2210
2211bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2212{
2213 if (node->getExpression())
2214 node->getExpression()->traverse(this);
2215
John Kesseniche485c7a2017-05-31 18:50:53 -06002216 builder.setLine(node->getLoc().line);
2217
John Kessenich140f3df2015-06-26 16:58:36 -06002218 switch (node->getFlowOp()) {
2219 case glslang::EOpKill:
2220 builder.makeDiscard();
2221 break;
2222 case glslang::EOpBreak:
2223 if (breakForLoop.top())
2224 builder.createLoopExit();
2225 else
2226 builder.addSwitchBreak();
2227 break;
2228 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002229 builder.createLoopContinue();
2230 break;
2231 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002232 if (node->getExpression()) {
2233 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2234 spv::Id returnId = accessChainLoad(glslangReturnType);
2235 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2236 builder.clearAccessChain();
2237 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2238 builder.setAccessChainLValue(copyId);
2239 multiTypeStore(glslangReturnType, returnId);
2240 returnId = builder.createLoad(copyId);
2241 }
2242 builder.makeReturn(false, returnId);
2243 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002244 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002245
2246 builder.clearAccessChain();
2247 break;
2248
2249 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002250 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002251 break;
2252 }
2253
2254 return false;
2255}
2256
2257spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2258{
qining25262b32016-05-06 17:25:16 -04002259 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002260 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002261 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002262 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002263 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002264 }
2265
2266 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002267 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002268 spv::Id spvType = convertGlslangToSpvType(node->getType());
2269
Rex Xuf89ad982017-04-07 23:22:33 +08002270#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002271 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2272 node->getType().containsBasicType(glslang::EbtInt16) ||
2273 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002274 if (contains16BitType) {
2275 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2276 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2277 builder.addCapability(spv::CapabilityStorageInputOutput16);
2278 } else if (storageClass == spv::StorageClassPushConstant) {
2279 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2280 builder.addCapability(spv::CapabilityStoragePushConstant16);
2281 } else if (storageClass == spv::StorageClassUniform) {
2282 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2283 builder.addCapability(spv::CapabilityStorageUniform16);
2284 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2285 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2286 }
2287 }
2288#endif
2289
John Kessenich140f3df2015-06-26 16:58:36 -06002290 const char* name = node->getName().c_str();
2291 if (glslang::IsAnonymous(name))
2292 name = "";
2293
2294 return builder.createVariable(storageClass, spvType, name);
2295}
2296
2297// Return type Id of the sampled type.
2298spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2299{
2300 switch (sampler.type) {
2301 case glslang::EbtFloat: return builder.makeFloatType(32);
2302 case glslang::EbtInt: return builder.makeIntType(32);
2303 case glslang::EbtUint: return builder.makeUintType(32);
2304 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002305 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002306 return builder.makeFloatType(32);
2307 }
2308}
2309
John Kessenich8c8505c2016-07-26 12:50:38 -06002310// If node is a swizzle operation, return the type that should be used if
2311// the swizzle base is first consumed by another operation, before the swizzle
2312// is applied.
2313spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2314{
John Kessenichecba76f2017-01-06 00:34:48 -07002315 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002316 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2317 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2318 else
2319 return spv::NoType;
2320}
2321
2322// When inverting a swizzle with a parent op, this function
2323// will apply the swizzle operation to a completed parent operation.
2324spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2325{
2326 std::vector<unsigned> swizzle;
2327 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2328 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2329}
2330
John Kessenich8c8505c2016-07-26 12:50:38 -06002331// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2332void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2333{
2334 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2335 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2336 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2337}
2338
John Kessenich3ac051e2015-12-20 11:29:16 -07002339// Convert from a glslang type to an SPV type, by calling into a
2340// recursive version of this function. This establishes the inherited
2341// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002342spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2343{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002344 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002345}
2346
2347// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002348// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002349// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002350spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002351{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002352 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002353
2354 switch (type.getBasicType()) {
2355 case glslang::EbtVoid:
2356 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002357 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002358 break;
2359 case glslang::EbtFloat:
2360 spvType = builder.makeFloatType(32);
2361 break;
2362 case glslang::EbtDouble:
2363 spvType = builder.makeFloatType(64);
2364 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002365#ifdef AMD_EXTENSIONS
2366 case glslang::EbtFloat16:
2367 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002368 spvType = builder.makeFloatType(16);
2369 break;
2370#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002371 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002372 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2373 // a 32-bit int where non-0 means true.
2374 if (explicitLayout != glslang::ElpNone)
2375 spvType = builder.makeUintType(32);
2376 else
2377 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002378 break;
2379 case glslang::EbtInt:
2380 spvType = builder.makeIntType(32);
2381 break;
2382 case glslang::EbtUint:
2383 spvType = builder.makeUintType(32);
2384 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002385 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002386 spvType = builder.makeIntType(64);
2387 break;
2388 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002389 spvType = builder.makeUintType(64);
2390 break;
Rex Xucabbb782017-03-24 13:41:14 +08002391#ifdef AMD_EXTENSIONS
2392 case glslang::EbtInt16:
2393 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2394 spvType = builder.makeIntType(16);
2395 break;
2396 case glslang::EbtUint16:
2397 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2398 spvType = builder.makeUintType(16);
2399 break;
2400#endif
John Kessenich426394d2015-07-23 10:22:48 -06002401 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002402 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002403 spvType = builder.makeUintType(32);
2404 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002405 case glslang::EbtSampler:
2406 {
2407 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002408 if (sampler.sampler) {
2409 // pure sampler
2410 spvType = builder.makeSamplerType();
2411 } else {
2412 // an image is present, make its type
2413 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2414 sampler.image ? 2 : 1, TranslateImageFormat(type));
2415 if (sampler.combined) {
2416 // already has both image and sampler, make the combined type
2417 spvType = builder.makeSampledImageType(spvType);
2418 }
John Kessenich55e7d112015-11-15 21:33:39 -07002419 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002420 }
John Kessenich140f3df2015-06-26 16:58:36 -06002421 break;
2422 case glslang::EbtStruct:
2423 case glslang::EbtBlock:
2424 {
2425 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002426 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002427
2428 // Try to share structs for different layouts, but not yet for other
2429 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002430 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002431 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002432 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002433 break;
2434
2435 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002436 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002437 memberRemapper[glslangMembers].resize(glslangMembers->size());
2438 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002439 }
2440 break;
2441 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002442 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002443 break;
2444 }
2445
2446 if (type.isMatrix())
2447 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2448 else {
2449 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2450 if (type.getVectorSize() > 1)
2451 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2452 }
2453
2454 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002455 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2456
John Kessenichc9a80832015-09-12 12:17:44 -06002457 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002458 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002459 // We need to decorate array strides for types needing explicit layout, except blocks.
2460 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002461 // Use a dummy glslang type for querying internal strides of
2462 // arrays of arrays, but using just a one-dimensional array.
2463 glslang::TType simpleArrayType(type, 0); // deference type of the array
2464 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2465 simpleArrayType.getArraySizes().dereference();
2466
2467 // Will compute the higher-order strides here, rather than making a whole
2468 // pile of types and doing repetitive recursion on their contents.
2469 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2470 }
John Kessenichf8842e52016-01-04 19:22:56 -07002471
2472 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002473 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002474 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002475 if (stride > 0)
2476 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002477 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002478 }
2479 } else {
2480 // single-dimensional array, and don't yet have stride
2481
John Kessenichf8842e52016-01-04 19:22:56 -07002482 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002483 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2484 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002485 }
John Kessenich31ed4832015-09-09 17:51:38 -06002486
John Kessenichc9a80832015-09-12 12:17:44 -06002487 // Do the outer dimension, which might not be known for a runtime-sized array
2488 if (type.isRuntimeSizedArray()) {
2489 spvType = builder.makeRuntimeArray(spvType);
2490 } else {
2491 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002492 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002493 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002494 if (stride > 0)
2495 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002496 }
2497
2498 return spvType;
2499}
2500
John Kessenich0e737842017-03-24 18:38:16 -06002501// TODO: this functionality should exist at a higher level, in creating the AST
2502//
2503// Identify interface members that don't have their required extension turned on.
2504//
2505bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2506{
2507 auto& extensions = glslangIntermediate->getRequestedExtensions();
2508
Rex Xubcf291a2017-03-29 23:01:36 +08002509 if (member.getFieldName() == "gl_ViewportMask" &&
2510 extensions.find("GL_NV_viewport_array2") == extensions.end())
2511 return true;
2512 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2513 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2514 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002515 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2516 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2517 return true;
2518 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2519 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2520 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002521 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2522 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2523 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002524
2525 return false;
2526};
2527
John Kessenich6090df02016-06-30 21:18:02 -06002528// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2529// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2530// Mutually recursive with convertGlslangToSpvType().
2531spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2532 const glslang::TTypeList* glslangMembers,
2533 glslang::TLayoutPacking explicitLayout,
2534 const glslang::TQualifier& qualifier)
2535{
2536 // Create a vector of struct types for SPIR-V to consume
2537 std::vector<spv::Id> spvMembers;
2538 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 -06002539 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2540 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2541 if (glslangMember.hiddenMember()) {
2542 ++memberDelta;
2543 if (type.getBasicType() == glslang::EbtBlock)
2544 memberRemapper[glslangMembers][i] = -1;
2545 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002546 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002547 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002548 if (filterMember(glslangMember))
2549 continue;
2550 }
John Kessenich6090df02016-06-30 21:18:02 -06002551 // modify just this child's view of the qualifier
2552 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2553 InheritQualifiers(memberQualifier, qualifier);
2554
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002555 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002556 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002557 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002558
2559 // recurse
2560 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2561 }
2562 }
2563
2564 // Make the SPIR-V type
2565 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002566 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002567 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2568
2569 // Decorate it
2570 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2571
2572 return spvType;
2573}
2574
2575void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2576 const glslang::TTypeList* glslangMembers,
2577 glslang::TLayoutPacking explicitLayout,
2578 const glslang::TQualifier& qualifier,
2579 spv::Id spvType)
2580{
2581 // Name and decorate the non-hidden members
2582 int offset = -1;
2583 int locationOffset = 0; // for use within the members of this struct
2584 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2585 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2586 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002587 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002588 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002589 if (filterMember(glslangMember))
2590 continue;
2591 }
John Kessenich6090df02016-06-30 21:18:02 -06002592
2593 // modify just this child's view of the qualifier
2594 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2595 InheritQualifiers(memberQualifier, qualifier);
2596
2597 // using -1 above to indicate a hidden member
2598 if (member >= 0) {
2599 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2600 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2601 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2602 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002603 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2604 type.getQualifier().storage == glslang::EvqVaryingOut) {
2605 if (type.getBasicType() == glslang::EbtBlock ||
2606 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002607 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2608 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2609 }
2610 }
2611 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2612
Rex Xu286ca432017-07-27 14:33:16 +08002613 if (type.getBasicType() == glslang::EbtBlock &&
2614 qualifier.storage == glslang::EvqBuffer) {
2615 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002616 std::vector<spv::Decoration> memory;
2617 TranslateMemoryDecoration(memberQualifier, memory);
2618 for (unsigned int i = 0; i < memory.size(); ++i)
2619 addMemberDecoration(spvType, member, memory[i]);
2620 }
2621
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002622 // Location assignment was already completed correctly by the front end,
2623 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002624 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002625 // ill-specified and decisions have been made to not allow this.
2626 if (! type.isArray() && memberQualifier.hasLocation())
2627 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002628
John Kessenich2f47bc92016-06-30 21:47:35 -06002629 if (qualifier.hasLocation()) // track for upcoming inheritance
2630 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2631
John Kessenich6090df02016-06-30 21:18:02 -06002632 // component, XFB, others
2633 if (glslangMember.getQualifier().hasComponent())
2634 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2635 if (glslangMember.getQualifier().hasXfbOffset())
2636 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2637 else if (explicitLayout != glslang::ElpNone) {
2638 // figure out what to do with offset, which is accumulating
2639 int nextOffset;
2640 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2641 if (offset >= 0)
2642 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2643 offset = nextOffset;
2644 }
2645
2646 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2647 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2648
2649 // built-in variable decorations
2650 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002651 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002652 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002653
2654#ifdef NV_EXTENSIONS
2655 if (builtIn == spv::BuiltInLayer) {
2656 // SPV_NV_viewport_array2 extension
2657 if (glslangMember.getQualifier().layoutViewportRelative){
2658 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2659 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2660 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2661 }
2662 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2663 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2664 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2665 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2666 }
2667 }
chaocdf3956c2017-02-14 14:52:34 -08002668 if (glslangMember.getQualifier().layoutPassthrough) {
2669 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2670 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2671 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2672 }
chaoc771d89f2017-01-13 01:10:53 -08002673#endif
John Kessenich6090df02016-06-30 21:18:02 -06002674 }
2675 }
2676
2677 // Decorate the structure
2678 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002679 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002680 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2681 builder.addCapability(spv::CapabilityGeometryStreams);
2682 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2683 }
John Kessenich6090df02016-06-30 21:18:02 -06002684}
2685
John Kessenich6c292d32016-02-15 20:58:50 -07002686// Turn the expression forming the array size into an id.
2687// This is not quite trivial, because of specialization constants.
2688// Sometimes, a raw constant is turned into an Id, and sometimes
2689// a specialization constant expression is.
2690spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2691{
2692 // First, see if this is sized with a node, meaning a specialization constant:
2693 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2694 if (specNode != nullptr) {
2695 builder.clearAccessChain();
2696 specNode->traverse(this);
2697 return accessChainLoad(specNode->getAsTyped()->getType());
2698 }
qining25262b32016-05-06 17:25:16 -04002699
John Kessenich6c292d32016-02-15 20:58:50 -07002700 // Otherwise, need a compile-time (front end) size, get it:
2701 int size = arraySizes.getDimSize(dim);
2702 assert(size > 0);
2703 return builder.makeUintConstant(size);
2704}
2705
John Kessenich103bef92016-02-08 21:38:15 -07002706// Wrap the builder's accessChainLoad to:
2707// - localize handling of RelaxedPrecision
2708// - use the SPIR-V inferred type instead of another conversion of the glslang type
2709// (avoids unnecessary work and possible type punning for structures)
2710// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002711spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2712{
John Kessenich103bef92016-02-08 21:38:15 -07002713 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2714 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2715
2716 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002717 if (type.getBasicType() == glslang::EbtBool) {
2718 if (builder.isScalarType(nominalTypeId)) {
2719 // Conversion for bool
2720 spv::Id boolType = builder.makeBoolType();
2721 if (nominalTypeId != boolType)
2722 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2723 } else if (builder.isVectorType(nominalTypeId)) {
2724 // Conversion for bvec
2725 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2726 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2727 if (nominalTypeId != bvecType)
2728 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2729 }
2730 }
John Kessenich103bef92016-02-08 21:38:15 -07002731
2732 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002733}
2734
Rex Xu27253232016-02-23 17:51:09 +08002735// Wrap the builder's accessChainStore to:
2736// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002737//
2738// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002739void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2740{
2741 // Need to convert to abstract types when necessary
2742 if (type.getBasicType() == glslang::EbtBool) {
2743 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2744
2745 if (builder.isScalarType(nominalTypeId)) {
2746 // Conversion for bool
2747 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002748 if (nominalTypeId != boolType) {
2749 // keep these outside arguments, for determinant order-of-evaluation
2750 spv::Id one = builder.makeUintConstant(1);
2751 spv::Id zero = builder.makeUintConstant(0);
2752 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2753 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002754 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002755 } else if (builder.isVectorType(nominalTypeId)) {
2756 // Conversion for bvec
2757 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2758 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002759 if (nominalTypeId != bvecType) {
2760 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002761 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2762 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2763 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002764 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002765 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2766 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002767 }
2768 }
2769
2770 builder.accessChainStore(rvalue);
2771}
2772
John Kessenich4bf71552016-09-02 11:20:21 -06002773// For storing when types match at the glslang level, but not might match at the
2774// SPIR-V level.
2775//
2776// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002777// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002778// as in a member-decorated way.
2779//
2780// NOTE: This function can handle any store request; if it's not special it
2781// simplifies to a simple OpStore.
2782//
2783// Implicitly uses the existing builder.accessChain as the storage target.
2784void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2785{
John Kessenichb3e24e42016-09-11 12:33:43 -06002786 // we only do the complex path here if it's an aggregate
2787 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002788 accessChainStore(type, rValue);
2789 return;
2790 }
2791
John Kessenichb3e24e42016-09-11 12:33:43 -06002792 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002793 spv::Id rType = builder.getTypeId(rValue);
2794 spv::Id lValue = builder.accessChainGetLValue();
2795 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2796 if (lType == rType) {
2797 accessChainStore(type, rValue);
2798 return;
2799 }
2800
John Kessenichb3e24e42016-09-11 12:33:43 -06002801 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002802 // where the two types were the same type in GLSL. This requires member
2803 // by member copy, recursively.
2804
John Kessenichb3e24e42016-09-11 12:33:43 -06002805 // If an array, copy element by element.
2806 if (type.isArray()) {
2807 glslang::TType glslangElementType(type, 0);
2808 spv::Id elementRType = builder.getContainedTypeId(rType);
2809 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2810 // get the source member
2811 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002812
John Kessenichb3e24e42016-09-11 12:33:43 -06002813 // set up the target storage
2814 builder.clearAccessChain();
2815 builder.setAccessChainLValue(lValue);
2816 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002817
John Kessenichb3e24e42016-09-11 12:33:43 -06002818 // store the member
2819 multiTypeStore(glslangElementType, elementRValue);
2820 }
2821 } else {
2822 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002823
John Kessenichb3e24e42016-09-11 12:33:43 -06002824 // loop over structure members
2825 const glslang::TTypeList& members = *type.getStruct();
2826 for (int m = 0; m < (int)members.size(); ++m) {
2827 const glslang::TType& glslangMemberType = *members[m].type;
2828
2829 // get the source member
2830 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2831 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2832
2833 // set up the target storage
2834 builder.clearAccessChain();
2835 builder.setAccessChainLValue(lValue);
2836 builder.accessChainPush(builder.makeIntConstant(m));
2837
2838 // store the member
2839 multiTypeStore(glslangMemberType, memberRValue);
2840 }
John Kessenich4bf71552016-09-02 11:20:21 -06002841 }
2842}
2843
John Kessenichf85e8062015-12-19 13:57:10 -07002844// Decide whether or not this type should be
2845// decorated with offsets and strides, and if so
2846// whether std140 or std430 rules should be applied.
2847glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002848{
John Kessenichf85e8062015-12-19 13:57:10 -07002849 // has to be a block
2850 if (type.getBasicType() != glslang::EbtBlock)
2851 return glslang::ElpNone;
2852
2853 // has to be a uniform or buffer block
2854 if (type.getQualifier().storage != glslang::EvqUniform &&
2855 type.getQualifier().storage != glslang::EvqBuffer)
2856 return glslang::ElpNone;
2857
2858 // return the layout to use
2859 switch (type.getQualifier().layoutPacking) {
2860 case glslang::ElpStd140:
2861 case glslang::ElpStd430:
2862 return type.getQualifier().layoutPacking;
2863 default:
2864 return glslang::ElpNone;
2865 }
John Kessenich31ed4832015-09-09 17:51:38 -06002866}
2867
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002868// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002869int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002870{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002871 int size;
John Kessenich49987892015-12-29 17:11:44 -07002872 int stride;
2873 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002874
2875 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002876}
2877
John Kessenich49987892015-12-29 17:11:44 -07002878// 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 -07002879// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002880int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002881{
John Kessenich49987892015-12-29 17:11:44 -07002882 glslang::TType elementType;
2883 elementType.shallowCopy(matrixType);
2884 elementType.clearArraySizes();
2885
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002886 int size;
John Kessenich49987892015-12-29 17:11:44 -07002887 int stride;
2888 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2889
2890 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002891}
2892
John Kessenich5e4b1242015-08-06 22:53:06 -06002893// Given a member type of a struct, realign the current offset for it, and compute
2894// the next (not yet aligned) offset for the next member, which will get aligned
2895// on the next call.
2896// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2897// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2898// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002899void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002900 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002901{
2902 // this will get a positive value when deemed necessary
2903 nextOffset = -1;
2904
John Kessenich5e4b1242015-08-06 22:53:06 -06002905 // override anything in currentOffset with user-set offset
2906 if (memberType.getQualifier().hasOffset())
2907 currentOffset = memberType.getQualifier().layoutOffset;
2908
2909 // It could be that current linker usage in glslang updated all the layoutOffset,
2910 // in which case the following code does not matter. But, that's not quite right
2911 // once cross-compilation unit GLSL validation is done, as the original user
2912 // settings are needed in layoutOffset, and then the following will come into play.
2913
John Kessenichf85e8062015-12-19 13:57:10 -07002914 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002915 if (! memberType.getQualifier().hasOffset())
2916 currentOffset = -1;
2917
2918 return;
2919 }
2920
John Kessenichf85e8062015-12-19 13:57:10 -07002921 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002922 if (currentOffset < 0)
2923 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002924
John Kessenich5e4b1242015-08-06 22:53:06 -06002925 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2926 // but possibly not yet correctly aligned.
2927
2928 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002929 int dummyStride;
2930 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002931
2932 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002933 // TODO: make this consistent in early phases of code:
2934 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2935 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2936 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002937 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002938 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002939 int dummySize;
2940 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2941 if (componentAlignment <= 4)
2942 memberAlignment = componentAlignment;
2943 }
2944
2945 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002946 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002947
2948 // Bump up to vec4 if there is a bad straddle
2949 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2950 glslang::RoundToPow2(currentOffset, 16);
2951
John Kessenich5e4b1242015-08-06 22:53:06 -06002952 nextOffset = currentOffset + memberSize;
2953}
2954
David Netoa901ffe2016-06-08 14:11:40 +01002955void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002956{
David Netoa901ffe2016-06-08 14:11:40 +01002957 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2958 switch (glslangBuiltIn)
2959 {
2960 case glslang::EbvClipDistance:
2961 case glslang::EbvCullDistance:
2962 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002963#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08002964 case glslang::EbvViewportMaskNV:
2965 case glslang::EbvSecondaryPositionNV:
2966 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002967 case glslang::EbvPositionPerViewNV:
2968 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002969#endif
David Netoa901ffe2016-06-08 14:11:40 +01002970 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2971 // Alternately, we could just call this for any glslang built-in, since the
2972 // capability already guards against duplicates.
2973 TranslateBuiltInDecoration(glslangBuiltIn, false);
2974 break;
2975 default:
2976 // Capabilities were already generated when the struct was declared.
2977 break;
2978 }
John Kessenichebb50532016-05-16 19:22:05 -06002979}
2980
John Kessenich6fccb3c2016-09-19 16:01:41 -06002981bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002982{
John Kessenicheee9d532016-09-19 18:09:30 -06002983 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002984}
2985
John Kessenichd41993d2017-09-10 15:21:05 -06002986// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07002987// Assumes called after originalParam(), which filters out block/buffer/opaque-based
2988// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd41993d2017-09-10 15:21:05 -06002989bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier)
2990{
John Kessenich6a14f782017-12-04 02:48:10 -07002991 assert(qualifier == glslang::EvqIn ||
2992 qualifier == glslang::EvqOut ||
2993 qualifier == glslang::EvqInOut ||
2994 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06002995 return qualifier != glslang::EvqConstReadOnly;
2996}
2997
2998// Is parameter pass-by-original?
2999bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
3000 bool implicitThisParam)
3001{
3002 if (implicitThisParam) // implicit this
3003 return true;
3004 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07003005 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06003006 return paramType.containsOpaque() || // sampler, etc.
3007 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
3008}
3009
John Kessenich140f3df2015-06-26 16:58:36 -06003010// Make all the functions, skeletally, without actually visiting their bodies.
3011void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
3012{
John Kessenichfad62972017-07-18 02:35:46 -06003013 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
3014 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
3015 if (paramPrecision != spv::NoPrecision)
3016 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06003017 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06003018 };
3019
John Kessenich140f3df2015-06-26 16:58:36 -06003020 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3021 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003022 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003023 continue;
3024
3025 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003026 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003027 //
qining25262b32016-05-06 17:25:16 -04003028 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003029 // function. What it is an address of varies:
3030 //
John Kessenich4bf71552016-09-02 11:20:21 -06003031 // - "in" parameters not marked as "const" can be written to without modifying the calling
3032 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003033 //
3034 // - "const in" parameters can just be the r-value, as no writes need occur.
3035 //
John Kessenich4bf71552016-09-02 11:20:21 -06003036 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3037 // 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 -06003038
3039 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003040 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003041 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3042
John Kessenichfad62972017-07-18 02:35:46 -06003043 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3044 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003045
John Kessenichfad62972017-07-18 02:35:46 -06003046 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003047 for (int p = 0; p < (int)parameters.size(); ++p) {
3048 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3049 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003050 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003051 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003052 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003053 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3054 else
John Kessenich4bf71552016-09-02 11:20:21 -06003055 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003056 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003057 paramTypes.push_back(typeId);
3058 }
3059
3060 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003061 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3062 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003063 glslFunction->getName().c_str(), paramTypes,
3064 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003065 if (implicitThis)
3066 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003067
3068 // Track function to emit/call later
3069 functionMap[glslFunction->getName().c_str()] = function;
3070
3071 // Set the parameter id's
3072 for (int p = 0; p < (int)parameters.size(); ++p) {
3073 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3074 // give a name too
3075 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3076 }
3077 }
3078}
3079
3080// Process all the initializers, while skipping the functions and link objects
3081void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3082{
3083 builder.setBuildPoint(shaderEntry->getLastBlock());
3084 for (int i = 0; i < (int)initializers.size(); ++i) {
3085 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3086 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3087
3088 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003089 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003090 initializer->traverse(this);
3091 }
3092 }
3093}
3094
3095// Process all the functions, while skipping initializers.
3096void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3097{
3098 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3099 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003100 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003101 node->traverse(this);
3102 }
3103}
3104
3105void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3106{
qining25262b32016-05-06 17:25:16 -04003107 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003108 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003109 currentFunction = functionMap[node->getName().c_str()];
3110 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003111 builder.setBuildPoint(functionBlock);
3112}
3113
Rex Xu04db3f52015-09-16 11:44:02 +08003114void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003115{
Rex Xufc618912015-09-09 16:42:49 +08003116 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003117
3118 glslang::TSampler sampler = {};
3119 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003120 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003121 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3122 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3123 }
3124
John Kessenich140f3df2015-06-26 16:58:36 -06003125 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3126 builder.clearAccessChain();
3127 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003128
3129 // Special case l-value operands
3130 bool lvalue = false;
3131 switch (node.getOp()) {
3132 case glslang::EOpImageAtomicAdd:
3133 case glslang::EOpImageAtomicMin:
3134 case glslang::EOpImageAtomicMax:
3135 case glslang::EOpImageAtomicAnd:
3136 case glslang::EOpImageAtomicOr:
3137 case glslang::EOpImageAtomicXor:
3138 case glslang::EOpImageAtomicExchange:
3139 case glslang::EOpImageAtomicCompSwap:
3140 if (i == 0)
3141 lvalue = true;
3142 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003143 case glslang::EOpSparseImageLoad:
3144 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3145 lvalue = true;
3146 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003147 case glslang::EOpSparseTexture:
3148 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3149 lvalue = true;
3150 break;
3151 case glslang::EOpSparseTextureClamp:
3152 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3153 lvalue = true;
3154 break;
3155 case glslang::EOpSparseTextureLod:
3156 case glslang::EOpSparseTextureOffset:
3157 if (i == 3)
3158 lvalue = true;
3159 break;
3160 case glslang::EOpSparseTextureFetch:
3161 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3162 lvalue = true;
3163 break;
3164 case glslang::EOpSparseTextureFetchOffset:
3165 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3166 lvalue = true;
3167 break;
3168 case glslang::EOpSparseTextureLodOffset:
3169 case glslang::EOpSparseTextureGrad:
3170 case glslang::EOpSparseTextureOffsetClamp:
3171 if (i == 4)
3172 lvalue = true;
3173 break;
3174 case glslang::EOpSparseTextureGradOffset:
3175 case glslang::EOpSparseTextureGradClamp:
3176 if (i == 5)
3177 lvalue = true;
3178 break;
3179 case glslang::EOpSparseTextureGradOffsetClamp:
3180 if (i == 6)
3181 lvalue = true;
3182 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003183 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003184 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3185 lvalue = true;
3186 break;
3187 case glslang::EOpSparseTextureGatherOffset:
3188 case glslang::EOpSparseTextureGatherOffsets:
3189 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3190 lvalue = true;
3191 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003192#ifdef AMD_EXTENSIONS
3193 case glslang::EOpSparseTextureGatherLod:
3194 if (i == 3)
3195 lvalue = true;
3196 break;
3197 case glslang::EOpSparseTextureGatherLodOffset:
3198 case glslang::EOpSparseTextureGatherLodOffsets:
3199 if (i == 4)
3200 lvalue = true;
3201 break;
Rex Xu129799a2017-07-05 17:23:28 +08003202 case glslang::EOpSparseImageLoadLod:
3203 if (i == 3)
3204 lvalue = true;
3205 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003206#endif
Rex Xufc618912015-09-09 16:42:49 +08003207 default:
3208 break;
3209 }
3210
Rex Xu6b86d492015-09-16 17:48:22 +08003211 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003212 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003213 else
John Kessenich32cfd492016-02-02 12:37:46 -07003214 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003215 }
3216}
3217
John Kessenichfc51d282015-08-19 13:34:18 -06003218void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003219{
John Kessenichfc51d282015-08-19 13:34:18 -06003220 builder.clearAccessChain();
3221 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003222 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003223}
John Kessenich140f3df2015-06-26 16:58:36 -06003224
John Kessenichfc51d282015-08-19 13:34:18 -06003225spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3226{
John Kesseniche485c7a2017-05-31 18:50:53 -06003227 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003228 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003229
3230 builder.setLine(node->getLoc().line);
3231
John Kessenich8c8505c2016-07-26 12:50:38 -06003232 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003233
John Kessenichfc51d282015-08-19 13:34:18 -06003234 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003235 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3236 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3237 std::vector<spv::Id> arguments;
3238 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003239 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003240 else
3241 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003242 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003243
3244 spv::Builder::TextureParameters params = { };
3245 params.sampler = arguments[0];
3246
Rex Xu04db3f52015-09-16 11:44:02 +08003247 glslang::TCrackedTextureOp cracked;
3248 node->crackTexture(sampler, cracked);
3249
amhagan05506bb2017-06-13 16:53:02 -04003250 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003251
John Kessenichfc51d282015-08-19 13:34:18 -06003252 // Check for queries
3253 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003254 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3255 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003256 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003257
John Kessenichfc51d282015-08-19 13:34:18 -06003258 switch (node->getOp()) {
3259 case glslang::EOpImageQuerySize:
3260 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003261 if (arguments.size() > 1) {
3262 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003263 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003264 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003265 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003266 case glslang::EOpImageQuerySamples:
3267 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003268 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003269 case glslang::EOpTextureQueryLod:
3270 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003271 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003272 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003273 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003274 case glslang::EOpSparseTexelsResident:
3275 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003276 default:
3277 assert(0);
3278 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003279 }
John Kessenich140f3df2015-06-26 16:58:36 -06003280 }
3281
Rex Xufc618912015-09-09 16:42:49 +08003282 // Check for image functions other than queries
3283 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003284 std::vector<spv::Id> operands;
3285 auto opIt = arguments.begin();
3286 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003287
3288 // Handle subpass operations
3289 // TODO: GLSL should change to have the "MS" only on the type rather than the
3290 // built-in function.
3291 if (cracked.subpass) {
3292 // add on the (0,0) coordinate
3293 spv::Id zero = builder.makeIntConstant(0);
3294 std::vector<spv::Id> comps;
3295 comps.push_back(zero);
3296 comps.push_back(zero);
3297 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3298 if (sampler.ms) {
3299 operands.push_back(spv::ImageOperandsSampleMask);
3300 operands.push_back(*(opIt++));
3301 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003302 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3303 builder.setPrecision(result, precision);
3304 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003305 }
3306
John Kessenich56bab042015-09-16 10:54:31 -06003307 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003308#ifdef AMD_EXTENSIONS
3309 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3310#else
John Kessenich56bab042015-09-16 10:54:31 -06003311 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003312#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003313 if (sampler.ms) {
3314 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003315 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003316#ifdef AMD_EXTENSIONS
3317 } else if (cracked.lod) {
3318 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3319 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3320
3321 operands.push_back(spv::ImageOperandsLodMask);
3322 operands.push_back(*opIt);
3323#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003324 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003325 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3326 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003327
3328 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3329 builder.setPrecision(result, precision);
3330 return result;
Rex Xu129799a2017-07-05 17:23:28 +08003331#ifdef AMD_EXTENSIONS
3332 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3333#else
John Kessenich56bab042015-09-16 10:54:31 -06003334 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003335#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003336 if (sampler.ms) {
3337 operands.push_back(*(opIt + 1));
3338 operands.push_back(spv::ImageOperandsSampleMask);
3339 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003340#ifdef AMD_EXTENSIONS
3341 } else if (cracked.lod) {
3342 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3343 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3344
3345 operands.push_back(*(opIt + 1));
3346 operands.push_back(spv::ImageOperandsLodMask);
3347 operands.push_back(*opIt);
3348#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003349 } else
3350 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003351 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003352 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3353 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003354 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003355#ifdef AMD_EXTENSIONS
3356 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3357#else
Rex Xu5eafa472016-02-19 22:24:03 +08003358 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003359#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003360 builder.addCapability(spv::CapabilitySparseResidency);
3361 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3362 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3363
3364 if (sampler.ms) {
3365 operands.push_back(spv::ImageOperandsSampleMask);
3366 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003367#ifdef AMD_EXTENSIONS
3368 } else if (cracked.lod) {
3369 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3370 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3371
3372 operands.push_back(spv::ImageOperandsLodMask);
3373 operands.push_back(*opIt++);
3374#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003375 }
3376
3377 // Create the return type that was a special structure
3378 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003379 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003380 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3381 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3382
3383 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3384
3385 // Decode the return type
3386 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3387 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003388 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003389 // Process image atomic operations
3390
3391 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3392 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003393 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003394
John Kessenich8c8505c2016-07-26 12:50:38 -06003395 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003396 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003397
3398 std::vector<spv::Id> operands;
3399 operands.push_back(pointer);
3400 for (; opIt != arguments.end(); ++opIt)
3401 operands.push_back(*opIt);
3402
John Kessenich8c8505c2016-07-26 12:50:38 -06003403 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003404 }
3405 }
3406
amhagan05506bb2017-06-13 16:53:02 -04003407#ifdef AMD_EXTENSIONS
3408 // Check for fragment mask functions other than queries
3409 if (cracked.fragMask) {
3410 assert(sampler.ms);
3411
3412 auto opIt = arguments.begin();
3413 std::vector<spv::Id> operands;
3414
3415 // Extract the image if necessary
3416 if (builder.isSampledImage(params.sampler))
3417 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3418
3419 operands.push_back(params.sampler);
3420 ++opIt;
3421
3422 if (sampler.isSubpass()) {
3423 // add on the (0,0) coordinate
3424 spv::Id zero = builder.makeIntConstant(0);
3425 std::vector<spv::Id> comps;
3426 comps.push_back(zero);
3427 comps.push_back(zero);
3428 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3429 }
3430
3431 for (; opIt != arguments.end(); ++opIt)
3432 operands.push_back(*opIt);
3433
3434 spv::Op fragMaskOp = spv::OpNop;
3435 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3436 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3437 else if (node->getOp() == glslang::EOpFragmentFetch)
3438 fragMaskOp = spv::OpFragmentFetchAMD;
3439
3440 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3441 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3442 return builder.createOp(fragMaskOp, resultType(), operands);
3443 }
3444#endif
3445
Rex Xufc618912015-09-09 16:42:49 +08003446 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003447 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003448 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3449
John Kessenichfc51d282015-08-19 13:34:18 -06003450 // check for bias argument
3451 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003452#ifdef AMD_EXTENSIONS
3453 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3454#else
Rex Xu71519fe2015-11-11 15:35:47 +08003455 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003456#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003457 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003458#ifdef AMD_EXTENSIONS
3459 if (cracked.gather)
3460 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3461#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003462 if (cracked.offset)
3463 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003464#ifdef AMD_EXTENSIONS
3465 else if (cracked.offsets)
3466 ++nonBiasArgCount;
3467#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003468 if (cracked.grad)
3469 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003470 if (cracked.lodClamp)
3471 ++nonBiasArgCount;
3472 if (sparse)
3473 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003474
3475 if ((int)arguments.size() > nonBiasArgCount)
3476 bias = true;
3477 }
3478
John Kessenicha5c33d62016-06-02 23:45:21 -06003479 // See if the sampler param should really be just the SPV image part
3480 if (cracked.fetch) {
3481 // a fetch needs to have the image extracted first
3482 if (builder.isSampledImage(params.sampler))
3483 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3484 }
3485
Rex Xu225e0fc2016-11-17 17:47:59 +08003486#ifdef AMD_EXTENSIONS
3487 if (cracked.gather) {
3488 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3489 if (bias || cracked.lod ||
3490 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3491 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003492 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003493 }
3494 }
3495#endif
3496
John Kessenichfc51d282015-08-19 13:34:18 -06003497 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003498
John Kessenichfc51d282015-08-19 13:34:18 -06003499 params.coords = arguments[1];
3500 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003501 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003502
3503 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003504 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003505 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003506 ++extraArgs;
3507 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003508 params.Dref = arguments[2];
3509 ++extraArgs;
3510 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003511 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003512 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003513 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003514 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003515 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003516 dRefComp = builder.getNumComponents(params.coords) - 1;
3517 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003518 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3519 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003520
3521 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003522 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003523 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003524 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003525 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3526 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3527 noImplicitLod = true;
3528 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003529
3530 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003531 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003532 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003533 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003534 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003535
3536 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003537 if (cracked.grad) {
3538 params.gradX = arguments[2 + extraArgs];
3539 params.gradY = arguments[3 + extraArgs];
3540 extraArgs += 2;
3541 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003542
3543 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003544 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003545 params.offset = arguments[2 + extraArgs];
3546 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003547 } else if (cracked.offsets) {
3548 params.offsets = arguments[2 + extraArgs];
3549 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003550 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003551
3552 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003553 if (cracked.lodClamp) {
3554 params.lodClamp = arguments[2 + extraArgs];
3555 ++extraArgs;
3556 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003557
3558 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003559 if (sparse) {
3560 params.texelOut = arguments[2 + extraArgs];
3561 ++extraArgs;
3562 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003563
John Kessenich76d4dfc2016-06-16 12:43:23 -06003564 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003565 if (cracked.gather && ! sampler.shadow) {
3566 // default component is 0, if missing, otherwise an argument
3567 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003568 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003569 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003570 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003571 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003572 }
3573
3574 // bias
3575 if (bias) {
3576 params.bias = arguments[2 + extraArgs];
3577 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003578 }
John Kessenichfc51d282015-08-19 13:34:18 -06003579
John Kessenich65336482016-06-16 14:06:26 -06003580 // projective component (might not to move)
3581 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3582 // are divided by the last component of P."
3583 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3584 // unused components will appear after all used components."
3585 if (cracked.proj) {
3586 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3587 int projTargetComp;
3588 switch (sampler.dim) {
3589 case glslang::Esd1D: projTargetComp = 1; break;
3590 case glslang::Esd2D: projTargetComp = 2; break;
3591 case glslang::EsdRect: projTargetComp = 2; break;
3592 default: projTargetComp = projSourceComp; break;
3593 }
3594 // copy the projective coordinate if we have to
3595 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003596 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003597 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3598 projSourceComp);
3599 params.coords = builder.createCompositeInsert(projComp, params.coords,
3600 builder.getTypeId(params.coords), projTargetComp);
3601 }
3602 }
3603
John Kessenich8c8505c2016-07-26 12:50:38 -06003604 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003605}
3606
3607spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3608{
3609 // Grab the function's pointer from the previously created function
3610 spv::Function* function = functionMap[node->getName().c_str()];
3611 if (! function)
3612 return 0;
3613
3614 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3615 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3616
3617 // See comments in makeFunctions() for details about the semantics for parameter passing.
3618 //
3619 // These imply we need a four step process:
3620 // 1. Evaluate the arguments
3621 // 2. Allocate and make copies of in, out, and inout arguments
3622 // 3. Make the call
3623 // 4. Copy back the results
3624
3625 // 1. Evaluate the arguments
3626 std::vector<spv::Builder::AccessChain> lValues;
3627 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003628 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003629 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003630 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003631 // build l-value
3632 builder.clearAccessChain();
3633 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003634 argTypes.push_back(&paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003635 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenich6a14f782017-12-04 02:48:10 -07003636 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0) ||
3637 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003638 // save l-value
3639 lValues.push_back(builder.getAccessChain());
3640 } else {
3641 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003642 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003643 }
3644 }
3645
3646 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3647 // copy the original into that space.
3648 //
3649 // Also, build up the list of actual arguments to pass in for the call
3650 int lValueCount = 0;
3651 int rValueCount = 0;
3652 std::vector<spv::Id> spvArgs;
3653 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003654 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003655 spv::Id arg;
John Kessenichd41993d2017-09-10 15:21:05 -06003656 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003657 builder.setAccessChain(lValues[lValueCount]);
3658 arg = builder.accessChainGetLValue();
3659 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06003660 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003661 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003662 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3663 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3664 // need to copy the input into output space
3665 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003666 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003667 builder.clearAccessChain();
3668 builder.setAccessChainLValue(arg);
3669 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003670 }
3671 ++lValueCount;
3672 } else {
3673 arg = rValues[rValueCount];
3674 ++rValueCount;
3675 }
3676 spvArgs.push_back(arg);
3677 }
3678
3679 // 3. Make the call.
3680 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003681 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003682
3683 // 4. Copy back out an "out" arguments.
3684 lValueCount = 0;
3685 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003686 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenichd41993d2017-09-10 15:21:05 -06003687 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0))
3688 ++lValueCount;
3689 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003690 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3691 spv::Id copy = builder.createLoad(spvArgs[a]);
3692 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003693 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003694 }
3695 ++lValueCount;
3696 }
3697 }
3698
3699 return result;
3700}
3701
3702// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003703spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3704 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003705 spv::Id typeId, spv::Id left, spv::Id right,
3706 glslang::TBasicType typeProxy, bool reduceComparison)
3707{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003708#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003709 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003710 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3711#else
Rex Xucabbb782017-03-24 13:41:14 +08003712 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003713 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003714#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003715 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003716
3717 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003718 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003719 bool comparison = false;
3720
3721 switch (op) {
3722 case glslang::EOpAdd:
3723 case glslang::EOpAddAssign:
3724 if (isFloat)
3725 binOp = spv::OpFAdd;
3726 else
3727 binOp = spv::OpIAdd;
3728 break;
3729 case glslang::EOpSub:
3730 case glslang::EOpSubAssign:
3731 if (isFloat)
3732 binOp = spv::OpFSub;
3733 else
3734 binOp = spv::OpISub;
3735 break;
3736 case glslang::EOpMul:
3737 case glslang::EOpMulAssign:
3738 if (isFloat)
3739 binOp = spv::OpFMul;
3740 else
3741 binOp = spv::OpIMul;
3742 break;
3743 case glslang::EOpVectorTimesScalar:
3744 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003745 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003746 if (builder.isVector(right))
3747 std::swap(left, right);
3748 assert(builder.isScalar(right));
3749 needMatchingVectors = false;
3750 binOp = spv::OpVectorTimesScalar;
3751 } else
3752 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003753 break;
3754 case glslang::EOpVectorTimesMatrix:
3755 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003756 binOp = spv::OpVectorTimesMatrix;
3757 break;
3758 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003759 binOp = spv::OpMatrixTimesVector;
3760 break;
3761 case glslang::EOpMatrixTimesScalar:
3762 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003763 binOp = spv::OpMatrixTimesScalar;
3764 break;
3765 case glslang::EOpMatrixTimesMatrix:
3766 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003767 binOp = spv::OpMatrixTimesMatrix;
3768 break;
3769 case glslang::EOpOuterProduct:
3770 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003771 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003772 break;
3773
3774 case glslang::EOpDiv:
3775 case glslang::EOpDivAssign:
3776 if (isFloat)
3777 binOp = spv::OpFDiv;
3778 else if (isUnsigned)
3779 binOp = spv::OpUDiv;
3780 else
3781 binOp = spv::OpSDiv;
3782 break;
3783 case glslang::EOpMod:
3784 case glslang::EOpModAssign:
3785 if (isFloat)
3786 binOp = spv::OpFMod;
3787 else if (isUnsigned)
3788 binOp = spv::OpUMod;
3789 else
3790 binOp = spv::OpSMod;
3791 break;
3792 case glslang::EOpRightShift:
3793 case glslang::EOpRightShiftAssign:
3794 if (isUnsigned)
3795 binOp = spv::OpShiftRightLogical;
3796 else
3797 binOp = spv::OpShiftRightArithmetic;
3798 break;
3799 case glslang::EOpLeftShift:
3800 case glslang::EOpLeftShiftAssign:
3801 binOp = spv::OpShiftLeftLogical;
3802 break;
3803 case glslang::EOpAnd:
3804 case glslang::EOpAndAssign:
3805 binOp = spv::OpBitwiseAnd;
3806 break;
3807 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003808 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003809 binOp = spv::OpLogicalAnd;
3810 break;
3811 case glslang::EOpInclusiveOr:
3812 case glslang::EOpInclusiveOrAssign:
3813 binOp = spv::OpBitwiseOr;
3814 break;
3815 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003816 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003817 binOp = spv::OpLogicalOr;
3818 break;
3819 case glslang::EOpExclusiveOr:
3820 case glslang::EOpExclusiveOrAssign:
3821 binOp = spv::OpBitwiseXor;
3822 break;
3823 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003824 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003825 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003826 break;
3827
3828 case glslang::EOpLessThan:
3829 case glslang::EOpGreaterThan:
3830 case glslang::EOpLessThanEqual:
3831 case glslang::EOpGreaterThanEqual:
3832 case glslang::EOpEqual:
3833 case glslang::EOpNotEqual:
3834 case glslang::EOpVectorEqual:
3835 case glslang::EOpVectorNotEqual:
3836 comparison = true;
3837 break;
3838 default:
3839 break;
3840 }
3841
John Kessenich7c1aa102015-10-15 13:29:11 -06003842 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003843 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003844 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003845 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003846 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003847
3848 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003849 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003850 builder.promoteScalar(precision, left, right);
3851
qining25262b32016-05-06 17:25:16 -04003852 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3853 addDecoration(result, noContraction);
3854 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003855 }
3856
3857 if (! comparison)
3858 return 0;
3859
John Kessenich7c1aa102015-10-15 13:29:11 -06003860 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003861
John Kessenich4583b612016-08-07 19:14:22 -06003862 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3863 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003864 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003865
3866 switch (op) {
3867 case glslang::EOpLessThan:
3868 if (isFloat)
3869 binOp = spv::OpFOrdLessThan;
3870 else if (isUnsigned)
3871 binOp = spv::OpULessThan;
3872 else
3873 binOp = spv::OpSLessThan;
3874 break;
3875 case glslang::EOpGreaterThan:
3876 if (isFloat)
3877 binOp = spv::OpFOrdGreaterThan;
3878 else if (isUnsigned)
3879 binOp = spv::OpUGreaterThan;
3880 else
3881 binOp = spv::OpSGreaterThan;
3882 break;
3883 case glslang::EOpLessThanEqual:
3884 if (isFloat)
3885 binOp = spv::OpFOrdLessThanEqual;
3886 else if (isUnsigned)
3887 binOp = spv::OpULessThanEqual;
3888 else
3889 binOp = spv::OpSLessThanEqual;
3890 break;
3891 case glslang::EOpGreaterThanEqual:
3892 if (isFloat)
3893 binOp = spv::OpFOrdGreaterThanEqual;
3894 else if (isUnsigned)
3895 binOp = spv::OpUGreaterThanEqual;
3896 else
3897 binOp = spv::OpSGreaterThanEqual;
3898 break;
3899 case glslang::EOpEqual:
3900 case glslang::EOpVectorEqual:
3901 if (isFloat)
3902 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003903 else if (isBool)
3904 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003905 else
3906 binOp = spv::OpIEqual;
3907 break;
3908 case glslang::EOpNotEqual:
3909 case glslang::EOpVectorNotEqual:
3910 if (isFloat)
3911 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003912 else if (isBool)
3913 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003914 else
3915 binOp = spv::OpINotEqual;
3916 break;
3917 default:
3918 break;
3919 }
3920
qining25262b32016-05-06 17:25:16 -04003921 if (binOp != spv::OpNop) {
3922 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3923 addDecoration(result, noContraction);
3924 return builder.setPrecision(result, precision);
3925 }
John Kessenich140f3df2015-06-26 16:58:36 -06003926
3927 return 0;
3928}
3929
John Kessenich04bb8a02015-12-12 12:28:14 -07003930//
3931// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3932// These can be any of:
3933//
3934// matrix * scalar
3935// scalar * matrix
3936// matrix * matrix linear algebraic
3937// matrix * vector
3938// vector * matrix
3939// matrix * matrix componentwise
3940// matrix op matrix op in {+, -, /}
3941// matrix op scalar op in {+, -, /}
3942// scalar op matrix op in {+, -, /}
3943//
qining25262b32016-05-06 17:25:16 -04003944spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07003945{
3946 bool firstClass = true;
3947
3948 // First, handle first-class matrix operations (* and matrix/scalar)
3949 switch (op) {
3950 case spv::OpFDiv:
3951 if (builder.isMatrix(left) && builder.isScalar(right)) {
3952 // turn matrix / scalar into a multiply...
3953 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3954 op = spv::OpMatrixTimesScalar;
3955 } else
3956 firstClass = false;
3957 break;
3958 case spv::OpMatrixTimesScalar:
3959 if (builder.isMatrix(right))
3960 std::swap(left, right);
3961 assert(builder.isScalar(right));
3962 break;
3963 case spv::OpVectorTimesMatrix:
3964 assert(builder.isVector(left));
3965 assert(builder.isMatrix(right));
3966 break;
3967 case spv::OpMatrixTimesVector:
3968 assert(builder.isMatrix(left));
3969 assert(builder.isVector(right));
3970 break;
3971 case spv::OpMatrixTimesMatrix:
3972 assert(builder.isMatrix(left));
3973 assert(builder.isMatrix(right));
3974 break;
3975 default:
3976 firstClass = false;
3977 break;
3978 }
3979
qining25262b32016-05-06 17:25:16 -04003980 if (firstClass) {
3981 spv::Id result = builder.createBinOp(op, typeId, left, right);
3982 addDecoration(result, noContraction);
3983 return builder.setPrecision(result, precision);
3984 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003985
LoopDawg592860c2016-06-09 08:57:35 -06003986 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003987 // The result type of all of them is the same type as the (a) matrix operand.
3988 // The algorithm is to:
3989 // - break the matrix(es) into vectors
3990 // - smear any scalar to a vector
3991 // - do vector operations
3992 // - make a matrix out the vector results
3993 switch (op) {
3994 case spv::OpFAdd:
3995 case spv::OpFSub:
3996 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003997 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003998 case spv::OpFMul:
3999 {
4000 // one time set up...
4001 bool leftMat = builder.isMatrix(left);
4002 bool rightMat = builder.isMatrix(right);
4003 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
4004 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
4005 spv::Id scalarType = builder.getScalarTypeId(typeId);
4006 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
4007 std::vector<spv::Id> results;
4008 spv::Id smearVec = spv::NoResult;
4009 if (builder.isScalar(left))
4010 smearVec = builder.smearScalar(precision, left, vecType);
4011 else if (builder.isScalar(right))
4012 smearVec = builder.smearScalar(precision, right, vecType);
4013
4014 // do each vector op
4015 for (unsigned int c = 0; c < numCols; ++c) {
4016 std::vector<unsigned int> indexes;
4017 indexes.push_back(c);
4018 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4019 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004020 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
4021 addDecoration(result, noContraction);
4022 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004023 }
4024
4025 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004026 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07004027 }
4028 default:
4029 assert(0);
4030 return spv::NoResult;
4031 }
4032}
4033
qining25262b32016-05-06 17:25:16 -04004034spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004035{
4036 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004037 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004038 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004039#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004040 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004041 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4042#else
Rex Xucabbb782017-03-24 13:41:14 +08004043 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08004044 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004045#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004046
4047 switch (op) {
4048 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004049 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004050 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004051 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04004052 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004053 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004054 unaryOp = spv::OpSNegate;
4055 break;
4056
4057 case glslang::EOpLogicalNot:
4058 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004059 unaryOp = spv::OpLogicalNot;
4060 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004061 case glslang::EOpBitwiseNot:
4062 unaryOp = spv::OpNot;
4063 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004064
John Kessenich140f3df2015-06-26 16:58:36 -06004065 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004066 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004067 break;
4068 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004069 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004070 break;
4071 case glslang::EOpTranspose:
4072 unaryOp = spv::OpTranspose;
4073 break;
4074
4075 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004076 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004077 break;
4078 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004079 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004080 break;
4081 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004082 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004083 break;
4084 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004085 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004086 break;
4087 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004088 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004089 break;
4090 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004091 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004092 break;
4093 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004094 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004095 break;
4096 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004097 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004098 break;
4099
4100 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004101 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004102 break;
4103 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004104 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004105 break;
4106 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004107 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004108 break;
4109 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004110 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004111 break;
4112 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004113 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004114 break;
4115 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004116 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004117 break;
4118
4119 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004120 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004121 break;
4122 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004123 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004124 break;
4125
4126 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004127 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004128 break;
4129 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004130 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004131 break;
4132 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004133 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004134 break;
4135 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004136 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004137 break;
4138 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004139 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004140 break;
4141 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004142 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004143 break;
4144
4145 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004146 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004147 break;
4148 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004149 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004150 break;
4151 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004152 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004153 break;
4154 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004155 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004156 break;
4157 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004158 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004159 break;
4160 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004161 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004162 break;
4163
4164 case glslang::EOpIsNan:
4165 unaryOp = spv::OpIsNan;
4166 break;
4167 case glslang::EOpIsInf:
4168 unaryOp = spv::OpIsInf;
4169 break;
LoopDawg592860c2016-06-09 08:57:35 -06004170 case glslang::EOpIsFinite:
4171 unaryOp = spv::OpIsFinite;
4172 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004173
Rex Xucbc426e2015-12-15 16:03:10 +08004174 case glslang::EOpFloatBitsToInt:
4175 case glslang::EOpFloatBitsToUint:
4176 case glslang::EOpIntBitsToFloat:
4177 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004178 case glslang::EOpDoubleBitsToInt64:
4179 case glslang::EOpDoubleBitsToUint64:
4180 case glslang::EOpInt64BitsToDouble:
4181 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004182#ifdef AMD_EXTENSIONS
4183 case glslang::EOpFloat16BitsToInt16:
4184 case glslang::EOpFloat16BitsToUint16:
4185 case glslang::EOpInt16BitsToFloat16:
4186 case glslang::EOpUint16BitsToFloat16:
4187#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004188 unaryOp = spv::OpBitcast;
4189 break;
4190
John Kessenich140f3df2015-06-26 16:58:36 -06004191 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004192 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004193 break;
4194 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004195 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004196 break;
4197 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004198 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004199 break;
4200 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004201 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004202 break;
4203 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004204 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004205 break;
4206 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004207 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004208 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004209 case glslang::EOpPackSnorm4x8:
4210 libCall = spv::GLSLstd450PackSnorm4x8;
4211 break;
4212 case glslang::EOpUnpackSnorm4x8:
4213 libCall = spv::GLSLstd450UnpackSnorm4x8;
4214 break;
4215 case glslang::EOpPackUnorm4x8:
4216 libCall = spv::GLSLstd450PackUnorm4x8;
4217 break;
4218 case glslang::EOpUnpackUnorm4x8:
4219 libCall = spv::GLSLstd450UnpackUnorm4x8;
4220 break;
4221 case glslang::EOpPackDouble2x32:
4222 libCall = spv::GLSLstd450PackDouble2x32;
4223 break;
4224 case glslang::EOpUnpackDouble2x32:
4225 libCall = spv::GLSLstd450UnpackDouble2x32;
4226 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004227
Rex Xu8ff43de2016-04-22 16:51:45 +08004228 case glslang::EOpPackInt2x32:
4229 case glslang::EOpUnpackInt2x32:
4230 case glslang::EOpPackUint2x32:
4231 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004232 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004233 break;
4234
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004235#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004236 case glslang::EOpPackInt2x16:
4237 case glslang::EOpUnpackInt2x16:
4238 case glslang::EOpPackUint2x16:
4239 case glslang::EOpUnpackUint2x16:
4240 case glslang::EOpPackInt4x16:
4241 case glslang::EOpUnpackInt4x16:
4242 case glslang::EOpPackUint4x16:
4243 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004244 case glslang::EOpPackFloat2x16:
4245 case glslang::EOpUnpackFloat2x16:
4246 unaryOp = spv::OpBitcast;
4247 break;
4248#endif
4249
John Kessenich140f3df2015-06-26 16:58:36 -06004250 case glslang::EOpDPdx:
4251 unaryOp = spv::OpDPdx;
4252 break;
4253 case glslang::EOpDPdy:
4254 unaryOp = spv::OpDPdy;
4255 break;
4256 case glslang::EOpFwidth:
4257 unaryOp = spv::OpFwidth;
4258 break;
4259 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004260 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004261 unaryOp = spv::OpDPdxFine;
4262 break;
4263 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004264 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004265 unaryOp = spv::OpDPdyFine;
4266 break;
4267 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004268 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004269 unaryOp = spv::OpFwidthFine;
4270 break;
4271 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004272 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004273 unaryOp = spv::OpDPdxCoarse;
4274 break;
4275 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004276 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004277 unaryOp = spv::OpDPdyCoarse;
4278 break;
4279 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004280 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004281 unaryOp = spv::OpFwidthCoarse;
4282 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004283 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004284 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004285 libCall = spv::GLSLstd450InterpolateAtCentroid;
4286 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004287 case glslang::EOpAny:
4288 unaryOp = spv::OpAny;
4289 break;
4290 case glslang::EOpAll:
4291 unaryOp = spv::OpAll;
4292 break;
4293
4294 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004295 if (isFloat)
4296 libCall = spv::GLSLstd450FAbs;
4297 else
4298 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004299 break;
4300 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004301 if (isFloat)
4302 libCall = spv::GLSLstd450FSign;
4303 else
4304 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004305 break;
4306
John Kessenichfc51d282015-08-19 13:34:18 -06004307 case glslang::EOpAtomicCounterIncrement:
4308 case glslang::EOpAtomicCounterDecrement:
4309 case glslang::EOpAtomicCounter:
4310 {
4311 // Handle all of the atomics in one place, in createAtomicOperation()
4312 std::vector<spv::Id> operands;
4313 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004314 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004315 }
4316
John Kessenichfc51d282015-08-19 13:34:18 -06004317 case glslang::EOpBitFieldReverse:
4318 unaryOp = spv::OpBitReverse;
4319 break;
4320 case glslang::EOpBitCount:
4321 unaryOp = spv::OpBitCount;
4322 break;
4323 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004324 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004325 break;
4326 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004327 if (isUnsigned)
4328 libCall = spv::GLSLstd450FindUMsb;
4329 else
4330 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004331 break;
4332
Rex Xu574ab042016-04-14 16:53:07 +08004333 case glslang::EOpBallot:
4334 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004335 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004336 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004337 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004338#ifdef AMD_EXTENSIONS
4339 case glslang::EOpMinInvocations:
4340 case glslang::EOpMaxInvocations:
4341 case glslang::EOpAddInvocations:
4342 case glslang::EOpMinInvocationsNonUniform:
4343 case glslang::EOpMaxInvocationsNonUniform:
4344 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004345 case glslang::EOpMinInvocationsInclusiveScan:
4346 case glslang::EOpMaxInvocationsInclusiveScan:
4347 case glslang::EOpAddInvocationsInclusiveScan:
4348 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4349 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4350 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4351 case glslang::EOpMinInvocationsExclusiveScan:
4352 case glslang::EOpMaxInvocationsExclusiveScan:
4353 case glslang::EOpAddInvocationsExclusiveScan:
4354 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4355 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4356 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004357#endif
Rex Xu51596642016-09-21 18:56:12 +08004358 {
4359 std::vector<spv::Id> operands;
4360 operands.push_back(operand);
4361 return createInvocationsOperation(op, typeId, operands, typeProxy);
4362 }
Rex Xu9d93a232016-05-05 12:30:44 +08004363
4364#ifdef AMD_EXTENSIONS
4365 case glslang::EOpMbcnt:
4366 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4367 libCall = spv::MbcntAMD;
4368 break;
4369
4370 case glslang::EOpCubeFaceIndex:
4371 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4372 libCall = spv::CubeFaceIndexAMD;
4373 break;
4374
4375 case glslang::EOpCubeFaceCoord:
4376 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4377 libCall = spv::CubeFaceCoordAMD;
4378 break;
4379#endif
Rex Xu338b1852016-05-05 20:38:33 +08004380
John Kessenich140f3df2015-06-26 16:58:36 -06004381 default:
4382 return 0;
4383 }
4384
4385 spv::Id id;
4386 if (libCall >= 0) {
4387 std::vector<spv::Id> args;
4388 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004389 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004390 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004391 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004392 }
John Kessenich140f3df2015-06-26 16:58:36 -06004393
qining25262b32016-05-06 17:25:16 -04004394 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004395 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004396}
4397
John Kessenich7a53f762016-01-20 11:19:27 -07004398// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004399spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07004400{
4401 // Handle unary operations vector by vector.
4402 // The result type is the same type as the original type.
4403 // The algorithm is to:
4404 // - break the matrix into vectors
4405 // - apply the operation to each vector
4406 // - make a matrix out the vector results
4407
4408 // get the types sorted out
4409 int numCols = builder.getNumColumns(operand);
4410 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004411 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4412 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004413 std::vector<spv::Id> results;
4414
4415 // do each vector op
4416 for (int c = 0; c < numCols; ++c) {
4417 std::vector<unsigned int> indexes;
4418 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004419 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4420 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4421 addDecoration(destVec, noContraction);
4422 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004423 }
4424
4425 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004426 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004427}
4428
Rex Xu73e3ce72016-04-27 18:48:17 +08004429spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destType, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004430{
4431 spv::Op convOp = spv::OpNop;
4432 spv::Id zero = 0;
4433 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004434 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004435
4436 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4437
4438 switch (op) {
4439 case glslang::EOpConvIntToBool:
4440 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004441 case glslang::EOpConvInt64ToBool:
4442 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004443#ifdef AMD_EXTENSIONS
4444 case glslang::EOpConvInt16ToBool:
4445 case glslang::EOpConvUint16ToBool:
4446#endif
4447 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4448 zero = builder.makeUint64Constant(0);
4449#ifdef AMD_EXTENSIONS
4450 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4451 zero = builder.makeUint16Constant(0);
4452#endif
4453 else
4454 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004455 zero = makeSmearedConstant(zero, vectorSize);
4456 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4457
4458 case glslang::EOpConvFloatToBool:
4459 zero = builder.makeFloatConstant(0.0F);
4460 zero = makeSmearedConstant(zero, vectorSize);
4461 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4462
4463 case glslang::EOpConvDoubleToBool:
4464 zero = builder.makeDoubleConstant(0.0);
4465 zero = makeSmearedConstant(zero, vectorSize);
4466 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4467
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004468#ifdef AMD_EXTENSIONS
4469 case glslang::EOpConvFloat16ToBool:
4470 zero = builder.makeFloat16Constant(0.0F);
4471 zero = makeSmearedConstant(zero, vectorSize);
4472 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4473#endif
4474
John Kessenich140f3df2015-06-26 16:58:36 -06004475 case glslang::EOpConvBoolToFloat:
4476 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004477 zero = builder.makeFloatConstant(0.0F);
4478 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004479 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004480
John Kessenich140f3df2015-06-26 16:58:36 -06004481 case glslang::EOpConvBoolToDouble:
4482 convOp = spv::OpSelect;
4483 zero = builder.makeDoubleConstant(0.0);
4484 one = builder.makeDoubleConstant(1.0);
4485 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004486
4487#ifdef AMD_EXTENSIONS
4488 case glslang::EOpConvBoolToFloat16:
4489 convOp = spv::OpSelect;
4490 zero = builder.makeFloat16Constant(0.0F);
4491 one = builder.makeFloat16Constant(1.0F);
4492 break;
4493#endif
4494
John Kessenich140f3df2015-06-26 16:58:36 -06004495 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004496 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004497#ifdef AMD_EXTENSIONS
4498 case glslang::EOpConvBoolToInt16:
4499#endif
4500 if (op == glslang::EOpConvBoolToInt64)
4501 zero = builder.makeInt64Constant(0);
4502#ifdef AMD_EXTENSIONS
4503 else if (op == glslang::EOpConvBoolToInt16)
4504 zero = builder.makeInt16Constant(0);
4505#endif
4506 else
4507 zero = builder.makeIntConstant(0);
4508
4509 if (op == glslang::EOpConvBoolToInt64)
4510 one = builder.makeInt64Constant(1);
4511#ifdef AMD_EXTENSIONS
4512 else if (op == glslang::EOpConvBoolToInt16)
4513 one = builder.makeInt16Constant(1);
4514#endif
4515 else
4516 one = builder.makeIntConstant(1);
4517
John Kessenich140f3df2015-06-26 16:58:36 -06004518 convOp = spv::OpSelect;
4519 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004520
John Kessenich140f3df2015-06-26 16:58:36 -06004521 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004522 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004523#ifdef AMD_EXTENSIONS
4524 case glslang::EOpConvBoolToUint16:
4525#endif
4526 if (op == glslang::EOpConvBoolToUint64)
4527 zero = builder.makeUint64Constant(0);
4528#ifdef AMD_EXTENSIONS
4529 else if (op == glslang::EOpConvBoolToUint16)
4530 zero = builder.makeUint16Constant(0);
4531#endif
4532 else
4533 zero = builder.makeUintConstant(0);
4534
4535 if (op == glslang::EOpConvBoolToUint64)
4536 one = builder.makeUint64Constant(1);
4537#ifdef AMD_EXTENSIONS
4538 else if (op == glslang::EOpConvBoolToUint16)
4539 one = builder.makeUint16Constant(1);
4540#endif
4541 else
4542 one = builder.makeUintConstant(1);
4543
John Kessenich140f3df2015-06-26 16:58:36 -06004544 convOp = spv::OpSelect;
4545 break;
4546
4547 case glslang::EOpConvIntToFloat:
4548 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004549 case glslang::EOpConvInt64ToFloat:
4550 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004551#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004552 case glslang::EOpConvInt16ToFloat:
4553 case glslang::EOpConvInt16ToDouble:
4554 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004555 case glslang::EOpConvIntToFloat16:
4556 case glslang::EOpConvInt64ToFloat16:
4557#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004558 convOp = spv::OpConvertSToF;
4559 break;
4560
4561 case glslang::EOpConvUintToFloat:
4562 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004563 case glslang::EOpConvUint64ToFloat:
4564 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004565#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004566 case glslang::EOpConvUint16ToFloat:
4567 case glslang::EOpConvUint16ToDouble:
4568 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004569 case glslang::EOpConvUintToFloat16:
4570 case glslang::EOpConvUint64ToFloat16:
4571#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004572 convOp = spv::OpConvertUToF;
4573 break;
4574
4575 case glslang::EOpConvDoubleToFloat:
4576 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004577#ifdef AMD_EXTENSIONS
4578 case glslang::EOpConvDoubleToFloat16:
4579 case glslang::EOpConvFloat16ToDouble:
4580 case glslang::EOpConvFloatToFloat16:
4581 case glslang::EOpConvFloat16ToFloat:
4582#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004583 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004584 if (builder.isMatrixType(destType))
4585 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004586 break;
4587
4588 case glslang::EOpConvFloatToInt:
4589 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004590 case glslang::EOpConvFloatToInt64:
4591 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004592#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004593 case glslang::EOpConvFloatToInt16:
4594 case glslang::EOpConvDoubleToInt16:
4595 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004596 case glslang::EOpConvFloat16ToInt:
4597 case glslang::EOpConvFloat16ToInt64:
4598#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004599 convOp = spv::OpConvertFToS;
4600 break;
4601
4602 case glslang::EOpConvUintToInt:
4603 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004604 case glslang::EOpConvUint64ToInt64:
4605 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004606#ifdef AMD_EXTENSIONS
4607 case glslang::EOpConvUint16ToInt16:
4608 case glslang::EOpConvInt16ToUint16:
4609#endif
qininge24aa5e2016-04-07 15:40:27 -04004610 if (builder.isInSpecConstCodeGenMode()) {
4611 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004612 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4613 zero = builder.makeUint64Constant(0);
4614#ifdef AMD_EXTENSIONS
4615 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4616 zero = builder.makeUint16Constant(0);
4617#endif
4618 else
4619 zero = builder.makeUintConstant(0);
4620
qining189b2032016-04-12 23:16:20 -04004621 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004622 // Use OpIAdd, instead of OpBitcast to do the conversion when
4623 // generating for OpSpecConstantOp instruction.
4624 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4625 }
4626 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004627 convOp = spv::OpBitcast;
4628 break;
4629
4630 case glslang::EOpConvFloatToUint:
4631 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004632 case glslang::EOpConvFloatToUint64:
4633 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004634#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004635 case glslang::EOpConvFloatToUint16:
4636 case glslang::EOpConvDoubleToUint16:
4637 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004638 case glslang::EOpConvFloat16ToUint:
4639 case glslang::EOpConvFloat16ToUint64:
4640#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004641 convOp = spv::OpConvertFToU;
4642 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004643
4644 case glslang::EOpConvIntToInt64:
4645 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004646#ifdef AMD_EXTENSIONS
4647 case glslang::EOpConvIntToInt16:
4648 case glslang::EOpConvInt16ToInt:
4649 case glslang::EOpConvInt64ToInt16:
4650 case glslang::EOpConvInt16ToInt64:
4651#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004652 convOp = spv::OpSConvert;
4653 break;
4654
4655 case glslang::EOpConvUintToUint64:
4656 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004657#ifdef AMD_EXTENSIONS
4658 case glslang::EOpConvUintToUint16:
4659 case glslang::EOpConvUint16ToUint:
4660 case glslang::EOpConvUint64ToUint16:
4661 case glslang::EOpConvUint16ToUint64:
4662#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004663 convOp = spv::OpUConvert;
4664 break;
4665
4666 case glslang::EOpConvIntToUint64:
4667 case glslang::EOpConvInt64ToUint:
4668 case glslang::EOpConvUint64ToInt:
4669 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004670#ifdef AMD_EXTENSIONS
4671 case glslang::EOpConvInt16ToUint:
4672 case glslang::EOpConvUintToInt16:
4673 case glslang::EOpConvInt16ToUint64:
4674 case glslang::EOpConvUint64ToInt16:
4675 case glslang::EOpConvUint16ToInt:
4676 case glslang::EOpConvIntToUint16:
4677 case glslang::EOpConvUint16ToInt64:
4678 case glslang::EOpConvInt64ToUint16:
4679#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004680 // OpSConvert/OpUConvert + OpBitCast
4681 switch (op) {
4682 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004683#ifdef AMD_EXTENSIONS
4684 case glslang::EOpConvInt16ToUint64:
4685#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004686 convOp = spv::OpSConvert;
4687 type = builder.makeIntType(64);
4688 break;
4689 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004690#ifdef AMD_EXTENSIONS
4691 case glslang::EOpConvInt16ToUint:
4692#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004693 convOp = spv::OpSConvert;
4694 type = builder.makeIntType(32);
4695 break;
4696 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004697#ifdef AMD_EXTENSIONS
4698 case glslang::EOpConvUint16ToInt:
4699#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004700 convOp = spv::OpUConvert;
4701 type = builder.makeUintType(32);
4702 break;
4703 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004704#ifdef AMD_EXTENSIONS
4705 case glslang::EOpConvUint16ToInt64:
4706#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004707 convOp = spv::OpUConvert;
4708 type = builder.makeUintType(64);
4709 break;
Rex Xucabbb782017-03-24 13:41:14 +08004710#ifdef AMD_EXTENSIONS
4711 case glslang::EOpConvUintToInt16:
4712 case glslang::EOpConvUint64ToInt16:
4713 convOp = spv::OpUConvert;
4714 type = builder.makeUintType(16);
4715 break;
4716 case glslang::EOpConvIntToUint16:
4717 case glslang::EOpConvInt64ToUint16:
4718 convOp = spv::OpSConvert;
4719 type = builder.makeIntType(16);
4720 break;
4721#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004722 default:
4723 assert(0);
4724 break;
4725 }
4726
4727 if (vectorSize > 0)
4728 type = builder.makeVectorType(type, vectorSize);
4729
4730 operand = builder.createUnaryOp(convOp, type, operand);
4731
4732 if (builder.isInSpecConstCodeGenMode()) {
4733 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004734#ifdef AMD_EXTENSIONS
4735 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4736 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4737 zero = builder.makeUint64Constant(0);
4738 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4739 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4740 zero = builder.makeUint16Constant(0);
4741 else
4742 zero = builder.makeUintConstant(0);
4743#else
4744 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4745 zero = builder.makeUint64Constant(0);
4746 else
4747 zero = builder.makeUintConstant(0);
4748#endif
4749
Rex Xu8ff43de2016-04-22 16:51:45 +08004750 zero = makeSmearedConstant(zero, vectorSize);
4751 // Use OpIAdd, instead of OpBitcast to do the conversion when
4752 // generating for OpSpecConstantOp instruction.
4753 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4754 }
4755 // For normal run-time conversion instruction, use OpBitcast.
4756 convOp = spv::OpBitcast;
4757 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004758 default:
4759 break;
4760 }
4761
4762 spv::Id result = 0;
4763 if (convOp == spv::OpNop)
4764 return result;
4765
4766 if (convOp == spv::OpSelect) {
4767 zero = makeSmearedConstant(zero, vectorSize);
4768 one = makeSmearedConstant(one, vectorSize);
4769 result = builder.createTriOp(convOp, destType, operand, one, zero);
4770 } else
4771 result = builder.createUnaryOp(convOp, destType, operand);
4772
John Kessenich32cfd492016-02-02 12:37:46 -07004773 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004774}
4775
4776spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4777{
4778 if (vectorSize == 0)
4779 return constant;
4780
4781 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4782 std::vector<spv::Id> components;
4783 for (int c = 0; c < vectorSize; ++c)
4784 components.push_back(constant);
4785 return builder.makeCompositeConstant(vectorTypeId, components);
4786}
4787
John Kessenich426394d2015-07-23 10:22:48 -06004788// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004789spv::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 -06004790{
4791 spv::Op opCode = spv::OpNop;
4792
4793 switch (op) {
4794 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004795 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004796 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004797 opCode = spv::OpAtomicIAdd;
4798 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004799 case glslang::EOpAtomicCounterSubtract:
4800 opCode = spv::OpAtomicISub;
4801 break;
John Kessenich426394d2015-07-23 10:22:48 -06004802 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004803 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004804 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08004805 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004806 break;
4807 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004808 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004809 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08004810 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004811 break;
4812 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004813 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004814 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004815 opCode = spv::OpAtomicAnd;
4816 break;
4817 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004818 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004819 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004820 opCode = spv::OpAtomicOr;
4821 break;
4822 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004823 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004824 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004825 opCode = spv::OpAtomicXor;
4826 break;
4827 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004828 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004829 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004830 opCode = spv::OpAtomicExchange;
4831 break;
4832 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004833 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004834 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004835 opCode = spv::OpAtomicCompareExchange;
4836 break;
4837 case glslang::EOpAtomicCounterIncrement:
4838 opCode = spv::OpAtomicIIncrement;
4839 break;
4840 case glslang::EOpAtomicCounterDecrement:
4841 opCode = spv::OpAtomicIDecrement;
4842 break;
4843 case glslang::EOpAtomicCounter:
4844 opCode = spv::OpAtomicLoad;
4845 break;
4846 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004847 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004848 break;
4849 }
4850
Rex Xue8fe8b02017-09-26 15:42:56 +08004851 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
4852 builder.addCapability(spv::CapabilityInt64Atomics);
4853
John Kessenich426394d2015-07-23 10:22:48 -06004854 // Sort out the operands
4855 // - mapping from glslang -> SPV
4856 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004857 // - compare-exchange swaps the value and comparator
4858 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06004859 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06004860 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4861 auto opIt = operands.begin(); // walk the glslang operands
4862 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004863 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4864 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4865 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004866 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4867 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004868 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004869 spvAtomicOperands.push_back(*(opIt + 1));
4870 spvAtomicOperands.push_back(*opIt);
4871 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004872 }
John Kessenich426394d2015-07-23 10:22:48 -06004873
John Kessenich3e60a6f2015-09-14 22:45:16 -06004874 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004875 for (; opIt != operands.end(); ++opIt)
4876 spvAtomicOperands.push_back(*opIt);
4877
John Kessenich48d6e792017-10-06 21:21:48 -06004878 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
4879
4880 // GLSL and HLSL atomic-counter decrement return post-decrement value,
4881 // while SPIR-V returns pre-decrement value. Translate between these semantics.
4882 if (op == glslang::EOpAtomicCounterDecrement)
4883 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
4884
4885 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06004886}
4887
John Kessenich91cef522016-05-05 16:45:40 -06004888// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004889spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004890{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004891#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004892 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004893 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004894#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004895
Rex Xu51596642016-09-21 18:56:12 +08004896 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004897 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004898 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4899
chaocf200da82016-12-20 12:44:35 -08004900 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4901 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004902 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4903 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004904 } else if (op == glslang::EOpAnyInvocation ||
4905 op == glslang::EOpAllInvocations ||
4906 op == glslang::EOpAllInvocationsEqual) {
4907 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4908 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004909 } else {
4910 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004911#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004912 if (op == glslang::EOpMinInvocationsNonUniform ||
4913 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004914 op == glslang::EOpAddInvocationsNonUniform ||
4915 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4916 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4917 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4918 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4919 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4920 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004921 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004922#endif
Rex Xu51596642016-09-21 18:56:12 +08004923
4924 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004925#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004926 switch (op) {
4927 case glslang::EOpMinInvocations:
4928 case glslang::EOpMaxInvocations:
4929 case glslang::EOpAddInvocations:
4930 case glslang::EOpMinInvocationsNonUniform:
4931 case glslang::EOpMaxInvocationsNonUniform:
4932 case glslang::EOpAddInvocationsNonUniform:
4933 groupOperation = spv::GroupOperationReduce;
4934 spvGroupOperands.push_back(groupOperation);
4935 break;
4936 case glslang::EOpMinInvocationsInclusiveScan:
4937 case glslang::EOpMaxInvocationsInclusiveScan:
4938 case glslang::EOpAddInvocationsInclusiveScan:
4939 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4940 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4941 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4942 groupOperation = spv::GroupOperationInclusiveScan;
4943 spvGroupOperands.push_back(groupOperation);
4944 break;
4945 case glslang::EOpMinInvocationsExclusiveScan:
4946 case glslang::EOpMaxInvocationsExclusiveScan:
4947 case glslang::EOpAddInvocationsExclusiveScan:
4948 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4949 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4950 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4951 groupOperation = spv::GroupOperationExclusiveScan;
4952 spvGroupOperands.push_back(groupOperation);
4953 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004954 default:
4955 break;
Rex Xu430ef402016-10-14 17:22:23 +08004956 }
Rex Xu9d93a232016-05-05 12:30:44 +08004957#endif
Rex Xu51596642016-09-21 18:56:12 +08004958 }
4959
4960 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4961 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004962
4963 switch (op) {
4964 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004965 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004966 break;
John Kessenich91cef522016-05-05 16:45:40 -06004967 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004968 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004969 break;
John Kessenich91cef522016-05-05 16:45:40 -06004970 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004971 opCode = spv::OpSubgroupAllEqualKHR;
4972 break;
Rex Xu51596642016-09-21 18:56:12 +08004973 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004974 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004975 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004976 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004977 break;
4978 case glslang::EOpReadFirstInvocation:
4979 opCode = spv::OpSubgroupFirstInvocationKHR;
4980 break;
4981 case glslang::EOpBallot:
4982 {
4983 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4984 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4985 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4986 //
4987 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4988 //
4989 spv::Id uintType = builder.makeUintType(32);
4990 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4991 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4992
4993 std::vector<spv::Id> components;
4994 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4995 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4996
4997 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4998 return builder.createUnaryOp(spv::OpBitcast, typeId,
4999 builder.createCompositeConstruct(uvec2Type, components));
5000 }
5001
Rex Xu9d93a232016-05-05 12:30:44 +08005002#ifdef AMD_EXTENSIONS
5003 case glslang::EOpMinInvocations:
5004 case glslang::EOpMaxInvocations:
5005 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08005006 case glslang::EOpMinInvocationsInclusiveScan:
5007 case glslang::EOpMaxInvocationsInclusiveScan:
5008 case glslang::EOpAddInvocationsInclusiveScan:
5009 case glslang::EOpMinInvocationsExclusiveScan:
5010 case glslang::EOpMaxInvocationsExclusiveScan:
5011 case glslang::EOpAddInvocationsExclusiveScan:
5012 if (op == glslang::EOpMinInvocations ||
5013 op == glslang::EOpMinInvocationsInclusiveScan ||
5014 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005015 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005016 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005017 else {
5018 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005019 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005020 else
Rex Xu51596642016-09-21 18:56:12 +08005021 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005022 }
Rex Xu430ef402016-10-14 17:22:23 +08005023 } else if (op == glslang::EOpMaxInvocations ||
5024 op == glslang::EOpMaxInvocationsInclusiveScan ||
5025 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005026 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005027 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005028 else {
5029 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005030 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005031 else
Rex Xu51596642016-09-21 18:56:12 +08005032 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005033 }
5034 } else {
5035 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005036 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005037 else
Rex Xu51596642016-09-21 18:56:12 +08005038 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005039 }
5040
Rex Xu2bbbe062016-08-23 15:41:05 +08005041 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005042 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005043
5044 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005045 case glslang::EOpMinInvocationsNonUniform:
5046 case glslang::EOpMaxInvocationsNonUniform:
5047 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005048 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5049 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5050 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5051 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5052 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5053 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5054 if (op == glslang::EOpMinInvocationsNonUniform ||
5055 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5056 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005057 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005058 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005059 else {
5060 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005061 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005062 else
Rex Xu51596642016-09-21 18:56:12 +08005063 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005064 }
5065 }
Rex Xu430ef402016-10-14 17:22:23 +08005066 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5067 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5068 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005069 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005070 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005071 else {
5072 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005073 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005074 else
Rex Xu51596642016-09-21 18:56:12 +08005075 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005076 }
5077 }
5078 else {
5079 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005080 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005081 else
Rex Xu51596642016-09-21 18:56:12 +08005082 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005083 }
5084
Rex Xu2bbbe062016-08-23 15:41:05 +08005085 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005086 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005087
5088 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005089#endif
John Kessenich91cef522016-05-05 16:45:40 -06005090 default:
5091 logger->missingFunctionality("invocation operation");
5092 return spv::NoResult;
5093 }
Rex Xu51596642016-09-21 18:56:12 +08005094
5095 assert(opCode != spv::OpNop);
5096 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005097}
5098
Rex Xu2bbbe062016-08-23 15:41:05 +08005099// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005100spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005101{
Rex Xub7072052016-09-26 15:53:40 +08005102#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005103 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5104 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005105 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005106 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005107 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5108 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5109 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005110#else
5111 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5112 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005113 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5114 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005115#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005116
5117 // Handle group invocation operations scalar by scalar.
5118 // The result type is the same type as the original type.
5119 // The algorithm is to:
5120 // - break the vector into scalars
5121 // - apply the operation to each scalar
5122 // - make a vector out the scalar results
5123
5124 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005125 int numComponents = builder.getNumComponents(operands[0]);
5126 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005127 std::vector<spv::Id> results;
5128
5129 // do each scalar op
5130 for (int comp = 0; comp < numComponents; ++comp) {
5131 std::vector<unsigned int> indexes;
5132 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005133 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005134 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005135 if (op == spv::OpSubgroupReadInvocationKHR) {
5136 spvGroupOperands.push_back(scalar);
5137 spvGroupOperands.push_back(operands[1]);
5138 } else if (op == spv::OpGroupBroadcast) {
5139 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005140 spvGroupOperands.push_back(scalar);
5141 spvGroupOperands.push_back(operands[1]);
5142 } else {
chaocf200da82016-12-20 12:44:35 -08005143 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005144 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005145 spvGroupOperands.push_back(scalar);
5146 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005147
Rex Xub7072052016-09-26 15:53:40 +08005148 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005149 }
5150
5151 // put the pieces together
5152 return builder.createCompositeConstruct(typeId, results);
5153}
Rex Xu2bbbe062016-08-23 15:41:05 +08005154
John Kessenich5e4b1242015-08-06 22:53:06 -06005155spv::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 -06005156{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005157#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005158 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005159 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5160#else
Rex Xucabbb782017-03-24 13:41:14 +08005161 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005162 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005163#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005164
John Kessenich140f3df2015-06-26 16:58:36 -06005165 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005166 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005167 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005168 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005169 spv::Id typeId0 = 0;
5170 if (consumedOperands > 0)
5171 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005172 spv::Id typeId1 = 0;
5173 if (consumedOperands > 1)
5174 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005175 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005176
5177 switch (op) {
5178 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005179 if (isFloat)
5180 libCall = spv::GLSLstd450FMin;
5181 else if (isUnsigned)
5182 libCall = spv::GLSLstd450UMin;
5183 else
5184 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005185 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005186 break;
5187 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005188 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005189 break;
5190 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005191 if (isFloat)
5192 libCall = spv::GLSLstd450FMax;
5193 else if (isUnsigned)
5194 libCall = spv::GLSLstd450UMax;
5195 else
5196 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005197 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005198 break;
5199 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005200 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005201 break;
5202 case glslang::EOpDot:
5203 opCode = spv::OpDot;
5204 break;
5205 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005206 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005207 break;
5208
5209 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005210 if (isFloat)
5211 libCall = spv::GLSLstd450FClamp;
5212 else if (isUnsigned)
5213 libCall = spv::GLSLstd450UClamp;
5214 else
5215 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005216 builder.promoteScalar(precision, operands.front(), operands[1]);
5217 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005218 break;
5219 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005220 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5221 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005222 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005223 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005224 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005225 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005226 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005227 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005228 break;
5229 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005230 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005231 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005232 break;
5233 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005234 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005235 builder.promoteScalar(precision, operands[0], operands[2]);
5236 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005237 break;
5238
5239 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005240 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005241 break;
5242 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005243 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005244 break;
5245 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005246 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005247 break;
5248 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005249 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005250 break;
5251 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005252 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005253 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005254 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005255 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005256 libCall = spv::GLSLstd450InterpolateAtSample;
5257 break;
5258 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005259 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005260 libCall = spv::GLSLstd450InterpolateAtOffset;
5261 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005262 case glslang::EOpAddCarry:
5263 opCode = spv::OpIAddCarry;
5264 typeId = builder.makeStructResultType(typeId0, typeId0);
5265 consumedOperands = 2;
5266 break;
5267 case glslang::EOpSubBorrow:
5268 opCode = spv::OpISubBorrow;
5269 typeId = builder.makeStructResultType(typeId0, typeId0);
5270 consumedOperands = 2;
5271 break;
5272 case glslang::EOpUMulExtended:
5273 opCode = spv::OpUMulExtended;
5274 typeId = builder.makeStructResultType(typeId0, typeId0);
5275 consumedOperands = 2;
5276 break;
5277 case glslang::EOpIMulExtended:
5278 opCode = spv::OpSMulExtended;
5279 typeId = builder.makeStructResultType(typeId0, typeId0);
5280 consumedOperands = 2;
5281 break;
5282 case glslang::EOpBitfieldExtract:
5283 if (isUnsigned)
5284 opCode = spv::OpBitFieldUExtract;
5285 else
5286 opCode = spv::OpBitFieldSExtract;
5287 break;
5288 case glslang::EOpBitfieldInsert:
5289 opCode = spv::OpBitFieldInsert;
5290 break;
5291
5292 case glslang::EOpFma:
5293 libCall = spv::GLSLstd450Fma;
5294 break;
5295 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005296 {
5297 libCall = spv::GLSLstd450FrexpStruct;
5298 assert(builder.isPointerType(typeId1));
5299 typeId1 = builder.getContainedTypeId(typeId1);
5300#ifdef AMD_EXTENSIONS
5301 int width = builder.getScalarTypeWidth(typeId1);
5302#else
5303 int width = 32;
5304#endif
5305 if (builder.getNumComponents(operands[0]) == 1)
5306 frexpIntType = builder.makeIntegerType(width, true);
5307 else
5308 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5309 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5310 consumedOperands = 1;
5311 }
John Kessenich55e7d112015-11-15 21:33:39 -07005312 break;
5313 case glslang::EOpLdexp:
5314 libCall = spv::GLSLstd450Ldexp;
5315 break;
5316
Rex Xu574ab042016-04-14 16:53:07 +08005317 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005318 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005319
Rex Xu9d93a232016-05-05 12:30:44 +08005320#ifdef AMD_EXTENSIONS
5321 case glslang::EOpSwizzleInvocations:
5322 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5323 libCall = spv::SwizzleInvocationsAMD;
5324 break;
5325 case glslang::EOpSwizzleInvocationsMasked:
5326 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5327 libCall = spv::SwizzleInvocationsMaskedAMD;
5328 break;
5329 case glslang::EOpWriteInvocation:
5330 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5331 libCall = spv::WriteInvocationAMD;
5332 break;
5333
5334 case glslang::EOpMin3:
5335 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5336 if (isFloat)
5337 libCall = spv::FMin3AMD;
5338 else {
5339 if (isUnsigned)
5340 libCall = spv::UMin3AMD;
5341 else
5342 libCall = spv::SMin3AMD;
5343 }
5344 break;
5345 case glslang::EOpMax3:
5346 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5347 if (isFloat)
5348 libCall = spv::FMax3AMD;
5349 else {
5350 if (isUnsigned)
5351 libCall = spv::UMax3AMD;
5352 else
5353 libCall = spv::SMax3AMD;
5354 }
5355 break;
5356 case glslang::EOpMid3:
5357 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5358 if (isFloat)
5359 libCall = spv::FMid3AMD;
5360 else {
5361 if (isUnsigned)
5362 libCall = spv::UMid3AMD;
5363 else
5364 libCall = spv::SMid3AMD;
5365 }
5366 break;
5367
5368 case glslang::EOpInterpolateAtVertex:
5369 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5370 libCall = spv::InterpolateAtVertexAMD;
5371 break;
5372#endif
5373
John Kessenich140f3df2015-06-26 16:58:36 -06005374 default:
5375 return 0;
5376 }
5377
5378 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005379 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005380 // Use an extended instruction from the standard library.
5381 // Construct the call arguments, without modifying the original operands vector.
5382 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5383 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005384 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005385 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005386 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005387 case 0:
5388 // should all be handled by visitAggregate and createNoArgOperation
5389 assert(0);
5390 return 0;
5391 case 1:
5392 // should all be handled by createUnaryOperation
5393 assert(0);
5394 return 0;
5395 case 2:
5396 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5397 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005398 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005399 // anything 3 or over doesn't have l-value operands, so all should be consumed
5400 assert(consumedOperands == operands.size());
5401 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005402 break;
5403 }
5404 }
5405
John Kessenich55e7d112015-11-15 21:33:39 -07005406 // Decode the return types that were structures
5407 switch (op) {
5408 case glslang::EOpAddCarry:
5409 case glslang::EOpSubBorrow:
5410 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5411 id = builder.createCompositeExtract(id, typeId0, 0);
5412 break;
5413 case glslang::EOpUMulExtended:
5414 case glslang::EOpIMulExtended:
5415 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5416 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5417 break;
5418 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005419 {
5420 assert(operands.size() == 2);
5421 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5422 // "exp" is floating-point type (from HLSL intrinsic)
5423 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5424 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5425 builder.createStore(member1, operands[1]);
5426 } else
5427 // "exp" is integer type (from GLSL built-in function)
5428 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5429 id = builder.createCompositeExtract(id, typeId0, 0);
5430 }
John Kessenich55e7d112015-11-15 21:33:39 -07005431 break;
5432 default:
5433 break;
5434 }
5435
John Kessenich32cfd492016-02-02 12:37:46 -07005436 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005437}
5438
Rex Xu9d93a232016-05-05 12:30:44 +08005439// Intrinsics with no arguments (or no return value, and no precision).
5440spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005441{
5442 // TODO: get the barrier operands correct
5443
5444 switch (op) {
5445 case glslang::EOpEmitVertex:
5446 builder.createNoResultOp(spv::OpEmitVertex);
5447 return 0;
5448 case glslang::EOpEndPrimitive:
5449 builder.createNoResultOp(spv::OpEndPrimitive);
5450 return 0;
5451 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005452 if (glslangIntermediate->getStage() == EShLangTessControl) {
5453 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
5454 // TODO: prefer the following, when available:
5455 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
5456 // spv::MemorySemanticsPatchMask |
5457 // spv::MemorySemanticsAcquireReleaseMask);
5458 } else {
5459 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
5460 spv::MemorySemanticsWorkgroupMemoryMask |
5461 spv::MemorySemanticsAcquireReleaseMask);
5462 }
John Kessenich140f3df2015-06-26 16:58:36 -06005463 return 0;
5464 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005465 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
5466 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005467 return 0;
5468 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07005469 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
5470 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005471 return 0;
5472 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07005473 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5474 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005475 return 0;
5476 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07005477 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
5478 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005479 return 0;
5480 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07005481 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
5482 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005483 return 0;
5484 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005485 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
5486 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005487 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005488 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07005489 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07005490 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07005491 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005492 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07005493 case glslang::EOpDeviceMemoryBarrier:
5494 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5495 spv::MemorySemanticsImageMemoryMask |
5496 spv::MemorySemanticsAcquireReleaseMask);
5497 return 0;
5498 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
5499 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5500 spv::MemorySemanticsImageMemoryMask |
5501 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005502 return 0;
5503 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07005504 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
5505 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005506 return 0;
5507 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07005508 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
5509 spv::MemorySemanticsWorkgroupMemoryMask |
5510 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005511 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005512#ifdef AMD_EXTENSIONS
5513 case glslang::EOpTime:
5514 {
5515 std::vector<spv::Id> args; // Dummy arguments
5516 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5517 return builder.setPrecision(id, precision);
5518 }
5519#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005520 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005521 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005522 return 0;
5523 }
5524}
5525
5526spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5527{
John Kessenich2f273362015-07-18 22:34:27 -06005528 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005529 spv::Id id;
5530 if (symbolValues.end() != iter) {
5531 id = iter->second;
5532 return id;
5533 }
5534
5535 // it was not found, create it
5536 id = createSpvVariable(symbol);
5537 symbolValues[symbol->getId()] = id;
5538
Rex Xuc884b4a2016-06-29 15:03:44 +08005539 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005540 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005541 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005542 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005543 if (symbol->getType().getQualifier().hasSpecConstantId())
5544 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005545 if (symbol->getQualifier().hasIndex())
5546 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5547 if (symbol->getQualifier().hasComponent())
5548 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06005549 // atomic counters use this:
5550 if (symbol->getQualifier().hasOffset())
5551 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005552 }
5553
scygan2c864272016-05-18 18:09:17 +02005554 if (symbol->getQualifier().hasLocation())
5555 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005556 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005557 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005558 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005559 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005560 }
John Kessenich140f3df2015-06-26 16:58:36 -06005561 if (symbol->getQualifier().hasSet())
5562 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005563 else if (IsDescriptorResource(symbol->getType())) {
5564 // default to 0
5565 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5566 }
John Kessenich140f3df2015-06-26 16:58:36 -06005567 if (symbol->getQualifier().hasBinding())
5568 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005569 if (symbol->getQualifier().hasAttachment())
5570 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005571 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005572 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005573 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005574 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07005575 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06005576 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07005577 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
5578 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
5579 builder.addDecoration(id, spv::DecorationXfbStride, stride);
5580 }
5581 if (symbol->getQualifier().hasXfbOffset())
5582 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005583 }
5584
Rex Xu1da878f2016-02-21 20:59:01 +08005585 if (symbol->getType().isImage()) {
5586 std::vector<spv::Decoration> memory;
5587 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5588 for (unsigned int i = 0; i < memory.size(); ++i)
5589 addDecoration(id, memory[i]);
5590 }
5591
John Kessenich140f3df2015-06-26 16:58:36 -06005592 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005593 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005594 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005595 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005596
John Kessenichecba76f2017-01-06 00:34:48 -07005597#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005598 if (builtIn == spv::BuiltInSampleMask) {
5599 spv::Decoration decoration;
5600 // GL_NV_sample_mask_override_coverage extension
5601 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005602 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005603 else
5604 decoration = (spv::Decoration)spv::DecorationMax;
5605 addDecoration(id, decoration);
5606 if (decoration != spv::DecorationMax) {
5607 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5608 }
5609 }
chaoc771d89f2017-01-13 01:10:53 -08005610 else if (builtIn == spv::BuiltInLayer) {
5611 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06005612 if (symbol->getQualifier().layoutViewportRelative) {
chaoc771d89f2017-01-13 01:10:53 -08005613 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5614 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5615 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5616 }
John Kessenichb41bff62017-08-11 13:07:17 -06005617 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
chaoc771d89f2017-01-13 01:10:53 -08005618 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5619 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5620 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5621 }
5622 }
5623
chaoc6e5acae2016-12-20 13:28:52 -08005624 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005625 addDecoration(id, spv::DecorationPassthroughNV);
5626 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005627 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5628 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005629#endif
5630
John Kessenich140f3df2015-06-26 16:58:36 -06005631 return id;
5632}
5633
John Kessenich55e7d112015-11-15 21:33:39 -07005634// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005635void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5636{
John Kessenich4016e382016-07-15 11:53:56 -06005637 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005638 builder.addDecoration(id, dec);
5639}
5640
John Kessenich55e7d112015-11-15 21:33:39 -07005641// If 'dec' is valid, add a one-operand decoration to an object
5642void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5643{
John Kessenich4016e382016-07-15 11:53:56 -06005644 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005645 builder.addDecoration(id, dec, value);
5646}
5647
5648// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005649void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5650{
John Kessenich4016e382016-07-15 11:53:56 -06005651 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005652 builder.addMemberDecoration(id, (unsigned)member, dec);
5653}
5654
John Kessenich92187592016-02-01 13:45:25 -07005655// If 'dec' is valid, add a one-operand decoration to a struct member
5656void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5657{
John Kessenich4016e382016-07-15 11:53:56 -06005658 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005659 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5660}
5661
John Kessenich55e7d112015-11-15 21:33:39 -07005662// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005663// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005664//
5665// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5666//
5667// Recursively walk the nodes. The nodes form a tree whose leaves are
5668// regular constants, which themselves are trees that createSpvConstant()
5669// recursively walks. So, this function walks the "top" of the tree:
5670// - emit specialization constant-building instructions for specConstant
5671// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005672spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005673{
John Kessenich7cc0e282016-03-20 00:46:02 -06005674 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005675
qining4f4bb812016-04-03 23:55:17 -04005676 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005677 if (! node.getQualifier().specConstant) {
5678 // hand off to the non-spec-constant path
5679 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5680 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005681 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005682 nextConst, false);
5683 }
5684
5685 // We now know we have a specialization constant to build
5686
John Kessenichd94c0032016-05-30 19:29:40 -06005687 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005688 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5689 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5690 std::vector<spv::Id> dimConstId;
5691 for (int dim = 0; dim < 3; ++dim) {
5692 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5693 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5694 if (specConst)
5695 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5696 }
5697 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5698 }
5699
5700 // An AST node labelled as specialization constant should be a symbol node.
5701 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5702 if (auto* sn = node.getAsSymbolNode()) {
5703 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005704 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5705 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5706 // will set the builder into spec constant op instruction generating mode.
5707 sub_tree->traverse(this);
5708 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005709 } else if (auto* const_union_array = &sn->getConstArray()){
5710 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005711 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5712 builder.addName(id, sn->getName().c_str());
5713 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005714 }
5715 }
qining4f4bb812016-04-03 23:55:17 -04005716
5717 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5718 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005719 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005720 exit(1);
5721 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005722}
5723
John Kessenich140f3df2015-06-26 16:58:36 -06005724// Use 'consts' as the flattened glslang source of scalar constants to recursively
5725// build the aggregate SPIR-V constant.
5726//
5727// If there are not enough elements present in 'consts', 0 will be substituted;
5728// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5729//
qining08408382016-03-21 09:51:37 -04005730spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005731{
5732 // vector of constants for SPIR-V
5733 std::vector<spv::Id> spvConsts;
5734
5735 // Type is used for struct and array constants
5736 spv::Id typeId = convertGlslangToSpvType(glslangType);
5737
5738 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005739 glslang::TType elementType(glslangType, 0);
5740 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005741 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005742 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005743 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005744 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005745 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005746 } else if (glslangType.getStruct()) {
5747 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5748 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005749 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005750 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005751 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5752 bool zero = nextConst >= consts.size();
5753 switch (glslangType.getBasicType()) {
5754 case glslang::EbtInt:
5755 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5756 break;
5757 case glslang::EbtUint:
5758 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5759 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005760 case glslang::EbtInt64:
5761 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5762 break;
5763 case glslang::EbtUint64:
5764 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5765 break;
Rex Xucabbb782017-03-24 13:41:14 +08005766#ifdef AMD_EXTENSIONS
5767 case glslang::EbtInt16:
5768 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5769 break;
5770 case glslang::EbtUint16:
5771 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5772 break;
5773#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005774 case glslang::EbtFloat:
5775 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5776 break;
5777 case glslang::EbtDouble:
5778 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5779 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005780#ifdef AMD_EXTENSIONS
5781 case glslang::EbtFloat16:
5782 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5783 break;
5784#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005785 case glslang::EbtBool:
5786 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5787 break;
5788 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005789 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005790 break;
5791 }
5792 ++nextConst;
5793 }
5794 } else {
5795 // we have a non-aggregate (scalar) constant
5796 bool zero = nextConst >= consts.size();
5797 spv::Id scalar = 0;
5798 switch (glslangType.getBasicType()) {
5799 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005800 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005801 break;
5802 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005803 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005804 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005805 case glslang::EbtInt64:
5806 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5807 break;
5808 case glslang::EbtUint64:
5809 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5810 break;
Rex Xucabbb782017-03-24 13:41:14 +08005811#ifdef AMD_EXTENSIONS
5812 case glslang::EbtInt16:
5813 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5814 break;
5815 case glslang::EbtUint16:
5816 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5817 break;
5818#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005819 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005820 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005821 break;
5822 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005823 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005824 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005825#ifdef AMD_EXTENSIONS
5826 case glslang::EbtFloat16:
5827 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5828 break;
5829#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005830 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005831 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005832 break;
5833 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005834 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005835 break;
5836 }
5837 ++nextConst;
5838 return scalar;
5839 }
5840
5841 return builder.makeCompositeConstant(typeId, spvConsts);
5842}
5843
John Kessenich7c1aa102015-10-15 13:29:11 -06005844// Return true if the node is a constant or symbol whose reading has no
5845// non-trivial observable cost or effect.
5846bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5847{
5848 // don't know what this is
5849 if (node == nullptr)
5850 return false;
5851
5852 // a constant is safe
5853 if (node->getAsConstantUnion() != nullptr)
5854 return true;
5855
5856 // not a symbol means non-trivial
5857 if (node->getAsSymbolNode() == nullptr)
5858 return false;
5859
5860 // a symbol, depends on what's being read
5861 switch (node->getType().getQualifier().storage) {
5862 case glslang::EvqTemporary:
5863 case glslang::EvqGlobal:
5864 case glslang::EvqIn:
5865 case glslang::EvqInOut:
5866 case glslang::EvqConst:
5867 case glslang::EvqConstReadOnly:
5868 case glslang::EvqUniform:
5869 return true;
5870 default:
5871 return false;
5872 }
qining25262b32016-05-06 17:25:16 -04005873}
John Kessenich7c1aa102015-10-15 13:29:11 -06005874
5875// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005876// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005877// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005878// Return true if trivial.
5879bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5880{
5881 if (node == nullptr)
5882 return false;
5883
John Kessenich84cc15f2017-05-24 16:44:47 -06005884 // count non scalars as trivial, as well as anything coming from HLSL
5885 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005886 return true;
5887
John Kessenich7c1aa102015-10-15 13:29:11 -06005888 // symbols and constants are trivial
5889 if (isTrivialLeaf(node))
5890 return true;
5891
5892 // otherwise, it needs to be a simple operation or one or two leaf nodes
5893
5894 // not a simple operation
5895 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5896 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5897 if (binaryNode == nullptr && unaryNode == nullptr)
5898 return false;
5899
5900 // not on leaf nodes
5901 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5902 return false;
5903
5904 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5905 return false;
5906 }
5907
5908 switch (node->getAsOperator()->getOp()) {
5909 case glslang::EOpLogicalNot:
5910 case glslang::EOpConvIntToBool:
5911 case glslang::EOpConvUintToBool:
5912 case glslang::EOpConvFloatToBool:
5913 case glslang::EOpConvDoubleToBool:
5914 case glslang::EOpEqual:
5915 case glslang::EOpNotEqual:
5916 case glslang::EOpLessThan:
5917 case glslang::EOpGreaterThan:
5918 case glslang::EOpLessThanEqual:
5919 case glslang::EOpGreaterThanEqual:
5920 case glslang::EOpIndexDirect:
5921 case glslang::EOpIndexDirectStruct:
5922 case glslang::EOpLogicalXor:
5923 case glslang::EOpAny:
5924 case glslang::EOpAll:
5925 return true;
5926 default:
5927 return false;
5928 }
5929}
5930
5931// Emit short-circuiting code, where 'right' is never evaluated unless
5932// the left side is true (for &&) or false (for ||).
5933spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5934{
5935 spv::Id boolTypeId = builder.makeBoolType();
5936
5937 // emit left operand
5938 builder.clearAccessChain();
5939 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005940 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005941
5942 // Operands to accumulate OpPhi operands
5943 std::vector<spv::Id> phiOperands;
5944 // accumulate left operand's phi information
5945 phiOperands.push_back(leftId);
5946 phiOperands.push_back(builder.getBuildPoint()->getId());
5947
5948 // Make the two kinds of operation symmetric with a "!"
5949 // || => emit "if (! left) result = right"
5950 // && => emit "if ( left) result = right"
5951 //
5952 // TODO: this runtime "not" for || could be avoided by adding functionality
5953 // to 'builder' to have an "else" without an "then"
5954 if (op == glslang::EOpLogicalOr)
5955 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5956
5957 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005958 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005959
5960 // emit right operand as the "then" part of the "if"
5961 builder.clearAccessChain();
5962 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005963 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005964
5965 // accumulate left operand's phi information
5966 phiOperands.push_back(rightId);
5967 phiOperands.push_back(builder.getBuildPoint()->getId());
5968
5969 // finish the "if"
5970 ifBuilder.makeEndIf();
5971
5972 // phi together the two results
5973 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5974}
5975
Frank Henigman541f7bb2018-01-16 00:18:26 -05005976#ifdef AMD_EXTENSIONS
Rex Xu9d93a232016-05-05 12:30:44 +08005977// Return type Id of the imported set of extended instructions corresponds to the name.
5978// Import this set if it has not been imported yet.
5979spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5980{
5981 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5982 return extBuiltinMap[name];
5983 else {
Rex Xu51596642016-09-21 18:56:12 +08005984 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005985 spv::Id extBuiltins = builder.import(name);
5986 extBuiltinMap[name] = extBuiltins;
5987 return extBuiltins;
5988 }
5989}
Frank Henigman541f7bb2018-01-16 00:18:26 -05005990#endif
Rex Xu9d93a232016-05-05 12:30:44 +08005991
John Kessenich140f3df2015-06-26 16:58:36 -06005992}; // end anonymous namespace
5993
5994namespace glslang {
5995
John Kessenich68d78fd2015-07-12 19:28:10 -06005996void GetSpirvVersion(std::string& version)
5997{
John Kessenich9e55f632015-07-15 10:03:39 -06005998 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005999 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07006000 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06006001 version = buf;
6002}
6003
John Kessenicha372a3e2017-11-02 22:32:14 -06006004// For low-order part of the generator's magic number. Bump up
6005// when there is a change in the style (e.g., if SSA form changes,
6006// or a different instruction sequence to do something gets used).
6007int GetSpirvGeneratorVersion()
6008{
John Kessenich3f0d4bc2017-12-16 23:46:37 -07006009 // return 1; // start
6010 // return 2; // EOpAtomicCounterDecrement gets a post decrement, to map between GLSL -> SPIR-V
John Kessenich71b5da62018-02-06 08:06:36 -07006011 // return 3; // change/correct barrier-instruction operands, to match memory model group decisions
6012 return 4; // some deeper access chains: for dynamic vector component, and local Boolean component
John Kessenicha372a3e2017-11-02 22:32:14 -06006013}
6014
John Kessenich140f3df2015-06-26 16:58:36 -06006015// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006016void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06006017{
6018 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06006019 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006020 if (out.fail())
6021 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06006022 for (int i = 0; i < (int)spirv.size(); ++i) {
6023 unsigned int word = spirv[i];
6024 out.write((const char*)&word, 4);
6025 }
6026 out.close();
6027}
6028
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006029// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08006030void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006031{
6032 std::ofstream out;
6033 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006034 if (out.fail())
6035 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006036 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08006037 if (varName != nullptr) {
6038 out << "\t #pragma once" << std::endl;
6039 out << "const uint32_t " << varName << "[] = {" << std::endl;
6040 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006041 const int WORDS_PER_LINE = 8;
6042 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
6043 out << "\t";
6044 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6045 const unsigned int word = spirv[i + j];
6046 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6047 if (i + j + 1 < (int)spirv.size()) {
6048 out << ",";
6049 }
6050 }
6051 out << std::endl;
6052 }
Flavio15017db2017-02-15 14:29:33 -08006053 if (varName != nullptr) {
6054 out << "};";
6055 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006056 out.close();
6057}
6058
GregFcd1f1692017-09-21 18:40:22 -06006059#ifdef ENABLE_OPT
6060void errHandler(const std::string& str) {
6061 std::cerr << str << std::endl;
6062}
6063#endif
6064
John Kessenich140f3df2015-06-26 16:58:36 -06006065//
6066// Set up the glslang traversal
6067//
John Kessenich121853f2017-05-31 17:11:16 -06006068void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006069{
Lei Zhang17535f72016-05-04 15:55:59 -04006070 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006071 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006072}
6073
John Kessenich121853f2017-05-31 17:11:16 -06006074void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6075 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006076{
John Kessenich140f3df2015-06-26 16:58:36 -06006077 TIntermNode* root = intermediate.getTreeRoot();
6078
6079 if (root == 0)
6080 return;
6081
John Kessenich121853f2017-05-31 17:11:16 -06006082 glslang::SpvOptions defaultOptions;
6083 if (options == nullptr)
6084 options = &defaultOptions;
6085
John Kessenich140f3df2015-06-26 16:58:36 -06006086 glslang::GetThreadPoolAllocator().push();
6087
John Kessenich2b5ea9f2018-01-31 18:35:56 -07006088 TGlslangToSpvTraverser it(intermediate.getSpv().spv, &intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006089 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006090 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006091 it.dumpSpv(spirv);
6092
GregFcd1f1692017-09-21 18:40:22 -06006093#ifdef ENABLE_OPT
6094 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6095 // eg. forward and remove memory writes of opaque types.
6096 if ((intermediate.getSource() == EShSourceHlsl ||
6097 options->optimizeSize) &&
6098 !options->disableOptimizer) {
6099 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6100
6101 spvtools::Optimizer optimizer(target_env);
6102 optimizer.SetMessageConsumer([](spv_message_level_t level,
6103 const char* source,
6104 const spv_position_t& position,
6105 const char* message) {
6106 std::cerr << StringifyMessage(level, source, position, message)
6107 << std::endl;
6108 });
6109
6110 optimizer.RegisterPass(CreateInlineExhaustivePass());
GregFe0639282017-12-21 10:55:57 -07006111 optimizer.RegisterPass(CreateEliminateDeadFunctionsPass());
6112 optimizer.RegisterPass(CreateScalarReplacementPass());
GregFcd1f1692017-09-21 18:40:22 -06006113 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
6114 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
6115 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
6116 optimizer.RegisterPass(CreateInsertExtractElimPass());
6117 optimizer.RegisterPass(CreateAggressiveDCEPass());
6118 optimizer.RegisterPass(CreateDeadBranchElimPass());
GregFcc80d802017-10-23 16:48:42 -06006119 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06006120 optimizer.RegisterPass(CreateBlockMergePass());
6121 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
6122 optimizer.RegisterPass(CreateInsertExtractElimPass());
6123 optimizer.RegisterPass(CreateAggressiveDCEPass());
6124 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
6125 // if (options->optimizeSize)
6126 // optimizer.RegisterPass(CreateCommonUniformElimPass());
6127
6128 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
6129 return;
6130
6131 // Remove dead module-level objects: functions, types, vars
6132 // TODO(greg-lunarg): Switch to spirv-opt versions when available
6133 spv::spirvbin_t Remapper(0);
6134 Remapper.registerErrorHandler(errHandler);
6135 Remapper.remap(spirv, spv::spirvbin_t::DCE_ALL);
6136 }
6137#endif
6138
John Kessenich140f3df2015-06-26 16:58:36 -06006139 glslang::GetThreadPoolAllocator().pop();
6140}
6141
6142}; // end namespace glslang