blob: f933a043961a47df048aabc6960a61798c906632 [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 Kessenich121853f2017-05-31 17:11:16 -0600110 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger, glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700111 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600112
113 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
114 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
115 void visitConstantUnion(glslang::TIntermConstantUnion*);
116 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
117 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
118 void visitSymbol(glslang::TIntermSymbol* symbol);
119 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
120 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
121 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
122
John Kessenichfca82622016-11-26 13:23:20 -0700123 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700124 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600125
126protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800127 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800128 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100129 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700130 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
Rex Xu57e65922017-07-04 23:23:40 +0800131 spv::SelectionControlMask TranslateSelectionControl(glslang::TSelectionControl) const;
steve-lunargf1709e72017-05-02 20:14:50 -0600132 spv::LoopControlMask TranslateLoopControl(glslang::TLoopControl) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600133 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600134 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
135 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600136 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
137 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
138 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600139 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700140 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600141 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600142 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
143 glslang::TLayoutPacking, const glslang::TQualifier&);
144 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
145 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700146 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700147 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800148 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600149 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700150 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700151 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
152 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
153 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 +0100154 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600155
John Kessenich6fccb3c2016-09-19 16:01:41 -0600156 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd41993d2017-09-10 15:21:05 -0600157 bool writableParam(glslang::TStorageQualifier);
158 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600159 void makeFunctions(const glslang::TIntermSequence&);
160 void makeGlobalInitializers(const glslang::TIntermSequence&);
161 void visitFunctions(const glslang::TIntermSequence&);
162 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800163 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600164 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
165 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600166 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
167
qining25262b32016-05-06 17:25:16 -0400168 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);
169 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
170 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 +0800171 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 +0800172 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 -0600173 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800174 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 +0800175 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800176 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600177 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 +0800178 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600179 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
180 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700181 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600182 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700183 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400184 spv::Id createSpvConstant(const glslang::TIntermTyped&);
185 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600186 bool isTrivialLeaf(const glslang::TIntermTyped* node);
187 bool isTrivial(const glslang::TIntermTyped* node);
188 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800189 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600190
John Kessenich121853f2017-05-31 17:11:16 -0600191 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600192 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600193 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700194 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600195 int sequenceDepth;
196
Lei Zhang17535f72016-05-04 15:55:59 -0400197 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400198
John Kessenich140f3df2015-06-26 16:58:36 -0600199 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
200 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700201 bool inEntryPoint;
202 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700203 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 -0700204 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600205 const glslang::TIntermediate* glslangIntermediate;
206 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800207 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600208
John Kessenich2f273362015-07-18 22:34:27 -0600209 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600210 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600211 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700212 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600213 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 -0600214 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600215};
216
217//
218// Helper functions for translating glslang representations to SPIR-V enumerants.
219//
220
221// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700222spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600223{
John Kessenich66e2faf2016-03-12 18:34:36 -0700224 switch (source) {
225 case glslang::EShSourceGlsl:
226 switch (profile) {
227 case ENoProfile:
228 case ECoreProfile:
229 case ECompatibilityProfile:
230 return spv::SourceLanguageGLSL;
231 case EEsProfile:
232 return spv::SourceLanguageESSL;
233 default:
234 return spv::SourceLanguageUnknown;
235 }
236 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600237 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600238 default:
239 return spv::SourceLanguageUnknown;
240 }
241}
242
243// Translate glslang language (stage) to SPIR-V execution model.
244spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
245{
246 switch (stage) {
247 case EShLangVertex: return spv::ExecutionModelVertex;
248 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
249 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
250 case EShLangGeometry: return spv::ExecutionModelGeometry;
251 case EShLangFragment: return spv::ExecutionModelFragment;
252 case EShLangCompute: return spv::ExecutionModelGLCompute;
253 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700254 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600255 return spv::ExecutionModelFragment;
256 }
257}
258
John Kessenich140f3df2015-06-26 16:58:36 -0600259// Translate glslang sampler type to SPIR-V dimensionality.
260spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
261{
262 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700263 case glslang::Esd1D: return spv::Dim1D;
264 case glslang::Esd2D: return spv::Dim2D;
265 case glslang::Esd3D: return spv::Dim3D;
266 case glslang::EsdCube: return spv::DimCube;
267 case glslang::EsdRect: return spv::DimRect;
268 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700269 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600270 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700271 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600272 return spv::Dim2D;
273 }
274}
275
John Kessenichf6640762016-08-01 19:44:00 -0600276// Translate glslang precision to SPIR-V precision decorations.
277spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600278{
John Kessenichf6640762016-08-01 19:44:00 -0600279 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700280 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600281 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600282 default:
283 return spv::NoPrecision;
284 }
285}
286
John Kessenichf6640762016-08-01 19:44:00 -0600287// Translate glslang type to SPIR-V precision decorations.
288spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
289{
290 return TranslatePrecisionDecoration(type.getQualifier().precision);
291}
292
John Kessenich140f3df2015-06-26 16:58:36 -0600293// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600294spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600295{
296 if (type.getBasicType() == glslang::EbtBlock) {
297 switch (type.getQualifier().storage) {
298 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600299 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600300 case glslang::EvqVaryingIn: return spv::DecorationBlock;
301 case glslang::EvqVaryingOut: return spv::DecorationBlock;
302 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700303 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600304 break;
305 }
306 }
307
John Kessenich4016e382016-07-15 11:53:56 -0600308 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600309}
310
Rex Xu1da878f2016-02-21 20:59:01 +0800311// Translate glslang type to SPIR-V memory decorations.
312void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
313{
314 if (qualifier.coherent)
315 memory.push_back(spv::DecorationCoherent);
316 if (qualifier.volatil)
317 memory.push_back(spv::DecorationVolatile);
318 if (qualifier.restrict)
319 memory.push_back(spv::DecorationRestrict);
320 if (qualifier.readonly)
321 memory.push_back(spv::DecorationNonWritable);
322 if (qualifier.writeonly)
323 memory.push_back(spv::DecorationNonReadable);
324}
325
John Kessenich140f3df2015-06-26 16:58:36 -0600326// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700327spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600328{
329 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700330 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600331 case glslang::ElmRowMajor:
332 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700333 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600334 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700335 default:
336 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600337 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600338 }
339 } else {
340 switch (type.getBasicType()) {
341 default:
John Kessenich4016e382016-07-15 11:53:56 -0600342 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600343 break;
344 case glslang::EbtBlock:
345 switch (type.getQualifier().storage) {
346 case glslang::EvqUniform:
347 case glslang::EvqBuffer:
348 switch (type.getQualifier().layoutPacking) {
349 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600350 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
351 default:
John Kessenich4016e382016-07-15 11:53:56 -0600352 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600353 }
354 case glslang::EvqVaryingIn:
355 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700356 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600357 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600358 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700359 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600360 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600361 }
362 }
363 }
364}
365
366// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600367// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700368// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800369spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600370{
Rex Xubbceed72016-05-21 09:40:44 +0800371 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700372 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600373 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800374 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700375 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700376 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600377 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800378#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800379 else if (qualifier.explicitInterp) {
380 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800381 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800382 }
Rex Xu9d93a232016-05-05 12:30:44 +0800383#endif
Rex Xubbceed72016-05-21 09:40:44 +0800384 else
John Kessenich4016e382016-07-15 11:53:56 -0600385 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800386}
387
388// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600389// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800390// should be applied.
391spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
392{
393 if (qualifier.patch)
394 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700395 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600396 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700397 else if (qualifier.sample) {
398 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600399 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700400 } else
John Kessenich4016e382016-07-15 11:53:56 -0600401 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600402}
403
John Kessenich92187592016-02-01 13:45:25 -0700404// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700405spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600406{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700407 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600408 return spv::DecorationInvariant;
409 else
John Kessenich4016e382016-07-15 11:53:56 -0600410 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600411}
412
qining9220dbb2016-05-04 17:34:38 -0400413// If glslang type is noContraction, return SPIR-V NoContraction decoration.
414spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
415{
416 if (qualifier.noContraction)
417 return spv::DecorationNoContraction;
418 else
John Kessenich4016e382016-07-15 11:53:56 -0600419 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400420}
421
David Netoa901ffe2016-06-08 14:11:40 +0100422// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
423// associated capabilities when required. For some built-in variables, a capability
424// is generated only when using the variable in an executable instruction, but not when
425// just declaring a struct member variable with it. This is true for PointSize,
426// ClipDistance, and CullDistance.
427spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600428{
429 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700430 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600431 // Defer adding the capability until the built-in is actually used.
432 if (! memberDeclaration) {
433 switch (glslangIntermediate->getStage()) {
434 case EShLangGeometry:
435 builder.addCapability(spv::CapabilityGeometryPointSize);
436 break;
437 case EShLangTessControl:
438 case EShLangTessEvaluation:
439 builder.addCapability(spv::CapabilityTessellationPointSize);
440 break;
441 default:
442 break;
443 }
John Kessenich92187592016-02-01 13:45:25 -0700444 }
445 return spv::BuiltInPointSize;
446
John Kessenichebb50532016-05-16 19:22:05 -0600447 // These *Distance capabilities logically belong here, but if the member is declared and
448 // then never used, consumers of SPIR-V prefer the capability not be declared.
449 // They are now generated when used, rather than here when declared.
450 // Potentially, the specification should be more clear what the minimum
451 // use needed is to trigger the capability.
452 //
John Kessenich92187592016-02-01 13:45:25 -0700453 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100454 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800455 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700456 return spv::BuiltInClipDistance;
457
458 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100459 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800460 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700461 return spv::BuiltInCullDistance;
462
463 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600464 builder.addCapability(spv::CapabilityMultiViewport);
465 if (glslangIntermediate->getStage() == EShLangVertex ||
466 glslangIntermediate->getStage() == EShLangTessControl ||
467 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800468
John Kessenichba6a3c22017-09-13 13:22:50 -0600469 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
470 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800471 }
John Kessenich92187592016-02-01 13:45:25 -0700472 return spv::BuiltInViewportIndex;
473
John Kessenich5e801132016-02-15 11:09:46 -0700474 case glslang::EbvSampleId:
475 builder.addCapability(spv::CapabilitySampleRateShading);
476 return spv::BuiltInSampleId;
477
478 case glslang::EbvSamplePosition:
479 builder.addCapability(spv::CapabilitySampleRateShading);
480 return spv::BuiltInSamplePosition;
481
482 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700483 return spv::BuiltInSampleMask;
484
John Kessenich78a45572016-07-08 14:05:15 -0600485 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600486 builder.addCapability(spv::CapabilityGeometry);
487 if (glslangIntermediate->getStage() == EShLangVertex ||
488 glslangIntermediate->getStage() == EShLangTessControl ||
489 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800490
John Kessenichba6a3c22017-09-13 13:22:50 -0600491 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
492 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800493 }
John Kessenich78a45572016-07-08 14:05:15 -0600494 return spv::BuiltInLayer;
495
John Kessenich140f3df2015-06-26 16:58:36 -0600496 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600497 case glslang::EbvVertexId: return spv::BuiltInVertexId;
498 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700499 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
500 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800501
John Kessenichda581a22015-10-14 14:10:30 -0600502 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800503 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
504 builder.addCapability(spv::CapabilityDrawParameters);
505 return spv::BuiltInBaseVertex;
506
John Kessenichda581a22015-10-14 14:10:30 -0600507 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800508 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
509 builder.addCapability(spv::CapabilityDrawParameters);
510 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200511
John Kessenichda581a22015-10-14 14:10:30 -0600512 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800513 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
514 builder.addCapability(spv::CapabilityDrawParameters);
515 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200516
517 case glslang::EbvPrimitiveId:
518 if (glslangIntermediate->getStage() == EShLangFragment)
519 builder.addCapability(spv::CapabilityGeometry);
520 return spv::BuiltInPrimitiveId;
521
Rex Xu37cdcee2017-06-29 17:46:34 +0800522 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800523 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
524 builder.addCapability(spv::CapabilityStencilExportEXT);
525 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800526
John Kessenich140f3df2015-06-26 16:58:36 -0600527 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600528 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
529 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
530 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
531 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
532 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
533 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
534 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600535 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
536 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
537 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
538 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
539 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
540 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
541 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
542 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800543
Rex Xu574ab042016-04-14 16:53:07 +0800544 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800545 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800546 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
547 return spv::BuiltInSubgroupSize;
548
Rex Xu574ab042016-04-14 16:53:07 +0800549 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800550 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800551 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
552 return spv::BuiltInSubgroupLocalInvocationId;
553
Rex Xu574ab042016-04-14 16:53:07 +0800554 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800555 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
556 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
557 return spv::BuiltInSubgroupEqMaskKHR;
558
Rex Xu574ab042016-04-14 16:53:07 +0800559 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800560 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
561 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
562 return spv::BuiltInSubgroupGeMaskKHR;
563
Rex Xu574ab042016-04-14 16:53:07 +0800564 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800565 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
566 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
567 return spv::BuiltInSubgroupGtMaskKHR;
568
Rex Xu574ab042016-04-14 16:53:07 +0800569 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800570 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
571 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
572 return spv::BuiltInSubgroupLeMaskKHR;
573
Rex Xu574ab042016-04-14 16:53:07 +0800574 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800575 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
576 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
577 return spv::BuiltInSubgroupLtMaskKHR;
578
Rex Xu9d93a232016-05-05 12:30:44 +0800579#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800580 case glslang::EbvBaryCoordNoPersp:
581 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
582 return spv::BuiltInBaryCoordNoPerspAMD;
583
584 case glslang::EbvBaryCoordNoPerspCentroid:
585 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
586 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
587
588 case glslang::EbvBaryCoordNoPerspSample:
589 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
590 return spv::BuiltInBaryCoordNoPerspSampleAMD;
591
592 case glslang::EbvBaryCoordSmooth:
593 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
594 return spv::BuiltInBaryCoordSmoothAMD;
595
596 case glslang::EbvBaryCoordSmoothCentroid:
597 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
598 return spv::BuiltInBaryCoordSmoothCentroidAMD;
599
600 case glslang::EbvBaryCoordSmoothSample:
601 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
602 return spv::BuiltInBaryCoordSmoothSampleAMD;
603
604 case glslang::EbvBaryCoordPullModel:
605 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
606 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800607#endif
chaoc771d89f2017-01-13 01:10:53 -0800608
John Kessenich6c8aaac2017-02-27 01:20:51 -0700609 case glslang::EbvDeviceIndex:
610 builder.addExtension(spv::E_SPV_KHR_device_group);
611 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700612 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700613
614 case glslang::EbvViewIndex:
615 builder.addExtension(spv::E_SPV_KHR_multiview);
616 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700617 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700618
chaoc771d89f2017-01-13 01:10:53 -0800619#ifdef NV_EXTENSIONS
620 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800621 if (!memberDeclaration) {
622 builder.addExtension(spv::E_SPV_NV_viewport_array2);
623 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
624 }
chaoc771d89f2017-01-13 01:10:53 -0800625 return spv::BuiltInViewportMaskNV;
626 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800627 if (!memberDeclaration) {
628 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
629 builder.addCapability(spv::CapabilityShaderStereoViewNV);
630 }
chaoc771d89f2017-01-13 01:10:53 -0800631 return spv::BuiltInSecondaryPositionNV;
632 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800633 if (!memberDeclaration) {
634 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
635 builder.addCapability(spv::CapabilityShaderStereoViewNV);
636 }
chaoc771d89f2017-01-13 01:10:53 -0800637 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800638 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800639 if (!memberDeclaration) {
640 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
641 builder.addCapability(spv::CapabilityPerViewAttributesNV);
642 }
chaocdf3956c2017-02-14 14:52:34 -0800643 return spv::BuiltInPositionPerViewNV;
644 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800645 if (!memberDeclaration) {
646 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
647 builder.addCapability(spv::CapabilityPerViewAttributesNV);
648 }
chaocdf3956c2017-02-14 14:52:34 -0800649 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700650 case glslang::EbvFragFullyCoveredNV:
651 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
652 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
653 return spv::BuiltInFullyCoveredEXT;
chaoc771d89f2017-01-13 01:10:53 -0800654#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800655 default:
656 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600657 }
658}
659
Rex Xufc618912015-09-09 16:42:49 +0800660// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700661spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800662{
663 assert(type.getBasicType() == glslang::EbtSampler);
664
John Kessenich5d0fa972016-02-15 11:57:00 -0700665 // Check for capabilities
666 switch (type.getQualifier().layoutFormat) {
667 case glslang::ElfRg32f:
668 case glslang::ElfRg16f:
669 case glslang::ElfR11fG11fB10f:
670 case glslang::ElfR16f:
671 case glslang::ElfRgba16:
672 case glslang::ElfRgb10A2:
673 case glslang::ElfRg16:
674 case glslang::ElfRg8:
675 case glslang::ElfR16:
676 case glslang::ElfR8:
677 case glslang::ElfRgba16Snorm:
678 case glslang::ElfRg16Snorm:
679 case glslang::ElfRg8Snorm:
680 case glslang::ElfR16Snorm:
681 case glslang::ElfR8Snorm:
682
683 case glslang::ElfRg32i:
684 case glslang::ElfRg16i:
685 case glslang::ElfRg8i:
686 case glslang::ElfR16i:
687 case glslang::ElfR8i:
688
689 case glslang::ElfRgb10a2ui:
690 case glslang::ElfRg32ui:
691 case glslang::ElfRg16ui:
692 case glslang::ElfRg8ui:
693 case glslang::ElfR16ui:
694 case glslang::ElfR8ui:
695 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
696 break;
697
698 default:
699 break;
700 }
701
702 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800703 switch (type.getQualifier().layoutFormat) {
704 case glslang::ElfNone: return spv::ImageFormatUnknown;
705 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
706 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
707 case glslang::ElfR32f: return spv::ImageFormatR32f;
708 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
709 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
710 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
711 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
712 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
713 case glslang::ElfR16f: return spv::ImageFormatR16f;
714 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
715 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
716 case glslang::ElfRg16: return spv::ImageFormatRg16;
717 case glslang::ElfRg8: return spv::ImageFormatRg8;
718 case glslang::ElfR16: return spv::ImageFormatR16;
719 case glslang::ElfR8: return spv::ImageFormatR8;
720 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
721 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
722 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
723 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
724 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
725 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
726 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
727 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
728 case glslang::ElfR32i: return spv::ImageFormatR32i;
729 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
730 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
731 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
732 case glslang::ElfR16i: return spv::ImageFormatR16i;
733 case glslang::ElfR8i: return spv::ImageFormatR8i;
734 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
735 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
736 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
737 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
738 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
739 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
740 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
741 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
742 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
743 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600744 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800745 }
746}
747
Rex Xu57e65922017-07-04 23:23:40 +0800748spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(glslang::TSelectionControl selectionControl) const
749{
750 switch (selectionControl) {
751 case glslang::ESelectionControlNone: return spv::SelectionControlMaskNone;
752 case glslang::ESelectionControlFlatten: return spv::SelectionControlFlattenMask;
753 case glslang::ESelectionControlDontFlatten: return spv::SelectionControlDontFlattenMask;
754 default: return spv::SelectionControlMaskNone;
755 }
756}
757
steve-lunargf1709e72017-05-02 20:14:50 -0600758spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
759{
760 switch (loopControl) {
761 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
762 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
763 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
764 // TODO: DependencyInfinite
765 // TODO: DependencyLength
766 default: return spv::LoopControlMaskNone;
767 }
768}
769
John Kessenicha5c5fb62017-05-05 05:09:58 -0600770// Translate glslang type to SPIR-V storage class.
771spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
772{
773 if (type.getQualifier().isPipeInput())
774 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600775 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600776 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600777
778 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
779 type.getQualifier().storage == glslang::EvqUniform) {
780 if (type.getBasicType() == glslang::EbtAtomicUint)
781 return spv::StorageClassAtomicCounter;
782 if (type.containsOpaque())
783 return spv::StorageClassUniformConstant;
784 }
785
786 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600787 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
788 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600789 }
790
791 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600792 if (type.getQualifier().layoutPushConstant)
793 return spv::StorageClassPushConstant;
794 if (type.getBasicType() == glslang::EbtBlock)
795 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600796 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600797 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600798
799 switch (type.getQualifier().storage) {
800 case glslang::EvqShared: return spv::StorageClassWorkgroup;
801 case glslang::EvqGlobal: return spv::StorageClassPrivate;
802 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
803 case glslang::EvqTemporary: return spv::StorageClassFunction;
804 default:
805 assert(0);
806 break;
807 }
808
809 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600810}
811
qining25262b32016-05-06 17:25:16 -0400812// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700813// descriptor set.
814bool IsDescriptorResource(const glslang::TType& type)
815{
John Kessenichf7497e22016-03-08 21:36:22 -0700816 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700817 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700818 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700819
820 // non block...
821 // basically samplerXXX/subpass/sampler/texture are all included
822 // if they are the global-scope-class, not the function parameter
823 // (or local, if they ever exist) class.
824 if (type.getBasicType() == glslang::EbtSampler)
825 return type.getQualifier().isUniformOrBuffer();
826
827 // None of the above.
828 return false;
829}
830
John Kesseniche0b6cad2015-12-24 10:30:13 -0700831void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
832{
833 if (child.layoutMatrix == glslang::ElmNone)
834 child.layoutMatrix = parent.layoutMatrix;
835
836 if (parent.invariant)
837 child.invariant = true;
838 if (parent.nopersp)
839 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800840#ifdef AMD_EXTENSIONS
841 if (parent.explicitInterp)
842 child.explicitInterp = true;
843#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700844 if (parent.flat)
845 child.flat = true;
846 if (parent.centroid)
847 child.centroid = true;
848 if (parent.patch)
849 child.patch = true;
850 if (parent.sample)
851 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800852 if (parent.coherent)
853 child.coherent = true;
854 if (parent.volatil)
855 child.volatil = true;
856 if (parent.restrict)
857 child.restrict = true;
858 if (parent.readonly)
859 child.readonly = true;
860 if (parent.writeonly)
861 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700862}
863
John Kessenichf2b7f332016-09-01 17:05:23 -0600864bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700865{
John Kessenich7b9fa252016-01-21 18:56:57 -0700866 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600867 // - struct members might inherit from a struct declaration
868 // (note that non-block structs don't explicitly inherit,
869 // only implicitly, meaning no decoration involved)
870 // - affect decorations on the struct members
871 // (note smooth does not, and expecting something like volatile
872 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700873 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600874 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700875}
876
John Kessenich140f3df2015-06-26 16:58:36 -0600877//
878// Implement the TGlslangToSpvTraverser class.
879//
880
John Kessenich121853f2017-05-31 17:11:16 -0600881TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate,
882 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
883 : TIntermTraverser(true, false, true),
884 options(options),
885 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600886 sequenceDepth(0), logger(buildLogger),
John Kessenicha372a3e2017-11-02 22:32:14 -0600887 builder((glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700888 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600889 glslangIntermediate(glslangIntermediate)
890{
891 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
892
893 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600894 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
895 glslangIntermediate->getVersion());
896
John Kessenich121853f2017-05-31 17:11:16 -0600897 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600898 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600899 builder.setSourceFile(glslangIntermediate->getSourceFile());
900
901 // Set the source shader's text. If for SPV version 1.0, include
902 // a preamble in comments stating the OpModuleProcessed instructions.
903 // Otherwise, emit those as actual instructions.
904 std::string text;
905 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
906 for (int p = 0; p < (int)processes.size(); ++p) {
907 if (glslangIntermediate->getSpv().spv < 0x00010100) {
908 text.append("// OpModuleProcessed ");
909 text.append(processes[p]);
910 text.append("\n");
911 } else
912 builder.addModuleProcessed(processes[p]);
913 }
914 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
915 text.append("#line 1\n");
916 text.append(glslangIntermediate->getSourceText());
917 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600918 }
John Kessenich140f3df2015-06-26 16:58:36 -0600919 stdBuiltins = builder.import("GLSL.std.450");
920 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600921 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
922 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600923
924 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600925 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
926 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600927 builder.addSourceExtension(it->c_str());
928
929 // Add the top-level modes for this shader.
930
John Kessenich92187592016-02-01 13:45:25 -0700931 if (glslangIntermediate->getXfbMode()) {
932 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600933 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700934 }
John Kessenich140f3df2015-06-26 16:58:36 -0600935
936 unsigned int mode;
937 switch (glslangIntermediate->getStage()) {
938 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600939 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600940 break;
941
steve-lunarge7412492017-03-23 11:56:07 -0600942 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600943 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600944 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600945
steve-lunarge7412492017-03-23 11:56:07 -0600946 glslang::TLayoutGeometry primitive;
947
948 if (glslangIntermediate->getStage() == EShLangTessControl) {
949 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
950 primitive = glslangIntermediate->getOutputPrimitive();
951 } else {
952 primitive = glslangIntermediate->getInputPrimitive();
953 }
954
955 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700956 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
957 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
958 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600959 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600960 }
John Kessenich4016e382016-07-15 11:53:56 -0600961 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600962 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
963
John Kesseniche6903322015-10-13 16:29:02 -0600964 switch (glslangIntermediate->getVertexSpacing()) {
965 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
966 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
967 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600968 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600969 }
John Kessenich4016e382016-07-15 11:53:56 -0600970 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600971 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
972
973 switch (glslangIntermediate->getVertexOrder()) {
974 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
975 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600976 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600977 }
John Kessenich4016e382016-07-15 11:53:56 -0600978 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600979 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
980
981 if (glslangIntermediate->getPointMode())
982 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600983 break;
984
985 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600986 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600987 switch (glslangIntermediate->getInputPrimitive()) {
988 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
989 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
990 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700991 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600992 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600993 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600994 }
John Kessenich4016e382016-07-15 11:53:56 -0600995 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600996 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600997
John Kessenich140f3df2015-06-26 16:58:36 -0600998 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
999
1000 switch (glslangIntermediate->getOutputPrimitive()) {
1001 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1002 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1003 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001004 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001005 }
John Kessenich4016e382016-07-15 11:53:56 -06001006 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001007 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1008 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1009 break;
1010
1011 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001012 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001013 if (glslangIntermediate->getPixelCenterInteger())
1014 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001015
John Kessenich140f3df2015-06-26 16:58:36 -06001016 if (glslangIntermediate->getOriginUpperLeft())
1017 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001018 else
1019 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001020
1021 if (glslangIntermediate->getEarlyFragmentTests())
1022 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1023
chaocc1204522017-06-30 17:14:30 -07001024 if (glslangIntermediate->getPostDepthCoverage()) {
1025 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1026 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1027 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1028 }
1029
John Kesseniche6903322015-10-13 16:29:02 -06001030 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001031 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1032 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001033 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001034 }
John Kessenich4016e382016-07-15 11:53:56 -06001035 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001036 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1037
1038 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1039 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001040 break;
1041
1042 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001043 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001044 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1045 glslangIntermediate->getLocalSize(1),
1046 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001047 break;
1048
1049 default:
1050 break;
1051 }
John Kessenich140f3df2015-06-26 16:58:36 -06001052}
1053
John Kessenichfca82622016-11-26 13:23:20 -07001054// Finish creating SPV, after the traversal is complete.
1055void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001056{
John Kessenich517fe7a2016-11-26 13:31:47 -07001057 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001058 builder.setBuildPoint(shaderEntry->getLastBlock());
1059 builder.leaveFunction();
1060 }
1061
John Kessenich7ba63412015-12-20 17:37:07 -07001062 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001063 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1064 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001065
qiningda397332016-03-09 19:54:03 -05001066 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001067}
1068
John Kessenichfca82622016-11-26 13:23:20 -07001069// Write the SPV into 'out'.
1070void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001071{
John Kessenichfca82622016-11-26 13:23:20 -07001072 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001073}
1074
1075//
1076// Implement the traversal functions.
1077//
1078// Return true from interior nodes to have the external traversal
1079// continue on to children. Return false if children were
1080// already processed.
1081//
1082
1083//
qining25262b32016-05-06 17:25:16 -04001084// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001085// - uniform/input reads
1086// - output writes
1087// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1088// - something simple that degenerates into the last bullet
1089//
1090void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1091{
qining75d1d802016-04-06 14:42:01 -04001092 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1093 if (symbol->getType().getQualifier().isSpecConstant())
1094 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1095
John Kessenich140f3df2015-06-26 16:58:36 -06001096 // getSymbolId() will set up all the IO decorations on the first call.
1097 // Formal function parameters were mapped during makeFunctions().
1098 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001099
1100 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1101 if (builder.isPointer(id)) {
1102 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001103 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1104 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1105 iOSet.insert(id);
1106 }
John Kessenich7ba63412015-12-20 17:37:07 -07001107 }
1108
1109 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001110 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001111 // Prepare to generate code for the access
1112
1113 // L-value chains will be computed left to right. We're on the symbol now,
1114 // which is the left-most part of the access chain, so now is "clear" time,
1115 // followed by setting the base.
1116 builder.clearAccessChain();
1117
1118 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001119 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001120 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001121 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001122 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001123 // These are also pure R-values.
1124 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001125 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001126 builder.setAccessChainRValue(id);
1127 else
1128 builder.setAccessChainLValue(id);
1129 }
1130}
1131
1132bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1133{
John Kesseniche485c7a2017-05-31 18:50:53 -06001134 builder.setLine(node->getLoc().line);
1135
qining40887662016-04-03 22:20:42 -04001136 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1137 if (node->getType().getQualifier().isSpecConstant())
1138 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1139
John Kessenich140f3df2015-06-26 16:58:36 -06001140 // First, handle special cases
1141 switch (node->getOp()) {
1142 case glslang::EOpAssign:
1143 case glslang::EOpAddAssign:
1144 case glslang::EOpSubAssign:
1145 case glslang::EOpMulAssign:
1146 case glslang::EOpVectorTimesMatrixAssign:
1147 case glslang::EOpVectorTimesScalarAssign:
1148 case glslang::EOpMatrixTimesScalarAssign:
1149 case glslang::EOpMatrixTimesMatrixAssign:
1150 case glslang::EOpDivAssign:
1151 case glslang::EOpModAssign:
1152 case glslang::EOpAndAssign:
1153 case glslang::EOpInclusiveOrAssign:
1154 case glslang::EOpExclusiveOrAssign:
1155 case glslang::EOpLeftShiftAssign:
1156 case glslang::EOpRightShiftAssign:
1157 // A bin-op assign "a += b" means the same thing as "a = a + b"
1158 // where a is evaluated before b. For a simple assignment, GLSL
1159 // says to evaluate the left before the right. So, always, left
1160 // node then right node.
1161 {
1162 // get the left l-value, save it away
1163 builder.clearAccessChain();
1164 node->getLeft()->traverse(this);
1165 spv::Builder::AccessChain lValue = builder.getAccessChain();
1166
1167 // evaluate the right
1168 builder.clearAccessChain();
1169 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001170 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001171
1172 if (node->getOp() != glslang::EOpAssign) {
1173 // the left is also an r-value
1174 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001175 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001176
1177 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001178 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001179 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001180 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1181 node->getType().getBasicType());
1182
1183 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001184 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001185 }
1186
1187 // store the result
1188 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001189 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001190
1191 // assignments are expressions having an rValue after they are evaluated...
1192 builder.clearAccessChain();
1193 builder.setAccessChainRValue(rValue);
1194 }
1195 return false;
1196 case glslang::EOpIndexDirect:
1197 case glslang::EOpIndexDirectStruct:
1198 {
1199 // Get the left part of the access chain.
1200 node->getLeft()->traverse(this);
1201
1202 // Add the next element in the chain
1203
David Netoa901ffe2016-06-08 14:11:40 +01001204 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001205 if (! node->getLeft()->getType().isArray() &&
1206 node->getLeft()->getType().isVector() &&
1207 node->getOp() == glslang::EOpIndexDirect) {
1208 // This is essentially a hard-coded vector swizzle of size 1,
1209 // so short circuit the access-chain stuff with a swizzle.
1210 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001211 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001212 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001213 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001214 int spvIndex = glslangIndex;
1215 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1216 node->getOp() == glslang::EOpIndexDirectStruct)
1217 {
1218 // This may be, e.g., an anonymous block-member selection, which generally need
1219 // index remapping due to hidden members in anonymous blocks.
1220 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1221 assert(remapper.size() > 0);
1222 spvIndex = remapper[glslangIndex];
1223 }
John Kessenichebb50532016-05-16 19:22:05 -06001224
David Netoa901ffe2016-06-08 14:11:40 +01001225 // normal case for indexing array or structure or block
1226 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1227
1228 // Add capabilities here for accessing PointSize and clip/cull distance.
1229 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001230 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001231 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001232 }
1233 }
1234 return false;
1235 case glslang::EOpIndexIndirect:
1236 {
1237 // Structure or array or vector indirection.
1238 // Will use native SPIR-V access-chain for struct and array indirection;
1239 // matrices are arrays of vectors, so will also work for a matrix.
1240 // Will use the access chain's 'component' for variable index into a vector.
1241
1242 // This adapter is building access chains left to right.
1243 // Set up the access chain to the left.
1244 node->getLeft()->traverse(this);
1245
1246 // save it so that computing the right side doesn't trash it
1247 spv::Builder::AccessChain partial = builder.getAccessChain();
1248
1249 // compute the next index in the chain
1250 builder.clearAccessChain();
1251 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001252 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001253
1254 // restore the saved access chain
1255 builder.setAccessChain(partial);
1256
1257 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001258 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001259 else
John Kessenichfa668da2015-09-13 14:46:30 -06001260 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001261 }
1262 return false;
1263 case glslang::EOpVectorSwizzle:
1264 {
1265 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001266 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001267 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001268 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001269 }
1270 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001271 case glslang::EOpMatrixSwizzle:
1272 logger->missingFunctionality("matrix swizzle");
1273 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001274 case glslang::EOpLogicalOr:
1275 case glslang::EOpLogicalAnd:
1276 {
1277
1278 // These may require short circuiting, but can sometimes be done as straight
1279 // binary operations. The right operand must be short circuited if it has
1280 // side effects, and should probably be if it is complex.
1281 if (isTrivial(node->getRight()->getAsTyped()))
1282 break; // handle below as a normal binary operation
1283 // otherwise, we need to do dynamic short circuiting on the right operand
1284 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1285 builder.clearAccessChain();
1286 builder.setAccessChainRValue(result);
1287 }
1288 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001289 default:
1290 break;
1291 }
1292
1293 // Assume generic binary op...
1294
John Kessenich32cfd492016-02-02 12:37:46 -07001295 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001296 builder.clearAccessChain();
1297 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001298 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001299
John Kessenich32cfd492016-02-02 12:37:46 -07001300 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001301 builder.clearAccessChain();
1302 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001303 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001304
John Kessenich32cfd492016-02-02 12:37:46 -07001305 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001306 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001307 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001308 convertGlslangToSpvType(node->getType()), left, right,
1309 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001310
John Kessenich50e57562015-12-21 21:21:11 -07001311 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001312 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001313 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001314 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001315 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001316 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001317 return false;
1318 }
John Kessenich140f3df2015-06-26 16:58:36 -06001319}
1320
1321bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1322{
John Kesseniche485c7a2017-05-31 18:50:53 -06001323 builder.setLine(node->getLoc().line);
1324
qining40887662016-04-03 22:20:42 -04001325 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1326 if (node->getType().getQualifier().isSpecConstant())
1327 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1328
John Kessenichfc51d282015-08-19 13:34:18 -06001329 spv::Id result = spv::NoResult;
1330
1331 // try texturing first
1332 result = createImageTextureFunctionCall(node);
1333 if (result != spv::NoResult) {
1334 builder.clearAccessChain();
1335 builder.setAccessChainRValue(result);
1336
1337 return false; // done with this node
1338 }
1339
1340 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001341
1342 if (node->getOp() == glslang::EOpArrayLength) {
1343 // Quite special; won't want to evaluate the operand.
1344
1345 // Normal .length() would have been constant folded by the front-end.
1346 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001347 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001348 assert(node->getOperand()->getType().isRuntimeSizedArray());
1349 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1350 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001351 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1352 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001353
1354 builder.clearAccessChain();
1355 builder.setAccessChainRValue(length);
1356
1357 return false;
1358 }
1359
John Kessenichfc51d282015-08-19 13:34:18 -06001360 // Start by evaluating the operand
1361
John Kessenich8c8505c2016-07-26 12:50:38 -06001362 // Does it need a swizzle inversion? If so, evaluation is inverted;
1363 // operate first on the swizzle base, then apply the swizzle.
1364 spv::Id invertedType = spv::NoType;
1365 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1366 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1367 invertedType = getInvertedSwizzleType(*node->getOperand());
1368
John Kessenich140f3df2015-06-26 16:58:36 -06001369 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001370 if (invertedType != spv::NoType)
1371 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1372 else
1373 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001374
Rex Xufc618912015-09-09 16:42:49 +08001375 spv::Id operand = spv::NoResult;
1376
1377 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1378 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001379 node->getOp() == glslang::EOpAtomicCounter ||
1380 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001381 operand = builder.accessChainGetLValue(); // Special case l-value operands
1382 else
John Kessenich32cfd492016-02-02 12:37:46 -07001383 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001384
John Kessenichf6640762016-08-01 19:44:00 -06001385 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001386 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001387
1388 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001389 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001390 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001391
1392 // if not, then possibly an operation
1393 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001394 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001395
1396 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001397 if (invertedType)
1398 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1399
John Kessenich140f3df2015-06-26 16:58:36 -06001400 builder.clearAccessChain();
1401 builder.setAccessChainRValue(result);
1402
1403 return false; // done with this node
1404 }
1405
1406 // it must be a special case, check...
1407 switch (node->getOp()) {
1408 case glslang::EOpPostIncrement:
1409 case glslang::EOpPostDecrement:
1410 case glslang::EOpPreIncrement:
1411 case glslang::EOpPreDecrement:
1412 {
1413 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001414 spv::Id one = 0;
1415 if (node->getBasicType() == glslang::EbtFloat)
1416 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001417 else if (node->getBasicType() == glslang::EbtDouble)
1418 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001419#ifdef AMD_EXTENSIONS
1420 else if (node->getBasicType() == glslang::EbtFloat16)
1421 one = builder.makeFloat16Constant(1.0F);
1422#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001423 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1424 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001425#ifdef AMD_EXTENSIONS
1426 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1427 one = builder.makeInt16Constant(1);
1428#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001429 else
1430 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001431 glslang::TOperator op;
1432 if (node->getOp() == glslang::EOpPreIncrement ||
1433 node->getOp() == glslang::EOpPostIncrement)
1434 op = glslang::EOpAdd;
1435 else
1436 op = glslang::EOpSub;
1437
John Kessenichf6640762016-08-01 19:44:00 -06001438 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001439 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001440 convertGlslangToSpvType(node->getType()), operand, one,
1441 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001442 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001443
1444 // The result of operation is always stored, but conditionally the
1445 // consumed result. The consumed result is always an r-value.
1446 builder.accessChainStore(result);
1447 builder.clearAccessChain();
1448 if (node->getOp() == glslang::EOpPreIncrement ||
1449 node->getOp() == glslang::EOpPreDecrement)
1450 builder.setAccessChainRValue(result);
1451 else
1452 builder.setAccessChainRValue(operand);
1453 }
1454
1455 return false;
1456
1457 case glslang::EOpEmitStreamVertex:
1458 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1459 return false;
1460 case glslang::EOpEndStreamPrimitive:
1461 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1462 return false;
1463
1464 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001465 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001466 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001467 }
John Kessenich140f3df2015-06-26 16:58:36 -06001468}
1469
1470bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1471{
qining27e04a02016-04-14 16:40:20 -04001472 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1473 if (node->getType().getQualifier().isSpecConstant())
1474 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1475
John Kessenichfc51d282015-08-19 13:34:18 -06001476 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001477 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1478 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001479
1480 // try texturing
1481 result = createImageTextureFunctionCall(node);
1482 if (result != spv::NoResult) {
1483 builder.clearAccessChain();
1484 builder.setAccessChainRValue(result);
1485
1486 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001487#ifdef AMD_EXTENSIONS
1488 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1489#else
John Kessenich56bab042015-09-16 10:54:31 -06001490 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001491#endif
Rex Xufc618912015-09-09 16:42:49 +08001492 // "imageStore" is a special case, which has no result
1493 return false;
1494 }
John Kessenichfc51d282015-08-19 13:34:18 -06001495
John Kessenich140f3df2015-06-26 16:58:36 -06001496 glslang::TOperator binOp = glslang::EOpNull;
1497 bool reduceComparison = true;
1498 bool isMatrix = false;
1499 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001500 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001501
1502 assert(node->getOp());
1503
John Kessenichf6640762016-08-01 19:44:00 -06001504 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001505
1506 switch (node->getOp()) {
1507 case glslang::EOpSequence:
1508 {
1509 if (preVisit)
1510 ++sequenceDepth;
1511 else
1512 --sequenceDepth;
1513
1514 if (sequenceDepth == 1) {
1515 // If this is the parent node of all the functions, we want to see them
1516 // early, so all call points have actual SPIR-V functions to reference.
1517 // In all cases, still let the traverser visit the children for us.
1518 makeFunctions(node->getAsAggregate()->getSequence());
1519
John Kessenich6fccb3c2016-09-19 16:01:41 -06001520 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001521 // anything else gets there, so visit out of order, doing them all now.
1522 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1523
John Kessenich6a60c2f2016-12-08 21:01:59 -07001524 // 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 -06001525 // so do them manually.
1526 visitFunctions(node->getAsAggregate()->getSequence());
1527
1528 return false;
1529 }
1530
1531 return true;
1532 }
1533 case glslang::EOpLinkerObjects:
1534 {
1535 if (visit == glslang::EvPreVisit)
1536 linkageOnly = true;
1537 else
1538 linkageOnly = false;
1539
1540 return true;
1541 }
1542 case glslang::EOpComma:
1543 {
1544 // processing from left to right naturally leaves the right-most
1545 // lying around in the access chain
1546 glslang::TIntermSequence& glslangOperands = node->getSequence();
1547 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1548 glslangOperands[i]->traverse(this);
1549
1550 return false;
1551 }
1552 case glslang::EOpFunction:
1553 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001554 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001555 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001556 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001557 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001558 } else {
1559 handleFunctionEntry(node);
1560 }
1561 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001562 if (inEntryPoint)
1563 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001564 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001565 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001566 }
1567
1568 return true;
1569 case glslang::EOpParameters:
1570 // Parameters will have been consumed by EOpFunction processing, but not
1571 // the body, so we still visited the function node's children, making this
1572 // child redundant.
1573 return false;
1574 case glslang::EOpFunctionCall:
1575 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001576 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001577 if (node->isUserDefined())
1578 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001579 // 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 -07001580 if (result) {
1581 builder.clearAccessChain();
1582 builder.setAccessChainRValue(result);
1583 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001584 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001585
1586 return false;
1587 }
1588 case glslang::EOpConstructMat2x2:
1589 case glslang::EOpConstructMat2x3:
1590 case glslang::EOpConstructMat2x4:
1591 case glslang::EOpConstructMat3x2:
1592 case glslang::EOpConstructMat3x3:
1593 case glslang::EOpConstructMat3x4:
1594 case glslang::EOpConstructMat4x2:
1595 case glslang::EOpConstructMat4x3:
1596 case glslang::EOpConstructMat4x4:
1597 case glslang::EOpConstructDMat2x2:
1598 case glslang::EOpConstructDMat2x3:
1599 case glslang::EOpConstructDMat2x4:
1600 case glslang::EOpConstructDMat3x2:
1601 case glslang::EOpConstructDMat3x3:
1602 case glslang::EOpConstructDMat3x4:
1603 case glslang::EOpConstructDMat4x2:
1604 case glslang::EOpConstructDMat4x3:
1605 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001606 case glslang::EOpConstructIMat2x2:
1607 case glslang::EOpConstructIMat2x3:
1608 case glslang::EOpConstructIMat2x4:
1609 case glslang::EOpConstructIMat3x2:
1610 case glslang::EOpConstructIMat3x3:
1611 case glslang::EOpConstructIMat3x4:
1612 case glslang::EOpConstructIMat4x2:
1613 case glslang::EOpConstructIMat4x3:
1614 case glslang::EOpConstructIMat4x4:
1615 case glslang::EOpConstructUMat2x2:
1616 case glslang::EOpConstructUMat2x3:
1617 case glslang::EOpConstructUMat2x4:
1618 case glslang::EOpConstructUMat3x2:
1619 case glslang::EOpConstructUMat3x3:
1620 case glslang::EOpConstructUMat3x4:
1621 case glslang::EOpConstructUMat4x2:
1622 case glslang::EOpConstructUMat4x3:
1623 case glslang::EOpConstructUMat4x4:
1624 case glslang::EOpConstructBMat2x2:
1625 case glslang::EOpConstructBMat2x3:
1626 case glslang::EOpConstructBMat2x4:
1627 case glslang::EOpConstructBMat3x2:
1628 case glslang::EOpConstructBMat3x3:
1629 case glslang::EOpConstructBMat3x4:
1630 case glslang::EOpConstructBMat4x2:
1631 case glslang::EOpConstructBMat4x3:
1632 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001633#ifdef AMD_EXTENSIONS
1634 case glslang::EOpConstructF16Mat2x2:
1635 case glslang::EOpConstructF16Mat2x3:
1636 case glslang::EOpConstructF16Mat2x4:
1637 case glslang::EOpConstructF16Mat3x2:
1638 case glslang::EOpConstructF16Mat3x3:
1639 case glslang::EOpConstructF16Mat3x4:
1640 case glslang::EOpConstructF16Mat4x2:
1641 case glslang::EOpConstructF16Mat4x3:
1642 case glslang::EOpConstructF16Mat4x4:
1643#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001644 isMatrix = true;
1645 // fall through
1646 case glslang::EOpConstructFloat:
1647 case glslang::EOpConstructVec2:
1648 case glslang::EOpConstructVec3:
1649 case glslang::EOpConstructVec4:
1650 case glslang::EOpConstructDouble:
1651 case glslang::EOpConstructDVec2:
1652 case glslang::EOpConstructDVec3:
1653 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001654#ifdef AMD_EXTENSIONS
1655 case glslang::EOpConstructFloat16:
1656 case glslang::EOpConstructF16Vec2:
1657 case glslang::EOpConstructF16Vec3:
1658 case glslang::EOpConstructF16Vec4:
1659#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001660 case glslang::EOpConstructBool:
1661 case glslang::EOpConstructBVec2:
1662 case glslang::EOpConstructBVec3:
1663 case glslang::EOpConstructBVec4:
1664 case glslang::EOpConstructInt:
1665 case glslang::EOpConstructIVec2:
1666 case glslang::EOpConstructIVec3:
1667 case glslang::EOpConstructIVec4:
1668 case glslang::EOpConstructUint:
1669 case glslang::EOpConstructUVec2:
1670 case glslang::EOpConstructUVec3:
1671 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001672 case glslang::EOpConstructInt64:
1673 case glslang::EOpConstructI64Vec2:
1674 case glslang::EOpConstructI64Vec3:
1675 case glslang::EOpConstructI64Vec4:
1676 case glslang::EOpConstructUint64:
1677 case glslang::EOpConstructU64Vec2:
1678 case glslang::EOpConstructU64Vec3:
1679 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001680#ifdef AMD_EXTENSIONS
1681 case glslang::EOpConstructInt16:
1682 case glslang::EOpConstructI16Vec2:
1683 case glslang::EOpConstructI16Vec3:
1684 case glslang::EOpConstructI16Vec4:
1685 case glslang::EOpConstructUint16:
1686 case glslang::EOpConstructU16Vec2:
1687 case glslang::EOpConstructU16Vec3:
1688 case glslang::EOpConstructU16Vec4:
1689#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001690 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001691 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001692 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001693 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001694 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001695 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001696 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001697 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001698 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001699 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001700 std::vector<spv::Id> constituents;
1701 for (int c = 0; c < (int)arguments.size(); ++c)
1702 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001703 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001704 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001705 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001706 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001707 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001708
1709 builder.clearAccessChain();
1710 builder.setAccessChainRValue(constructed);
1711
1712 return false;
1713 }
1714
1715 // These six are component-wise compares with component-wise results.
1716 // Forward on to createBinaryOperation(), requesting a vector result.
1717 case glslang::EOpLessThan:
1718 case glslang::EOpGreaterThan:
1719 case glslang::EOpLessThanEqual:
1720 case glslang::EOpGreaterThanEqual:
1721 case glslang::EOpVectorEqual:
1722 case glslang::EOpVectorNotEqual:
1723 {
1724 // Map the operation to a binary
1725 binOp = node->getOp();
1726 reduceComparison = false;
1727 switch (node->getOp()) {
1728 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1729 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1730 default: binOp = node->getOp(); break;
1731 }
1732
1733 break;
1734 }
1735 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001736 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001737 binOp = glslang::EOpMul;
1738 break;
1739 case glslang::EOpOuterProduct:
1740 // two vectors multiplied to make a matrix
1741 binOp = glslang::EOpOuterProduct;
1742 break;
1743 case glslang::EOpDot:
1744 {
qining25262b32016-05-06 17:25:16 -04001745 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001746 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001747 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001748 binOp = glslang::EOpMul;
1749 break;
1750 }
1751 case glslang::EOpMod:
1752 // when an aggregate, this is the floating-point mod built-in function,
1753 // which can be emitted by the one in createBinaryOperation()
1754 binOp = glslang::EOpMod;
1755 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001756 case glslang::EOpEmitVertex:
1757 case glslang::EOpEndPrimitive:
1758 case glslang::EOpBarrier:
1759 case glslang::EOpMemoryBarrier:
1760 case glslang::EOpMemoryBarrierAtomicCounter:
1761 case glslang::EOpMemoryBarrierBuffer:
1762 case glslang::EOpMemoryBarrierImage:
1763 case glslang::EOpMemoryBarrierShared:
1764 case glslang::EOpGroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07001765 case glslang::EOpDeviceMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001766 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07001767 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001768 case glslang::EOpWorkgroupMemoryBarrier:
1769 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001770 noReturnValue = true;
1771 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1772 break;
1773
John Kessenich426394d2015-07-23 10:22:48 -06001774 case glslang::EOpAtomicAdd:
1775 case glslang::EOpAtomicMin:
1776 case glslang::EOpAtomicMax:
1777 case glslang::EOpAtomicAnd:
1778 case glslang::EOpAtomicOr:
1779 case glslang::EOpAtomicXor:
1780 case glslang::EOpAtomicExchange:
1781 case glslang::EOpAtomicCompSwap:
1782 atomic = true;
1783 break;
1784
John Kessenich0d0c6d32017-07-23 16:08:26 -06001785 case glslang::EOpAtomicCounterAdd:
1786 case glslang::EOpAtomicCounterSubtract:
1787 case glslang::EOpAtomicCounterMin:
1788 case glslang::EOpAtomicCounterMax:
1789 case glslang::EOpAtomicCounterAnd:
1790 case glslang::EOpAtomicCounterOr:
1791 case glslang::EOpAtomicCounterXor:
1792 case glslang::EOpAtomicCounterExchange:
1793 case glslang::EOpAtomicCounterCompSwap:
1794 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1795 builder.addCapability(spv::CapabilityAtomicStorageOps);
1796 atomic = true;
1797 break;
1798
John Kessenich140f3df2015-06-26 16:58:36 -06001799 default:
1800 break;
1801 }
1802
1803 //
1804 // See if it maps to a regular operation.
1805 //
John Kessenich140f3df2015-06-26 16:58:36 -06001806 if (binOp != glslang::EOpNull) {
1807 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1808 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1809 assert(left && right);
1810
1811 builder.clearAccessChain();
1812 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001813 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001814
1815 builder.clearAccessChain();
1816 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001817 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001818
John Kesseniche485c7a2017-05-31 18:50:53 -06001819 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001820 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001821 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001822 left->getType().getBasicType(), reduceComparison);
1823
1824 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001825 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001826 builder.clearAccessChain();
1827 builder.setAccessChainRValue(result);
1828
1829 return false;
1830 }
1831
John Kessenich426394d2015-07-23 10:22:48 -06001832 //
1833 // Create the list of operands.
1834 //
John Kessenich140f3df2015-06-26 16:58:36 -06001835 glslang::TIntermSequence& glslangOperands = node->getSequence();
1836 std::vector<spv::Id> operands;
1837 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001838 // special case l-value operands; there are just a few
1839 bool lvalue = false;
1840 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001841 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001842 case glslang::EOpModf:
1843 if (arg == 1)
1844 lvalue = true;
1845 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001846 case glslang::EOpInterpolateAtSample:
1847 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001848#ifdef AMD_EXTENSIONS
1849 case glslang::EOpInterpolateAtVertex:
1850#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001851 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001852 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001853
1854 // Does it need a swizzle inversion? If so, evaluation is inverted;
1855 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001856 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001857 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1858 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1859 }
Rex Xu7a26c172015-12-08 17:12:09 +08001860 break;
Rex Xud4782c12015-09-06 16:30:11 +08001861 case glslang::EOpAtomicAdd:
1862 case glslang::EOpAtomicMin:
1863 case glslang::EOpAtomicMax:
1864 case glslang::EOpAtomicAnd:
1865 case glslang::EOpAtomicOr:
1866 case glslang::EOpAtomicXor:
1867 case glslang::EOpAtomicExchange:
1868 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001869 case glslang::EOpAtomicCounterAdd:
1870 case glslang::EOpAtomicCounterSubtract:
1871 case glslang::EOpAtomicCounterMin:
1872 case glslang::EOpAtomicCounterMax:
1873 case glslang::EOpAtomicCounterAnd:
1874 case glslang::EOpAtomicCounterOr:
1875 case glslang::EOpAtomicCounterXor:
1876 case glslang::EOpAtomicCounterExchange:
1877 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001878 if (arg == 0)
1879 lvalue = true;
1880 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001881 case glslang::EOpAddCarry:
1882 case glslang::EOpSubBorrow:
1883 if (arg == 2)
1884 lvalue = true;
1885 break;
1886 case glslang::EOpUMulExtended:
1887 case glslang::EOpIMulExtended:
1888 if (arg >= 2)
1889 lvalue = true;
1890 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001891 default:
1892 break;
1893 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001894 builder.clearAccessChain();
1895 if (invertedType != spv::NoType && arg == 0)
1896 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1897 else
1898 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001899 if (lvalue)
1900 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001901 else {
1902 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001903 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001904 }
John Kessenich140f3df2015-06-26 16:58:36 -06001905 }
John Kessenich426394d2015-07-23 10:22:48 -06001906
John Kesseniche485c7a2017-05-31 18:50:53 -06001907 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001908 if (atomic) {
1909 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001910 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001911 } else {
1912 // Pass through to generic operations.
1913 switch (glslangOperands.size()) {
1914 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001915 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001916 break;
1917 case 1:
qining25262b32016-05-06 17:25:16 -04001918 result = createUnaryOperation(
1919 node->getOp(), precision,
1920 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001921 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001922 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001923 break;
1924 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001925 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001926 break;
1927 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001928 if (invertedType)
1929 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001930 }
1931
1932 if (noReturnValue)
1933 return false;
1934
1935 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001936 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001937 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001938 } else {
1939 builder.clearAccessChain();
1940 builder.setAccessChainRValue(result);
1941 return false;
1942 }
1943}
1944
John Kessenich433e9ff2017-01-26 20:31:11 -07001945// This path handles both if-then-else and ?:
1946// The if-then-else has a node type of void, while
1947// ?: has either a void or a non-void node type
1948//
1949// Leaving the result, when not void:
1950// GLSL only has r-values as the result of a :?, but
1951// if we have an l-value, that can be more efficient if it will
1952// become the base of a complex r-value expression, because the
1953// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001954bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1955{
John Kessenich433e9ff2017-01-26 20:31:11 -07001956 // See if it simple and safe to generate OpSelect instead of using control flow.
1957 // Crucially, side effects must be avoided, and there are performance trade-offs.
1958 // Return true if good idea (and safe) for OpSelect, false otherwise.
1959 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001960 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1961 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001962 return false;
1963
1964 if (node->getTrueBlock() == nullptr ||
1965 node->getFalseBlock() == nullptr)
1966 return false;
1967
1968 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1969 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1970
1971 // return true if a single operand to ? : is okay for OpSelect
1972 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001973 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001974 };
1975
1976 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1977 operandOkay(node->getFalseBlock()->getAsTyped());
1978 };
1979
1980 // Emit OpSelect for this selection.
1981 const auto handleAsOpSelect = [&]() {
1982 node->getCondition()->traverse(this);
1983 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1984 node->getTrueBlock()->traverse(this);
1985 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1986 node->getFalseBlock()->traverse(this);
1987 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1988
John Kesseniche485c7a2017-05-31 18:50:53 -06001989 builder.setLine(node->getLoc().line);
1990
John Kesseniche434ad92017-03-30 10:09:28 -06001991 // smear condition to vector, if necessary (AST is always scalar)
1992 if (builder.isVector(trueValue))
1993 condition = builder.smearScalar(spv::NoPrecision, condition,
1994 builder.makeVectorType(builder.makeBoolType(),
1995 builder.getNumComponents(trueValue)));
1996
1997 spv::Id select = builder.createTriOp(spv::OpSelect,
1998 convertGlslangToSpvType(node->getType()), condition,
1999 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07002000 builder.clearAccessChain();
2001 builder.setAccessChainRValue(select);
2002 };
2003
2004 // Try for OpSelect
2005
2006 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002007 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2008 if (node->getType().getQualifier().isSpecConstant())
2009 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2010
John Kessenich433e9ff2017-01-26 20:31:11 -07002011 handleAsOpSelect();
2012 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002013 }
2014
Rex Xu57e65922017-07-04 23:23:40 +08002015 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07002016 // Don't handle results as temporaries, because there will be two names
2017 // and better to leave SSA to later passes.
2018 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
2019 ? spv::NoResult
2020 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2021
John Kessenich140f3df2015-06-26 16:58:36 -06002022 // emit the condition before doing anything with selection
2023 node->getCondition()->traverse(this);
2024
Rex Xu57e65922017-07-04 23:23:40 +08002025 // Selection control:
2026 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2027
John Kessenich140f3df2015-06-26 16:58:36 -06002028 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08002029 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06002030
John Kessenich433e9ff2017-01-26 20:31:11 -07002031 // emit the "then" statement
2032 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002033 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002034 if (result != spv::NoResult)
2035 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002036 }
2037
John Kessenich433e9ff2017-01-26 20:31:11 -07002038 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002039 ifBuilder.makeBeginElse();
2040 // emit the "else" statement
2041 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002042 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07002043 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002044 }
2045
John Kessenich433e9ff2017-01-26 20:31:11 -07002046 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06002047 ifBuilder.makeEndIf();
2048
John Kessenich433e9ff2017-01-26 20:31:11 -07002049 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06002050 // GLSL only has r-values as the result of a :?, but
2051 // if we have an l-value, that can be more efficient if it will
2052 // become the base of a complex r-value expression, because the
2053 // next layer copies r-values into memory to use the access-chain mechanism
2054 builder.clearAccessChain();
2055 builder.setAccessChainLValue(result);
2056 }
2057
2058 return false;
2059}
2060
2061bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2062{
2063 // emit and get the condition before doing anything with switch
2064 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002065 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002066
Rex Xu57e65922017-07-04 23:23:40 +08002067 // Selection control:
2068 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2069
John Kessenich140f3df2015-06-26 16:58:36 -06002070 // browse the children to sort out code segments
2071 int defaultSegment = -1;
2072 std::vector<TIntermNode*> codeSegments;
2073 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2074 std::vector<int> caseValues;
2075 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2076 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2077 TIntermNode* child = *c;
2078 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002079 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002080 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002081 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002082 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2083 } else
2084 codeSegments.push_back(child);
2085 }
2086
qining25262b32016-05-06 17:25:16 -04002087 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002088 // statements between the last case and the end of the switch statement
2089 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2090 (int)codeSegments.size() == defaultSegment)
2091 codeSegments.push_back(nullptr);
2092
2093 // make the switch statement
2094 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002095 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002096
2097 // emit all the code in the segments
2098 breakForLoop.push(false);
2099 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2100 builder.nextSwitchSegment(segmentBlocks, s);
2101 if (codeSegments[s])
2102 codeSegments[s]->traverse(this);
2103 else
2104 builder.addSwitchBreak();
2105 }
2106 breakForLoop.pop();
2107
2108 builder.endSwitch(segmentBlocks);
2109
2110 return false;
2111}
2112
2113void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2114{
2115 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002116 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002117
2118 builder.clearAccessChain();
2119 builder.setAccessChainRValue(constant);
2120}
2121
2122bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2123{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002124 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002125 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002126
2127 // Loop control:
2128 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2129
2130 // TODO: dependency length
2131
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002132 // Spec requires back edges to target header blocks, and every header block
2133 // must dominate its merge block. Make a header block first to ensure these
2134 // conditions are met. By definition, it will contain OpLoopMerge, followed
2135 // by a block-ending branch. But we don't want to put any other body/test
2136 // instructions in it, since the body/test may have arbitrary instructions,
2137 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002138 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002139 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002140 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002141 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002142 spv::Block& test = builder.makeNewBlock();
2143 builder.createBranch(&test);
2144
2145 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002146 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002147 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002148 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2149
2150 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002151 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002152 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002153 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002154 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002155 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002156
2157 builder.setBuildPoint(&blocks.continue_target);
2158 if (node->getTerminal())
2159 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002160 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002161 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002162 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002163 builder.createBranch(&blocks.body);
2164
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002165 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002166 builder.setBuildPoint(&blocks.body);
2167 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002168 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002169 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002170 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002171
2172 builder.setBuildPoint(&blocks.continue_target);
2173 if (node->getTerminal())
2174 node->getTerminal()->traverse(this);
2175 if (node->getTest()) {
2176 node->getTest()->traverse(this);
2177 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002178 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002179 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002180 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002181 // TODO: unless there was a break/return/discard instruction
2182 // somewhere in the body, this is an infinite loop, so we should
2183 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002184 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002185 }
John Kessenich140f3df2015-06-26 16:58:36 -06002186 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002187 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002188 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002189 return false;
2190}
2191
2192bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2193{
2194 if (node->getExpression())
2195 node->getExpression()->traverse(this);
2196
John Kesseniche485c7a2017-05-31 18:50:53 -06002197 builder.setLine(node->getLoc().line);
2198
John Kessenich140f3df2015-06-26 16:58:36 -06002199 switch (node->getFlowOp()) {
2200 case glslang::EOpKill:
2201 builder.makeDiscard();
2202 break;
2203 case glslang::EOpBreak:
2204 if (breakForLoop.top())
2205 builder.createLoopExit();
2206 else
2207 builder.addSwitchBreak();
2208 break;
2209 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002210 builder.createLoopContinue();
2211 break;
2212 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002213 if (node->getExpression()) {
2214 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2215 spv::Id returnId = accessChainLoad(glslangReturnType);
2216 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2217 builder.clearAccessChain();
2218 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2219 builder.setAccessChainLValue(copyId);
2220 multiTypeStore(glslangReturnType, returnId);
2221 returnId = builder.createLoad(copyId);
2222 }
2223 builder.makeReturn(false, returnId);
2224 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002225 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002226
2227 builder.clearAccessChain();
2228 break;
2229
2230 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002231 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002232 break;
2233 }
2234
2235 return false;
2236}
2237
2238spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2239{
qining25262b32016-05-06 17:25:16 -04002240 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002241 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002242 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002243 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002244 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002245 }
2246
2247 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002248 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002249 spv::Id spvType = convertGlslangToSpvType(node->getType());
2250
Rex Xuf89ad982017-04-07 23:22:33 +08002251#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002252 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2253 node->getType().containsBasicType(glslang::EbtInt16) ||
2254 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002255 if (contains16BitType) {
2256 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2257 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2258 builder.addCapability(spv::CapabilityStorageInputOutput16);
2259 } else if (storageClass == spv::StorageClassPushConstant) {
2260 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2261 builder.addCapability(spv::CapabilityStoragePushConstant16);
2262 } else if (storageClass == spv::StorageClassUniform) {
2263 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2264 builder.addCapability(spv::CapabilityStorageUniform16);
2265 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2266 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2267 }
2268 }
2269#endif
2270
John Kessenich140f3df2015-06-26 16:58:36 -06002271 const char* name = node->getName().c_str();
2272 if (glslang::IsAnonymous(name))
2273 name = "";
2274
2275 return builder.createVariable(storageClass, spvType, name);
2276}
2277
2278// Return type Id of the sampled type.
2279spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2280{
2281 switch (sampler.type) {
2282 case glslang::EbtFloat: return builder.makeFloatType(32);
2283 case glslang::EbtInt: return builder.makeIntType(32);
2284 case glslang::EbtUint: return builder.makeUintType(32);
2285 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002286 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002287 return builder.makeFloatType(32);
2288 }
2289}
2290
John Kessenich8c8505c2016-07-26 12:50:38 -06002291// If node is a swizzle operation, return the type that should be used if
2292// the swizzle base is first consumed by another operation, before the swizzle
2293// is applied.
2294spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2295{
John Kessenichecba76f2017-01-06 00:34:48 -07002296 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002297 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2298 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2299 else
2300 return spv::NoType;
2301}
2302
2303// When inverting a swizzle with a parent op, this function
2304// will apply the swizzle operation to a completed parent operation.
2305spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2306{
2307 std::vector<unsigned> swizzle;
2308 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2309 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2310}
2311
John Kessenich8c8505c2016-07-26 12:50:38 -06002312// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2313void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2314{
2315 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2316 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2317 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2318}
2319
John Kessenich3ac051e2015-12-20 11:29:16 -07002320// Convert from a glslang type to an SPV type, by calling into a
2321// recursive version of this function. This establishes the inherited
2322// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002323spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2324{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002325 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002326}
2327
2328// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002329// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002330// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002331spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002332{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002333 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002334
2335 switch (type.getBasicType()) {
2336 case glslang::EbtVoid:
2337 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002338 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002339 break;
2340 case glslang::EbtFloat:
2341 spvType = builder.makeFloatType(32);
2342 break;
2343 case glslang::EbtDouble:
2344 spvType = builder.makeFloatType(64);
2345 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002346#ifdef AMD_EXTENSIONS
2347 case glslang::EbtFloat16:
2348 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002349 spvType = builder.makeFloatType(16);
2350 break;
2351#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002352 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002353 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2354 // a 32-bit int where non-0 means true.
2355 if (explicitLayout != glslang::ElpNone)
2356 spvType = builder.makeUintType(32);
2357 else
2358 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002359 break;
2360 case glslang::EbtInt:
2361 spvType = builder.makeIntType(32);
2362 break;
2363 case glslang::EbtUint:
2364 spvType = builder.makeUintType(32);
2365 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002366 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002367 spvType = builder.makeIntType(64);
2368 break;
2369 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002370 spvType = builder.makeUintType(64);
2371 break;
Rex Xucabbb782017-03-24 13:41:14 +08002372#ifdef AMD_EXTENSIONS
2373 case glslang::EbtInt16:
2374 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2375 spvType = builder.makeIntType(16);
2376 break;
2377 case glslang::EbtUint16:
2378 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2379 spvType = builder.makeUintType(16);
2380 break;
2381#endif
John Kessenich426394d2015-07-23 10:22:48 -06002382 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002383 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002384 spvType = builder.makeUintType(32);
2385 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002386 case glslang::EbtSampler:
2387 {
2388 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002389 if (sampler.sampler) {
2390 // pure sampler
2391 spvType = builder.makeSamplerType();
2392 } else {
2393 // an image is present, make its type
2394 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2395 sampler.image ? 2 : 1, TranslateImageFormat(type));
2396 if (sampler.combined) {
2397 // already has both image and sampler, make the combined type
2398 spvType = builder.makeSampledImageType(spvType);
2399 }
John Kessenich55e7d112015-11-15 21:33:39 -07002400 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002401 }
John Kessenich140f3df2015-06-26 16:58:36 -06002402 break;
2403 case glslang::EbtStruct:
2404 case glslang::EbtBlock:
2405 {
2406 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002407 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002408
2409 // Try to share structs for different layouts, but not yet for other
2410 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002411 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002412 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002413 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002414 break;
2415
2416 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002417 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002418 memberRemapper[glslangMembers].resize(glslangMembers->size());
2419 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002420 }
2421 break;
2422 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002423 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002424 break;
2425 }
2426
2427 if (type.isMatrix())
2428 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2429 else {
2430 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2431 if (type.getVectorSize() > 1)
2432 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2433 }
2434
2435 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002436 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2437
John Kessenichc9a80832015-09-12 12:17:44 -06002438 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002439 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002440 // We need to decorate array strides for types needing explicit layout, except blocks.
2441 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002442 // Use a dummy glslang type for querying internal strides of
2443 // arrays of arrays, but using just a one-dimensional array.
2444 glslang::TType simpleArrayType(type, 0); // deference type of the array
2445 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2446 simpleArrayType.getArraySizes().dereference();
2447
2448 // Will compute the higher-order strides here, rather than making a whole
2449 // pile of types and doing repetitive recursion on their contents.
2450 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2451 }
John Kessenichf8842e52016-01-04 19:22:56 -07002452
2453 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002454 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002455 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002456 if (stride > 0)
2457 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002458 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002459 }
2460 } else {
2461 // single-dimensional array, and don't yet have stride
2462
John Kessenichf8842e52016-01-04 19:22:56 -07002463 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002464 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2465 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002466 }
John Kessenich31ed4832015-09-09 17:51:38 -06002467
John Kessenichc9a80832015-09-12 12:17:44 -06002468 // Do the outer dimension, which might not be known for a runtime-sized array
2469 if (type.isRuntimeSizedArray()) {
2470 spvType = builder.makeRuntimeArray(spvType);
2471 } else {
2472 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002473 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002474 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002475 if (stride > 0)
2476 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002477 }
2478
2479 return spvType;
2480}
2481
John Kessenich0e737842017-03-24 18:38:16 -06002482// TODO: this functionality should exist at a higher level, in creating the AST
2483//
2484// Identify interface members that don't have their required extension turned on.
2485//
2486bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2487{
2488 auto& extensions = glslangIntermediate->getRequestedExtensions();
2489
Rex Xubcf291a2017-03-29 23:01:36 +08002490 if (member.getFieldName() == "gl_ViewportMask" &&
2491 extensions.find("GL_NV_viewport_array2") == extensions.end())
2492 return true;
2493 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2494 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2495 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002496 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2497 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2498 return true;
2499 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2500 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2501 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002502 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2503 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2504 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002505
2506 return false;
2507};
2508
John Kessenich6090df02016-06-30 21:18:02 -06002509// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2510// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2511// Mutually recursive with convertGlslangToSpvType().
2512spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2513 const glslang::TTypeList* glslangMembers,
2514 glslang::TLayoutPacking explicitLayout,
2515 const glslang::TQualifier& qualifier)
2516{
2517 // Create a vector of struct types for SPIR-V to consume
2518 std::vector<spv::Id> spvMembers;
2519 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 -06002520 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2521 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2522 if (glslangMember.hiddenMember()) {
2523 ++memberDelta;
2524 if (type.getBasicType() == glslang::EbtBlock)
2525 memberRemapper[glslangMembers][i] = -1;
2526 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002527 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002528 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002529 if (filterMember(glslangMember))
2530 continue;
2531 }
John Kessenich6090df02016-06-30 21:18:02 -06002532 // modify just this child's view of the qualifier
2533 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2534 InheritQualifiers(memberQualifier, qualifier);
2535
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002536 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002537 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002538 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002539
2540 // recurse
2541 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2542 }
2543 }
2544
2545 // Make the SPIR-V type
2546 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002547 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002548 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2549
2550 // Decorate it
2551 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2552
2553 return spvType;
2554}
2555
2556void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2557 const glslang::TTypeList* glslangMembers,
2558 glslang::TLayoutPacking explicitLayout,
2559 const glslang::TQualifier& qualifier,
2560 spv::Id spvType)
2561{
2562 // Name and decorate the non-hidden members
2563 int offset = -1;
2564 int locationOffset = 0; // for use within the members of this struct
2565 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2566 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2567 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002568 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002569 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002570 if (filterMember(glslangMember))
2571 continue;
2572 }
John Kessenich6090df02016-06-30 21:18:02 -06002573
2574 // modify just this child's view of the qualifier
2575 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2576 InheritQualifiers(memberQualifier, qualifier);
2577
2578 // using -1 above to indicate a hidden member
2579 if (member >= 0) {
2580 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2581 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2582 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2583 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002584 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2585 type.getQualifier().storage == glslang::EvqVaryingOut) {
2586 if (type.getBasicType() == glslang::EbtBlock ||
2587 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002588 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2589 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2590 }
2591 }
2592 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2593
Rex Xu286ca432017-07-27 14:33:16 +08002594 if (type.getBasicType() == glslang::EbtBlock &&
2595 qualifier.storage == glslang::EvqBuffer) {
2596 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002597 std::vector<spv::Decoration> memory;
2598 TranslateMemoryDecoration(memberQualifier, memory);
2599 for (unsigned int i = 0; i < memory.size(); ++i)
2600 addMemberDecoration(spvType, member, memory[i]);
2601 }
2602
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002603 // Location assignment was already completed correctly by the front end,
2604 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002605 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002606 // ill-specified and decisions have been made to not allow this.
2607 if (! type.isArray() && memberQualifier.hasLocation())
2608 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002609
John Kessenich2f47bc92016-06-30 21:47:35 -06002610 if (qualifier.hasLocation()) // track for upcoming inheritance
2611 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2612
John Kessenich6090df02016-06-30 21:18:02 -06002613 // component, XFB, others
2614 if (glslangMember.getQualifier().hasComponent())
2615 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2616 if (glslangMember.getQualifier().hasXfbOffset())
2617 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2618 else if (explicitLayout != glslang::ElpNone) {
2619 // figure out what to do with offset, which is accumulating
2620 int nextOffset;
2621 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2622 if (offset >= 0)
2623 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2624 offset = nextOffset;
2625 }
2626
2627 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2628 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2629
2630 // built-in variable decorations
2631 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002632 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002633 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002634
2635#ifdef NV_EXTENSIONS
2636 if (builtIn == spv::BuiltInLayer) {
2637 // SPV_NV_viewport_array2 extension
2638 if (glslangMember.getQualifier().layoutViewportRelative){
2639 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2640 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2641 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2642 }
2643 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2644 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2645 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2646 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2647 }
2648 }
chaocdf3956c2017-02-14 14:52:34 -08002649 if (glslangMember.getQualifier().layoutPassthrough) {
2650 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2651 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2652 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2653 }
chaoc771d89f2017-01-13 01:10:53 -08002654#endif
John Kessenich6090df02016-06-30 21:18:02 -06002655 }
2656 }
2657
2658 // Decorate the structure
2659 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002660 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002661 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2662 builder.addCapability(spv::CapabilityGeometryStreams);
2663 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2664 }
John Kessenich6090df02016-06-30 21:18:02 -06002665}
2666
John Kessenich6c292d32016-02-15 20:58:50 -07002667// Turn the expression forming the array size into an id.
2668// This is not quite trivial, because of specialization constants.
2669// Sometimes, a raw constant is turned into an Id, and sometimes
2670// a specialization constant expression is.
2671spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2672{
2673 // First, see if this is sized with a node, meaning a specialization constant:
2674 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2675 if (specNode != nullptr) {
2676 builder.clearAccessChain();
2677 specNode->traverse(this);
2678 return accessChainLoad(specNode->getAsTyped()->getType());
2679 }
qining25262b32016-05-06 17:25:16 -04002680
John Kessenich6c292d32016-02-15 20:58:50 -07002681 // Otherwise, need a compile-time (front end) size, get it:
2682 int size = arraySizes.getDimSize(dim);
2683 assert(size > 0);
2684 return builder.makeUintConstant(size);
2685}
2686
John Kessenich103bef92016-02-08 21:38:15 -07002687// Wrap the builder's accessChainLoad to:
2688// - localize handling of RelaxedPrecision
2689// - use the SPIR-V inferred type instead of another conversion of the glslang type
2690// (avoids unnecessary work and possible type punning for structures)
2691// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002692spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2693{
John Kessenich103bef92016-02-08 21:38:15 -07002694 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2695 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2696
2697 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002698 if (type.getBasicType() == glslang::EbtBool) {
2699 if (builder.isScalarType(nominalTypeId)) {
2700 // Conversion for bool
2701 spv::Id boolType = builder.makeBoolType();
2702 if (nominalTypeId != boolType)
2703 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2704 } else if (builder.isVectorType(nominalTypeId)) {
2705 // Conversion for bvec
2706 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2707 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2708 if (nominalTypeId != bvecType)
2709 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2710 }
2711 }
John Kessenich103bef92016-02-08 21:38:15 -07002712
2713 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002714}
2715
Rex Xu27253232016-02-23 17:51:09 +08002716// Wrap the builder's accessChainStore to:
2717// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002718//
2719// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002720void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2721{
2722 // Need to convert to abstract types when necessary
2723 if (type.getBasicType() == glslang::EbtBool) {
2724 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2725
2726 if (builder.isScalarType(nominalTypeId)) {
2727 // Conversion for bool
2728 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002729 if (nominalTypeId != boolType) {
2730 // keep these outside arguments, for determinant order-of-evaluation
2731 spv::Id one = builder.makeUintConstant(1);
2732 spv::Id zero = builder.makeUintConstant(0);
2733 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2734 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002735 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002736 } else if (builder.isVectorType(nominalTypeId)) {
2737 // Conversion for bvec
2738 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2739 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002740 if (nominalTypeId != bvecType) {
2741 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002742 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2743 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2744 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002745 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002746 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2747 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002748 }
2749 }
2750
2751 builder.accessChainStore(rvalue);
2752}
2753
John Kessenich4bf71552016-09-02 11:20:21 -06002754// For storing when types match at the glslang level, but not might match at the
2755// SPIR-V level.
2756//
2757// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002758// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002759// as in a member-decorated way.
2760//
2761// NOTE: This function can handle any store request; if it's not special it
2762// simplifies to a simple OpStore.
2763//
2764// Implicitly uses the existing builder.accessChain as the storage target.
2765void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2766{
John Kessenichb3e24e42016-09-11 12:33:43 -06002767 // we only do the complex path here if it's an aggregate
2768 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002769 accessChainStore(type, rValue);
2770 return;
2771 }
2772
John Kessenichb3e24e42016-09-11 12:33:43 -06002773 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002774 spv::Id rType = builder.getTypeId(rValue);
2775 spv::Id lValue = builder.accessChainGetLValue();
2776 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2777 if (lType == rType) {
2778 accessChainStore(type, rValue);
2779 return;
2780 }
2781
John Kessenichb3e24e42016-09-11 12:33:43 -06002782 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002783 // where the two types were the same type in GLSL. This requires member
2784 // by member copy, recursively.
2785
John Kessenichb3e24e42016-09-11 12:33:43 -06002786 // If an array, copy element by element.
2787 if (type.isArray()) {
2788 glslang::TType glslangElementType(type, 0);
2789 spv::Id elementRType = builder.getContainedTypeId(rType);
2790 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2791 // get the source member
2792 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002793
John Kessenichb3e24e42016-09-11 12:33:43 -06002794 // set up the target storage
2795 builder.clearAccessChain();
2796 builder.setAccessChainLValue(lValue);
2797 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002798
John Kessenichb3e24e42016-09-11 12:33:43 -06002799 // store the member
2800 multiTypeStore(glslangElementType, elementRValue);
2801 }
2802 } else {
2803 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002804
John Kessenichb3e24e42016-09-11 12:33:43 -06002805 // loop over structure members
2806 const glslang::TTypeList& members = *type.getStruct();
2807 for (int m = 0; m < (int)members.size(); ++m) {
2808 const glslang::TType& glslangMemberType = *members[m].type;
2809
2810 // get the source member
2811 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2812 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2813
2814 // set up the target storage
2815 builder.clearAccessChain();
2816 builder.setAccessChainLValue(lValue);
2817 builder.accessChainPush(builder.makeIntConstant(m));
2818
2819 // store the member
2820 multiTypeStore(glslangMemberType, memberRValue);
2821 }
John Kessenich4bf71552016-09-02 11:20:21 -06002822 }
2823}
2824
John Kessenichf85e8062015-12-19 13:57:10 -07002825// Decide whether or not this type should be
2826// decorated with offsets and strides, and if so
2827// whether std140 or std430 rules should be applied.
2828glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002829{
John Kessenichf85e8062015-12-19 13:57:10 -07002830 // has to be a block
2831 if (type.getBasicType() != glslang::EbtBlock)
2832 return glslang::ElpNone;
2833
2834 // has to be a uniform or buffer block
2835 if (type.getQualifier().storage != glslang::EvqUniform &&
2836 type.getQualifier().storage != glslang::EvqBuffer)
2837 return glslang::ElpNone;
2838
2839 // return the layout to use
2840 switch (type.getQualifier().layoutPacking) {
2841 case glslang::ElpStd140:
2842 case glslang::ElpStd430:
2843 return type.getQualifier().layoutPacking;
2844 default:
2845 return glslang::ElpNone;
2846 }
John Kessenich31ed4832015-09-09 17:51:38 -06002847}
2848
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002849// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002850int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002851{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002852 int size;
John Kessenich49987892015-12-29 17:11:44 -07002853 int stride;
2854 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002855
2856 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002857}
2858
John Kessenich49987892015-12-29 17:11:44 -07002859// 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 -07002860// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002861int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002862{
John Kessenich49987892015-12-29 17:11:44 -07002863 glslang::TType elementType;
2864 elementType.shallowCopy(matrixType);
2865 elementType.clearArraySizes();
2866
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002867 int size;
John Kessenich49987892015-12-29 17:11:44 -07002868 int stride;
2869 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2870
2871 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002872}
2873
John Kessenich5e4b1242015-08-06 22:53:06 -06002874// Given a member type of a struct, realign the current offset for it, and compute
2875// the next (not yet aligned) offset for the next member, which will get aligned
2876// on the next call.
2877// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2878// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2879// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002880void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002881 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002882{
2883 // this will get a positive value when deemed necessary
2884 nextOffset = -1;
2885
John Kessenich5e4b1242015-08-06 22:53:06 -06002886 // override anything in currentOffset with user-set offset
2887 if (memberType.getQualifier().hasOffset())
2888 currentOffset = memberType.getQualifier().layoutOffset;
2889
2890 // It could be that current linker usage in glslang updated all the layoutOffset,
2891 // in which case the following code does not matter. But, that's not quite right
2892 // once cross-compilation unit GLSL validation is done, as the original user
2893 // settings are needed in layoutOffset, and then the following will come into play.
2894
John Kessenichf85e8062015-12-19 13:57:10 -07002895 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002896 if (! memberType.getQualifier().hasOffset())
2897 currentOffset = -1;
2898
2899 return;
2900 }
2901
John Kessenichf85e8062015-12-19 13:57:10 -07002902 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002903 if (currentOffset < 0)
2904 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002905
John Kessenich5e4b1242015-08-06 22:53:06 -06002906 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2907 // but possibly not yet correctly aligned.
2908
2909 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002910 int dummyStride;
2911 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002912
2913 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002914 // TODO: make this consistent in early phases of code:
2915 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2916 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2917 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002918 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002919 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002920 int dummySize;
2921 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2922 if (componentAlignment <= 4)
2923 memberAlignment = componentAlignment;
2924 }
2925
2926 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002927 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002928
2929 // Bump up to vec4 if there is a bad straddle
2930 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2931 glslang::RoundToPow2(currentOffset, 16);
2932
John Kessenich5e4b1242015-08-06 22:53:06 -06002933 nextOffset = currentOffset + memberSize;
2934}
2935
David Netoa901ffe2016-06-08 14:11:40 +01002936void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002937{
David Netoa901ffe2016-06-08 14:11:40 +01002938 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2939 switch (glslangBuiltIn)
2940 {
2941 case glslang::EbvClipDistance:
2942 case glslang::EbvCullDistance:
2943 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002944#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08002945 case glslang::EbvViewportMaskNV:
2946 case glslang::EbvSecondaryPositionNV:
2947 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002948 case glslang::EbvPositionPerViewNV:
2949 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002950#endif
David Netoa901ffe2016-06-08 14:11:40 +01002951 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2952 // Alternately, we could just call this for any glslang built-in, since the
2953 // capability already guards against duplicates.
2954 TranslateBuiltInDecoration(glslangBuiltIn, false);
2955 break;
2956 default:
2957 // Capabilities were already generated when the struct was declared.
2958 break;
2959 }
John Kessenichebb50532016-05-16 19:22:05 -06002960}
2961
John Kessenich6fccb3c2016-09-19 16:01:41 -06002962bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002963{
John Kessenicheee9d532016-09-19 18:09:30 -06002964 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002965}
2966
John Kessenichd41993d2017-09-10 15:21:05 -06002967// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07002968// Assumes called after originalParam(), which filters out block/buffer/opaque-based
2969// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd41993d2017-09-10 15:21:05 -06002970bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier)
2971{
John Kessenich6a14f782017-12-04 02:48:10 -07002972 assert(qualifier == glslang::EvqIn ||
2973 qualifier == glslang::EvqOut ||
2974 qualifier == glslang::EvqInOut ||
2975 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06002976 return qualifier != glslang::EvqConstReadOnly;
2977}
2978
2979// Is parameter pass-by-original?
2980bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
2981 bool implicitThisParam)
2982{
2983 if (implicitThisParam) // implicit this
2984 return true;
2985 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07002986 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06002987 return paramType.containsOpaque() || // sampler, etc.
2988 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
2989}
2990
John Kessenich140f3df2015-06-26 16:58:36 -06002991// Make all the functions, skeletally, without actually visiting their bodies.
2992void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2993{
John Kessenichfad62972017-07-18 02:35:46 -06002994 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
2995 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
2996 if (paramPrecision != spv::NoPrecision)
2997 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06002998 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06002999 };
3000
John Kessenich140f3df2015-06-26 16:58:36 -06003001 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3002 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003003 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003004 continue;
3005
3006 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003007 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003008 //
qining25262b32016-05-06 17:25:16 -04003009 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003010 // function. What it is an address of varies:
3011 //
John Kessenich4bf71552016-09-02 11:20:21 -06003012 // - "in" parameters not marked as "const" can be written to without modifying the calling
3013 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003014 //
3015 // - "const in" parameters can just be the r-value, as no writes need occur.
3016 //
John Kessenich4bf71552016-09-02 11:20:21 -06003017 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3018 // 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 -06003019
3020 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003021 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003022 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3023
John Kessenichfad62972017-07-18 02:35:46 -06003024 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3025 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003026
John Kessenichfad62972017-07-18 02:35:46 -06003027 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003028 for (int p = 0; p < (int)parameters.size(); ++p) {
3029 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3030 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003031 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003032 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003033 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003034 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3035 else
John Kessenich4bf71552016-09-02 11:20:21 -06003036 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003037 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003038 paramTypes.push_back(typeId);
3039 }
3040
3041 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003042 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3043 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003044 glslFunction->getName().c_str(), paramTypes,
3045 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003046 if (implicitThis)
3047 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003048
3049 // Track function to emit/call later
3050 functionMap[glslFunction->getName().c_str()] = function;
3051
3052 // Set the parameter id's
3053 for (int p = 0; p < (int)parameters.size(); ++p) {
3054 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3055 // give a name too
3056 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3057 }
3058 }
3059}
3060
3061// Process all the initializers, while skipping the functions and link objects
3062void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3063{
3064 builder.setBuildPoint(shaderEntry->getLastBlock());
3065 for (int i = 0; i < (int)initializers.size(); ++i) {
3066 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3067 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3068
3069 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003070 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003071 initializer->traverse(this);
3072 }
3073 }
3074}
3075
3076// Process all the functions, while skipping initializers.
3077void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3078{
3079 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3080 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003081 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003082 node->traverse(this);
3083 }
3084}
3085
3086void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3087{
qining25262b32016-05-06 17:25:16 -04003088 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003089 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003090 currentFunction = functionMap[node->getName().c_str()];
3091 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003092 builder.setBuildPoint(functionBlock);
3093}
3094
Rex Xu04db3f52015-09-16 11:44:02 +08003095void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003096{
Rex Xufc618912015-09-09 16:42:49 +08003097 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003098
3099 glslang::TSampler sampler = {};
3100 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003101 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003102 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3103 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3104 }
3105
John Kessenich140f3df2015-06-26 16:58:36 -06003106 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3107 builder.clearAccessChain();
3108 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003109
3110 // Special case l-value operands
3111 bool lvalue = false;
3112 switch (node.getOp()) {
3113 case glslang::EOpImageAtomicAdd:
3114 case glslang::EOpImageAtomicMin:
3115 case glslang::EOpImageAtomicMax:
3116 case glslang::EOpImageAtomicAnd:
3117 case glslang::EOpImageAtomicOr:
3118 case glslang::EOpImageAtomicXor:
3119 case glslang::EOpImageAtomicExchange:
3120 case glslang::EOpImageAtomicCompSwap:
3121 if (i == 0)
3122 lvalue = true;
3123 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003124 case glslang::EOpSparseImageLoad:
3125 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3126 lvalue = true;
3127 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003128 case glslang::EOpSparseTexture:
3129 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3130 lvalue = true;
3131 break;
3132 case glslang::EOpSparseTextureClamp:
3133 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3134 lvalue = true;
3135 break;
3136 case glslang::EOpSparseTextureLod:
3137 case glslang::EOpSparseTextureOffset:
3138 if (i == 3)
3139 lvalue = true;
3140 break;
3141 case glslang::EOpSparseTextureFetch:
3142 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3143 lvalue = true;
3144 break;
3145 case glslang::EOpSparseTextureFetchOffset:
3146 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3147 lvalue = true;
3148 break;
3149 case glslang::EOpSparseTextureLodOffset:
3150 case glslang::EOpSparseTextureGrad:
3151 case glslang::EOpSparseTextureOffsetClamp:
3152 if (i == 4)
3153 lvalue = true;
3154 break;
3155 case glslang::EOpSparseTextureGradOffset:
3156 case glslang::EOpSparseTextureGradClamp:
3157 if (i == 5)
3158 lvalue = true;
3159 break;
3160 case glslang::EOpSparseTextureGradOffsetClamp:
3161 if (i == 6)
3162 lvalue = true;
3163 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003164 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003165 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3166 lvalue = true;
3167 break;
3168 case glslang::EOpSparseTextureGatherOffset:
3169 case glslang::EOpSparseTextureGatherOffsets:
3170 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3171 lvalue = true;
3172 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003173#ifdef AMD_EXTENSIONS
3174 case glslang::EOpSparseTextureGatherLod:
3175 if (i == 3)
3176 lvalue = true;
3177 break;
3178 case glslang::EOpSparseTextureGatherLodOffset:
3179 case glslang::EOpSparseTextureGatherLodOffsets:
3180 if (i == 4)
3181 lvalue = true;
3182 break;
Rex Xu129799a2017-07-05 17:23:28 +08003183 case glslang::EOpSparseImageLoadLod:
3184 if (i == 3)
3185 lvalue = true;
3186 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003187#endif
Rex Xufc618912015-09-09 16:42:49 +08003188 default:
3189 break;
3190 }
3191
Rex Xu6b86d492015-09-16 17:48:22 +08003192 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003193 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003194 else
John Kessenich32cfd492016-02-02 12:37:46 -07003195 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003196 }
3197}
3198
John Kessenichfc51d282015-08-19 13:34:18 -06003199void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003200{
John Kessenichfc51d282015-08-19 13:34:18 -06003201 builder.clearAccessChain();
3202 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003203 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003204}
John Kessenich140f3df2015-06-26 16:58:36 -06003205
John Kessenichfc51d282015-08-19 13:34:18 -06003206spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3207{
John Kesseniche485c7a2017-05-31 18:50:53 -06003208 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003209 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003210
3211 builder.setLine(node->getLoc().line);
3212
John Kessenich8c8505c2016-07-26 12:50:38 -06003213 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003214
John Kessenichfc51d282015-08-19 13:34:18 -06003215 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003216 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3217 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3218 std::vector<spv::Id> arguments;
3219 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003220 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003221 else
3222 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003223 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003224
3225 spv::Builder::TextureParameters params = { };
3226 params.sampler = arguments[0];
3227
Rex Xu04db3f52015-09-16 11:44:02 +08003228 glslang::TCrackedTextureOp cracked;
3229 node->crackTexture(sampler, cracked);
3230
amhagan05506bb2017-06-13 16:53:02 -04003231 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003232
John Kessenichfc51d282015-08-19 13:34:18 -06003233 // Check for queries
3234 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003235 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3236 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003237 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003238
John Kessenichfc51d282015-08-19 13:34:18 -06003239 switch (node->getOp()) {
3240 case glslang::EOpImageQuerySize:
3241 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003242 if (arguments.size() > 1) {
3243 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003244 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003245 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003246 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003247 case glslang::EOpImageQuerySamples:
3248 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003249 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003250 case glslang::EOpTextureQueryLod:
3251 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003252 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003253 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003254 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003255 case glslang::EOpSparseTexelsResident:
3256 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003257 default:
3258 assert(0);
3259 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003260 }
John Kessenich140f3df2015-06-26 16:58:36 -06003261 }
3262
Rex Xufc618912015-09-09 16:42:49 +08003263 // Check for image functions other than queries
3264 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003265 std::vector<spv::Id> operands;
3266 auto opIt = arguments.begin();
3267 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003268
3269 // Handle subpass operations
3270 // TODO: GLSL should change to have the "MS" only on the type rather than the
3271 // built-in function.
3272 if (cracked.subpass) {
3273 // add on the (0,0) coordinate
3274 spv::Id zero = builder.makeIntConstant(0);
3275 std::vector<spv::Id> comps;
3276 comps.push_back(zero);
3277 comps.push_back(zero);
3278 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3279 if (sampler.ms) {
3280 operands.push_back(spv::ImageOperandsSampleMask);
3281 operands.push_back(*(opIt++));
3282 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003283 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3284 builder.setPrecision(result, precision);
3285 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003286 }
3287
John Kessenich56bab042015-09-16 10:54:31 -06003288 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003289#ifdef AMD_EXTENSIONS
3290 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3291#else
John Kessenich56bab042015-09-16 10:54:31 -06003292 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003293#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003294 if (sampler.ms) {
3295 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003296 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003297#ifdef AMD_EXTENSIONS
3298 } else if (cracked.lod) {
3299 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3300 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3301
3302 operands.push_back(spv::ImageOperandsLodMask);
3303 operands.push_back(*opIt);
3304#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003305 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003306 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3307 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003308
3309 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3310 builder.setPrecision(result, precision);
3311 return result;
Rex Xu129799a2017-07-05 17:23:28 +08003312#ifdef AMD_EXTENSIONS
3313 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3314#else
John Kessenich56bab042015-09-16 10:54:31 -06003315 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003316#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003317 if (sampler.ms) {
3318 operands.push_back(*(opIt + 1));
3319 operands.push_back(spv::ImageOperandsSampleMask);
3320 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003321#ifdef AMD_EXTENSIONS
3322 } else if (cracked.lod) {
3323 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3324 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3325
3326 operands.push_back(*(opIt + 1));
3327 operands.push_back(spv::ImageOperandsLodMask);
3328 operands.push_back(*opIt);
3329#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003330 } else
3331 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003332 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003333 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3334 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003335 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003336#ifdef AMD_EXTENSIONS
3337 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3338#else
Rex Xu5eafa472016-02-19 22:24:03 +08003339 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003340#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003341 builder.addCapability(spv::CapabilitySparseResidency);
3342 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3343 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3344
3345 if (sampler.ms) {
3346 operands.push_back(spv::ImageOperandsSampleMask);
3347 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003348#ifdef AMD_EXTENSIONS
3349 } else if (cracked.lod) {
3350 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3351 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3352
3353 operands.push_back(spv::ImageOperandsLodMask);
3354 operands.push_back(*opIt++);
3355#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003356 }
3357
3358 // Create the return type that was a special structure
3359 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003360 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003361 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3362 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3363
3364 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3365
3366 // Decode the return type
3367 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3368 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003369 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003370 // Process image atomic operations
3371
3372 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3373 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003374 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003375
John Kessenich8c8505c2016-07-26 12:50:38 -06003376 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003377 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003378
3379 std::vector<spv::Id> operands;
3380 operands.push_back(pointer);
3381 for (; opIt != arguments.end(); ++opIt)
3382 operands.push_back(*opIt);
3383
John Kessenich8c8505c2016-07-26 12:50:38 -06003384 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003385 }
3386 }
3387
amhagan05506bb2017-06-13 16:53:02 -04003388#ifdef AMD_EXTENSIONS
3389 // Check for fragment mask functions other than queries
3390 if (cracked.fragMask) {
3391 assert(sampler.ms);
3392
3393 auto opIt = arguments.begin();
3394 std::vector<spv::Id> operands;
3395
3396 // Extract the image if necessary
3397 if (builder.isSampledImage(params.sampler))
3398 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3399
3400 operands.push_back(params.sampler);
3401 ++opIt;
3402
3403 if (sampler.isSubpass()) {
3404 // add on the (0,0) coordinate
3405 spv::Id zero = builder.makeIntConstant(0);
3406 std::vector<spv::Id> comps;
3407 comps.push_back(zero);
3408 comps.push_back(zero);
3409 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3410 }
3411
3412 for (; opIt != arguments.end(); ++opIt)
3413 operands.push_back(*opIt);
3414
3415 spv::Op fragMaskOp = spv::OpNop;
3416 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3417 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3418 else if (node->getOp() == glslang::EOpFragmentFetch)
3419 fragMaskOp = spv::OpFragmentFetchAMD;
3420
3421 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3422 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3423 return builder.createOp(fragMaskOp, resultType(), operands);
3424 }
3425#endif
3426
Rex Xufc618912015-09-09 16:42:49 +08003427 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003428 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003429 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3430
John Kessenichfc51d282015-08-19 13:34:18 -06003431 // check for bias argument
3432 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003433#ifdef AMD_EXTENSIONS
3434 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3435#else
Rex Xu71519fe2015-11-11 15:35:47 +08003436 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003437#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003438 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003439#ifdef AMD_EXTENSIONS
3440 if (cracked.gather)
3441 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3442#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003443 if (cracked.offset)
3444 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003445#ifdef AMD_EXTENSIONS
3446 else if (cracked.offsets)
3447 ++nonBiasArgCount;
3448#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003449 if (cracked.grad)
3450 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003451 if (cracked.lodClamp)
3452 ++nonBiasArgCount;
3453 if (sparse)
3454 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003455
3456 if ((int)arguments.size() > nonBiasArgCount)
3457 bias = true;
3458 }
3459
John Kessenicha5c33d62016-06-02 23:45:21 -06003460 // See if the sampler param should really be just the SPV image part
3461 if (cracked.fetch) {
3462 // a fetch needs to have the image extracted first
3463 if (builder.isSampledImage(params.sampler))
3464 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3465 }
3466
Rex Xu225e0fc2016-11-17 17:47:59 +08003467#ifdef AMD_EXTENSIONS
3468 if (cracked.gather) {
3469 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3470 if (bias || cracked.lod ||
3471 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3472 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003473 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003474 }
3475 }
3476#endif
3477
John Kessenichfc51d282015-08-19 13:34:18 -06003478 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003479
John Kessenichfc51d282015-08-19 13:34:18 -06003480 params.coords = arguments[1];
3481 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003482 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003483
3484 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003485 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003486 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003487 ++extraArgs;
3488 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003489 params.Dref = arguments[2];
3490 ++extraArgs;
3491 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003492 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003493 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003494 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003495 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003496 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003497 dRefComp = builder.getNumComponents(params.coords) - 1;
3498 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003499 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3500 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003501
3502 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003503 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003504 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003505 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003506 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3507 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3508 noImplicitLod = true;
3509 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003510
3511 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003512 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003513 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003514 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003515 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003516
3517 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003518 if (cracked.grad) {
3519 params.gradX = arguments[2 + extraArgs];
3520 params.gradY = arguments[3 + extraArgs];
3521 extraArgs += 2;
3522 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003523
3524 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003525 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003526 params.offset = arguments[2 + extraArgs];
3527 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003528 } else if (cracked.offsets) {
3529 params.offsets = arguments[2 + extraArgs];
3530 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003531 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003532
3533 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003534 if (cracked.lodClamp) {
3535 params.lodClamp = arguments[2 + extraArgs];
3536 ++extraArgs;
3537 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003538
3539 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003540 if (sparse) {
3541 params.texelOut = arguments[2 + extraArgs];
3542 ++extraArgs;
3543 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003544
John Kessenich76d4dfc2016-06-16 12:43:23 -06003545 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003546 if (cracked.gather && ! sampler.shadow) {
3547 // default component is 0, if missing, otherwise an argument
3548 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003549 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003550 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003551 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003552 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003553 }
3554
3555 // bias
3556 if (bias) {
3557 params.bias = arguments[2 + extraArgs];
3558 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003559 }
John Kessenichfc51d282015-08-19 13:34:18 -06003560
John Kessenich65336482016-06-16 14:06:26 -06003561 // projective component (might not to move)
3562 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3563 // are divided by the last component of P."
3564 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3565 // unused components will appear after all used components."
3566 if (cracked.proj) {
3567 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3568 int projTargetComp;
3569 switch (sampler.dim) {
3570 case glslang::Esd1D: projTargetComp = 1; break;
3571 case glslang::Esd2D: projTargetComp = 2; break;
3572 case glslang::EsdRect: projTargetComp = 2; break;
3573 default: projTargetComp = projSourceComp; break;
3574 }
3575 // copy the projective coordinate if we have to
3576 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003577 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003578 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3579 projSourceComp);
3580 params.coords = builder.createCompositeInsert(projComp, params.coords,
3581 builder.getTypeId(params.coords), projTargetComp);
3582 }
3583 }
3584
John Kessenich8c8505c2016-07-26 12:50:38 -06003585 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003586}
3587
3588spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3589{
3590 // Grab the function's pointer from the previously created function
3591 spv::Function* function = functionMap[node->getName().c_str()];
3592 if (! function)
3593 return 0;
3594
3595 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3596 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3597
3598 // See comments in makeFunctions() for details about the semantics for parameter passing.
3599 //
3600 // These imply we need a four step process:
3601 // 1. Evaluate the arguments
3602 // 2. Allocate and make copies of in, out, and inout arguments
3603 // 3. Make the call
3604 // 4. Copy back the results
3605
3606 // 1. Evaluate the arguments
3607 std::vector<spv::Builder::AccessChain> lValues;
3608 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003609 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003610 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003611 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003612 // build l-value
3613 builder.clearAccessChain();
3614 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003615 argTypes.push_back(&paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003616 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenich6a14f782017-12-04 02:48:10 -07003617 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0) ||
3618 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003619 // save l-value
3620 lValues.push_back(builder.getAccessChain());
3621 } else {
3622 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003623 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003624 }
3625 }
3626
3627 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3628 // copy the original into that space.
3629 //
3630 // Also, build up the list of actual arguments to pass in for the call
3631 int lValueCount = 0;
3632 int rValueCount = 0;
3633 std::vector<spv::Id> spvArgs;
3634 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003635 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003636 spv::Id arg;
John Kessenichd41993d2017-09-10 15:21:05 -06003637 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003638 builder.setAccessChain(lValues[lValueCount]);
3639 arg = builder.accessChainGetLValue();
3640 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06003641 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003642 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003643 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3644 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3645 // need to copy the input into output space
3646 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003647 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003648 builder.clearAccessChain();
3649 builder.setAccessChainLValue(arg);
3650 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003651 }
3652 ++lValueCount;
3653 } else {
3654 arg = rValues[rValueCount];
3655 ++rValueCount;
3656 }
3657 spvArgs.push_back(arg);
3658 }
3659
3660 // 3. Make the call.
3661 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003662 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003663
3664 // 4. Copy back out an "out" arguments.
3665 lValueCount = 0;
3666 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003667 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenichd41993d2017-09-10 15:21:05 -06003668 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0))
3669 ++lValueCount;
3670 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003671 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3672 spv::Id copy = builder.createLoad(spvArgs[a]);
3673 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003674 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003675 }
3676 ++lValueCount;
3677 }
3678 }
3679
3680 return result;
3681}
3682
3683// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003684spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3685 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003686 spv::Id typeId, spv::Id left, spv::Id right,
3687 glslang::TBasicType typeProxy, bool reduceComparison)
3688{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003689#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003690 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003691 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3692#else
Rex Xucabbb782017-03-24 13:41:14 +08003693 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003694 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003695#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003696 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003697
3698 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003699 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003700 bool comparison = false;
3701
3702 switch (op) {
3703 case glslang::EOpAdd:
3704 case glslang::EOpAddAssign:
3705 if (isFloat)
3706 binOp = spv::OpFAdd;
3707 else
3708 binOp = spv::OpIAdd;
3709 break;
3710 case glslang::EOpSub:
3711 case glslang::EOpSubAssign:
3712 if (isFloat)
3713 binOp = spv::OpFSub;
3714 else
3715 binOp = spv::OpISub;
3716 break;
3717 case glslang::EOpMul:
3718 case glslang::EOpMulAssign:
3719 if (isFloat)
3720 binOp = spv::OpFMul;
3721 else
3722 binOp = spv::OpIMul;
3723 break;
3724 case glslang::EOpVectorTimesScalar:
3725 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003726 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003727 if (builder.isVector(right))
3728 std::swap(left, right);
3729 assert(builder.isScalar(right));
3730 needMatchingVectors = false;
3731 binOp = spv::OpVectorTimesScalar;
3732 } else
3733 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003734 break;
3735 case glslang::EOpVectorTimesMatrix:
3736 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003737 binOp = spv::OpVectorTimesMatrix;
3738 break;
3739 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003740 binOp = spv::OpMatrixTimesVector;
3741 break;
3742 case glslang::EOpMatrixTimesScalar:
3743 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003744 binOp = spv::OpMatrixTimesScalar;
3745 break;
3746 case glslang::EOpMatrixTimesMatrix:
3747 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003748 binOp = spv::OpMatrixTimesMatrix;
3749 break;
3750 case glslang::EOpOuterProduct:
3751 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003752 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003753 break;
3754
3755 case glslang::EOpDiv:
3756 case glslang::EOpDivAssign:
3757 if (isFloat)
3758 binOp = spv::OpFDiv;
3759 else if (isUnsigned)
3760 binOp = spv::OpUDiv;
3761 else
3762 binOp = spv::OpSDiv;
3763 break;
3764 case glslang::EOpMod:
3765 case glslang::EOpModAssign:
3766 if (isFloat)
3767 binOp = spv::OpFMod;
3768 else if (isUnsigned)
3769 binOp = spv::OpUMod;
3770 else
3771 binOp = spv::OpSMod;
3772 break;
3773 case glslang::EOpRightShift:
3774 case glslang::EOpRightShiftAssign:
3775 if (isUnsigned)
3776 binOp = spv::OpShiftRightLogical;
3777 else
3778 binOp = spv::OpShiftRightArithmetic;
3779 break;
3780 case glslang::EOpLeftShift:
3781 case glslang::EOpLeftShiftAssign:
3782 binOp = spv::OpShiftLeftLogical;
3783 break;
3784 case glslang::EOpAnd:
3785 case glslang::EOpAndAssign:
3786 binOp = spv::OpBitwiseAnd;
3787 break;
3788 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003789 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003790 binOp = spv::OpLogicalAnd;
3791 break;
3792 case glslang::EOpInclusiveOr:
3793 case glslang::EOpInclusiveOrAssign:
3794 binOp = spv::OpBitwiseOr;
3795 break;
3796 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003797 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003798 binOp = spv::OpLogicalOr;
3799 break;
3800 case glslang::EOpExclusiveOr:
3801 case glslang::EOpExclusiveOrAssign:
3802 binOp = spv::OpBitwiseXor;
3803 break;
3804 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003805 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003806 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003807 break;
3808
3809 case glslang::EOpLessThan:
3810 case glslang::EOpGreaterThan:
3811 case glslang::EOpLessThanEqual:
3812 case glslang::EOpGreaterThanEqual:
3813 case glslang::EOpEqual:
3814 case glslang::EOpNotEqual:
3815 case glslang::EOpVectorEqual:
3816 case glslang::EOpVectorNotEqual:
3817 comparison = true;
3818 break;
3819 default:
3820 break;
3821 }
3822
John Kessenich7c1aa102015-10-15 13:29:11 -06003823 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003824 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003825 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003826 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003827 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003828
3829 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003830 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003831 builder.promoteScalar(precision, left, right);
3832
qining25262b32016-05-06 17:25:16 -04003833 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3834 addDecoration(result, noContraction);
3835 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003836 }
3837
3838 if (! comparison)
3839 return 0;
3840
John Kessenich7c1aa102015-10-15 13:29:11 -06003841 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003842
John Kessenich4583b612016-08-07 19:14:22 -06003843 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3844 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003845 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003846
3847 switch (op) {
3848 case glslang::EOpLessThan:
3849 if (isFloat)
3850 binOp = spv::OpFOrdLessThan;
3851 else if (isUnsigned)
3852 binOp = spv::OpULessThan;
3853 else
3854 binOp = spv::OpSLessThan;
3855 break;
3856 case glslang::EOpGreaterThan:
3857 if (isFloat)
3858 binOp = spv::OpFOrdGreaterThan;
3859 else if (isUnsigned)
3860 binOp = spv::OpUGreaterThan;
3861 else
3862 binOp = spv::OpSGreaterThan;
3863 break;
3864 case glslang::EOpLessThanEqual:
3865 if (isFloat)
3866 binOp = spv::OpFOrdLessThanEqual;
3867 else if (isUnsigned)
3868 binOp = spv::OpULessThanEqual;
3869 else
3870 binOp = spv::OpSLessThanEqual;
3871 break;
3872 case glslang::EOpGreaterThanEqual:
3873 if (isFloat)
3874 binOp = spv::OpFOrdGreaterThanEqual;
3875 else if (isUnsigned)
3876 binOp = spv::OpUGreaterThanEqual;
3877 else
3878 binOp = spv::OpSGreaterThanEqual;
3879 break;
3880 case glslang::EOpEqual:
3881 case glslang::EOpVectorEqual:
3882 if (isFloat)
3883 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003884 else if (isBool)
3885 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003886 else
3887 binOp = spv::OpIEqual;
3888 break;
3889 case glslang::EOpNotEqual:
3890 case glslang::EOpVectorNotEqual:
3891 if (isFloat)
3892 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003893 else if (isBool)
3894 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003895 else
3896 binOp = spv::OpINotEqual;
3897 break;
3898 default:
3899 break;
3900 }
3901
qining25262b32016-05-06 17:25:16 -04003902 if (binOp != spv::OpNop) {
3903 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3904 addDecoration(result, noContraction);
3905 return builder.setPrecision(result, precision);
3906 }
John Kessenich140f3df2015-06-26 16:58:36 -06003907
3908 return 0;
3909}
3910
John Kessenich04bb8a02015-12-12 12:28:14 -07003911//
3912// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3913// These can be any of:
3914//
3915// matrix * scalar
3916// scalar * matrix
3917// matrix * matrix linear algebraic
3918// matrix * vector
3919// vector * matrix
3920// matrix * matrix componentwise
3921// matrix op matrix op in {+, -, /}
3922// matrix op scalar op in {+, -, /}
3923// scalar op matrix op in {+, -, /}
3924//
qining25262b32016-05-06 17:25:16 -04003925spv::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 -07003926{
3927 bool firstClass = true;
3928
3929 // First, handle first-class matrix operations (* and matrix/scalar)
3930 switch (op) {
3931 case spv::OpFDiv:
3932 if (builder.isMatrix(left) && builder.isScalar(right)) {
3933 // turn matrix / scalar into a multiply...
3934 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3935 op = spv::OpMatrixTimesScalar;
3936 } else
3937 firstClass = false;
3938 break;
3939 case spv::OpMatrixTimesScalar:
3940 if (builder.isMatrix(right))
3941 std::swap(left, right);
3942 assert(builder.isScalar(right));
3943 break;
3944 case spv::OpVectorTimesMatrix:
3945 assert(builder.isVector(left));
3946 assert(builder.isMatrix(right));
3947 break;
3948 case spv::OpMatrixTimesVector:
3949 assert(builder.isMatrix(left));
3950 assert(builder.isVector(right));
3951 break;
3952 case spv::OpMatrixTimesMatrix:
3953 assert(builder.isMatrix(left));
3954 assert(builder.isMatrix(right));
3955 break;
3956 default:
3957 firstClass = false;
3958 break;
3959 }
3960
qining25262b32016-05-06 17:25:16 -04003961 if (firstClass) {
3962 spv::Id result = builder.createBinOp(op, typeId, left, right);
3963 addDecoration(result, noContraction);
3964 return builder.setPrecision(result, precision);
3965 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003966
LoopDawg592860c2016-06-09 08:57:35 -06003967 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003968 // The result type of all of them is the same type as the (a) matrix operand.
3969 // The algorithm is to:
3970 // - break the matrix(es) into vectors
3971 // - smear any scalar to a vector
3972 // - do vector operations
3973 // - make a matrix out the vector results
3974 switch (op) {
3975 case spv::OpFAdd:
3976 case spv::OpFSub:
3977 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003978 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003979 case spv::OpFMul:
3980 {
3981 // one time set up...
3982 bool leftMat = builder.isMatrix(left);
3983 bool rightMat = builder.isMatrix(right);
3984 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3985 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3986 spv::Id scalarType = builder.getScalarTypeId(typeId);
3987 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3988 std::vector<spv::Id> results;
3989 spv::Id smearVec = spv::NoResult;
3990 if (builder.isScalar(left))
3991 smearVec = builder.smearScalar(precision, left, vecType);
3992 else if (builder.isScalar(right))
3993 smearVec = builder.smearScalar(precision, right, vecType);
3994
3995 // do each vector op
3996 for (unsigned int c = 0; c < numCols; ++c) {
3997 std::vector<unsigned int> indexes;
3998 indexes.push_back(c);
3999 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
4000 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004001 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
4002 addDecoration(result, noContraction);
4003 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004004 }
4005
4006 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004007 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07004008 }
4009 default:
4010 assert(0);
4011 return spv::NoResult;
4012 }
4013}
4014
qining25262b32016-05-06 17:25:16 -04004015spv::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 -06004016{
4017 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004018 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004019 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004020#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004021 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004022 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4023#else
Rex Xucabbb782017-03-24 13:41:14 +08004024 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08004025 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004026#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004027
4028 switch (op) {
4029 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004030 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004031 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004032 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04004033 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004034 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004035 unaryOp = spv::OpSNegate;
4036 break;
4037
4038 case glslang::EOpLogicalNot:
4039 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004040 unaryOp = spv::OpLogicalNot;
4041 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004042 case glslang::EOpBitwiseNot:
4043 unaryOp = spv::OpNot;
4044 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004045
John Kessenich140f3df2015-06-26 16:58:36 -06004046 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004047 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004048 break;
4049 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004050 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004051 break;
4052 case glslang::EOpTranspose:
4053 unaryOp = spv::OpTranspose;
4054 break;
4055
4056 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004057 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004058 break;
4059 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004060 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004061 break;
4062 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004063 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004064 break;
4065 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004066 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004067 break;
4068 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004069 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004070 break;
4071 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004072 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004073 break;
4074 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004075 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004076 break;
4077 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004078 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004079 break;
4080
4081 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004082 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004083 break;
4084 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004085 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004086 break;
4087 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004088 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004089 break;
4090 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004091 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004092 break;
4093 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004094 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004095 break;
4096 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004097 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004098 break;
4099
4100 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004101 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004102 break;
4103 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004104 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004105 break;
4106
4107 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004108 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004109 break;
4110 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004111 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004112 break;
4113 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004114 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004115 break;
4116 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004117 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004118 break;
4119 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004120 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004121 break;
4122 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004123 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004124 break;
4125
4126 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004127 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004128 break;
4129 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004130 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004131 break;
4132 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004133 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004134 break;
4135 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004136 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004137 break;
4138 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004139 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004140 break;
4141 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004142 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004143 break;
4144
4145 case glslang::EOpIsNan:
4146 unaryOp = spv::OpIsNan;
4147 break;
4148 case glslang::EOpIsInf:
4149 unaryOp = spv::OpIsInf;
4150 break;
LoopDawg592860c2016-06-09 08:57:35 -06004151 case glslang::EOpIsFinite:
4152 unaryOp = spv::OpIsFinite;
4153 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004154
Rex Xucbc426e2015-12-15 16:03:10 +08004155 case glslang::EOpFloatBitsToInt:
4156 case glslang::EOpFloatBitsToUint:
4157 case glslang::EOpIntBitsToFloat:
4158 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004159 case glslang::EOpDoubleBitsToInt64:
4160 case glslang::EOpDoubleBitsToUint64:
4161 case glslang::EOpInt64BitsToDouble:
4162 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004163#ifdef AMD_EXTENSIONS
4164 case glslang::EOpFloat16BitsToInt16:
4165 case glslang::EOpFloat16BitsToUint16:
4166 case glslang::EOpInt16BitsToFloat16:
4167 case glslang::EOpUint16BitsToFloat16:
4168#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004169 unaryOp = spv::OpBitcast;
4170 break;
4171
John Kessenich140f3df2015-06-26 16:58:36 -06004172 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004173 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004174 break;
4175 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004176 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004177 break;
4178 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004179 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004180 break;
4181 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004182 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004183 break;
4184 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004185 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004186 break;
4187 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004188 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004189 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004190 case glslang::EOpPackSnorm4x8:
4191 libCall = spv::GLSLstd450PackSnorm4x8;
4192 break;
4193 case glslang::EOpUnpackSnorm4x8:
4194 libCall = spv::GLSLstd450UnpackSnorm4x8;
4195 break;
4196 case glslang::EOpPackUnorm4x8:
4197 libCall = spv::GLSLstd450PackUnorm4x8;
4198 break;
4199 case glslang::EOpUnpackUnorm4x8:
4200 libCall = spv::GLSLstd450UnpackUnorm4x8;
4201 break;
4202 case glslang::EOpPackDouble2x32:
4203 libCall = spv::GLSLstd450PackDouble2x32;
4204 break;
4205 case glslang::EOpUnpackDouble2x32:
4206 libCall = spv::GLSLstd450UnpackDouble2x32;
4207 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004208
Rex Xu8ff43de2016-04-22 16:51:45 +08004209 case glslang::EOpPackInt2x32:
4210 case glslang::EOpUnpackInt2x32:
4211 case glslang::EOpPackUint2x32:
4212 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004213 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004214 break;
4215
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004216#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004217 case glslang::EOpPackInt2x16:
4218 case glslang::EOpUnpackInt2x16:
4219 case glslang::EOpPackUint2x16:
4220 case glslang::EOpUnpackUint2x16:
4221 case glslang::EOpPackInt4x16:
4222 case glslang::EOpUnpackInt4x16:
4223 case glslang::EOpPackUint4x16:
4224 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004225 case glslang::EOpPackFloat2x16:
4226 case glslang::EOpUnpackFloat2x16:
4227 unaryOp = spv::OpBitcast;
4228 break;
4229#endif
4230
John Kessenich140f3df2015-06-26 16:58:36 -06004231 case glslang::EOpDPdx:
4232 unaryOp = spv::OpDPdx;
4233 break;
4234 case glslang::EOpDPdy:
4235 unaryOp = spv::OpDPdy;
4236 break;
4237 case glslang::EOpFwidth:
4238 unaryOp = spv::OpFwidth;
4239 break;
4240 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004241 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004242 unaryOp = spv::OpDPdxFine;
4243 break;
4244 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004245 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004246 unaryOp = spv::OpDPdyFine;
4247 break;
4248 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004249 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004250 unaryOp = spv::OpFwidthFine;
4251 break;
4252 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004253 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004254 unaryOp = spv::OpDPdxCoarse;
4255 break;
4256 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004257 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004258 unaryOp = spv::OpDPdyCoarse;
4259 break;
4260 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004261 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004262 unaryOp = spv::OpFwidthCoarse;
4263 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004264 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004265 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004266 libCall = spv::GLSLstd450InterpolateAtCentroid;
4267 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004268 case glslang::EOpAny:
4269 unaryOp = spv::OpAny;
4270 break;
4271 case glslang::EOpAll:
4272 unaryOp = spv::OpAll;
4273 break;
4274
4275 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004276 if (isFloat)
4277 libCall = spv::GLSLstd450FAbs;
4278 else
4279 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004280 break;
4281 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004282 if (isFloat)
4283 libCall = spv::GLSLstd450FSign;
4284 else
4285 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004286 break;
4287
John Kessenichfc51d282015-08-19 13:34:18 -06004288 case glslang::EOpAtomicCounterIncrement:
4289 case glslang::EOpAtomicCounterDecrement:
4290 case glslang::EOpAtomicCounter:
4291 {
4292 // Handle all of the atomics in one place, in createAtomicOperation()
4293 std::vector<spv::Id> operands;
4294 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004295 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004296 }
4297
John Kessenichfc51d282015-08-19 13:34:18 -06004298 case glslang::EOpBitFieldReverse:
4299 unaryOp = spv::OpBitReverse;
4300 break;
4301 case glslang::EOpBitCount:
4302 unaryOp = spv::OpBitCount;
4303 break;
4304 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004305 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004306 break;
4307 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004308 if (isUnsigned)
4309 libCall = spv::GLSLstd450FindUMsb;
4310 else
4311 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004312 break;
4313
Rex Xu574ab042016-04-14 16:53:07 +08004314 case glslang::EOpBallot:
4315 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004316 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004317 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004318 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004319#ifdef AMD_EXTENSIONS
4320 case glslang::EOpMinInvocations:
4321 case glslang::EOpMaxInvocations:
4322 case glslang::EOpAddInvocations:
4323 case glslang::EOpMinInvocationsNonUniform:
4324 case glslang::EOpMaxInvocationsNonUniform:
4325 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004326 case glslang::EOpMinInvocationsInclusiveScan:
4327 case glslang::EOpMaxInvocationsInclusiveScan:
4328 case glslang::EOpAddInvocationsInclusiveScan:
4329 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4330 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4331 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4332 case glslang::EOpMinInvocationsExclusiveScan:
4333 case glslang::EOpMaxInvocationsExclusiveScan:
4334 case glslang::EOpAddInvocationsExclusiveScan:
4335 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4336 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4337 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004338#endif
Rex Xu51596642016-09-21 18:56:12 +08004339 {
4340 std::vector<spv::Id> operands;
4341 operands.push_back(operand);
4342 return createInvocationsOperation(op, typeId, operands, typeProxy);
4343 }
Rex Xu9d93a232016-05-05 12:30:44 +08004344
4345#ifdef AMD_EXTENSIONS
4346 case glslang::EOpMbcnt:
4347 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4348 libCall = spv::MbcntAMD;
4349 break;
4350
4351 case glslang::EOpCubeFaceIndex:
4352 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4353 libCall = spv::CubeFaceIndexAMD;
4354 break;
4355
4356 case glslang::EOpCubeFaceCoord:
4357 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4358 libCall = spv::CubeFaceCoordAMD;
4359 break;
4360#endif
Rex Xu338b1852016-05-05 20:38:33 +08004361
John Kessenich140f3df2015-06-26 16:58:36 -06004362 default:
4363 return 0;
4364 }
4365
4366 spv::Id id;
4367 if (libCall >= 0) {
4368 std::vector<spv::Id> args;
4369 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004370 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004371 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004372 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004373 }
John Kessenich140f3df2015-06-26 16:58:36 -06004374
qining25262b32016-05-06 17:25:16 -04004375 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004376 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004377}
4378
John Kessenich7a53f762016-01-20 11:19:27 -07004379// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004380spv::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 -07004381{
4382 // Handle unary operations vector by vector.
4383 // The result type is the same type as the original type.
4384 // The algorithm is to:
4385 // - break the matrix into vectors
4386 // - apply the operation to each vector
4387 // - make a matrix out the vector results
4388
4389 // get the types sorted out
4390 int numCols = builder.getNumColumns(operand);
4391 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004392 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4393 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004394 std::vector<spv::Id> results;
4395
4396 // do each vector op
4397 for (int c = 0; c < numCols; ++c) {
4398 std::vector<unsigned int> indexes;
4399 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004400 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4401 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4402 addDecoration(destVec, noContraction);
4403 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004404 }
4405
4406 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004407 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004408}
4409
Rex Xu73e3ce72016-04-27 18:48:17 +08004410spv::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 -06004411{
4412 spv::Op convOp = spv::OpNop;
4413 spv::Id zero = 0;
4414 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004415 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004416
4417 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4418
4419 switch (op) {
4420 case glslang::EOpConvIntToBool:
4421 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004422 case glslang::EOpConvInt64ToBool:
4423 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004424#ifdef AMD_EXTENSIONS
4425 case glslang::EOpConvInt16ToBool:
4426 case glslang::EOpConvUint16ToBool:
4427#endif
4428 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4429 zero = builder.makeUint64Constant(0);
4430#ifdef AMD_EXTENSIONS
4431 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4432 zero = builder.makeUint16Constant(0);
4433#endif
4434 else
4435 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004436 zero = makeSmearedConstant(zero, vectorSize);
4437 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4438
4439 case glslang::EOpConvFloatToBool:
4440 zero = builder.makeFloatConstant(0.0F);
4441 zero = makeSmearedConstant(zero, vectorSize);
4442 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4443
4444 case glslang::EOpConvDoubleToBool:
4445 zero = builder.makeDoubleConstant(0.0);
4446 zero = makeSmearedConstant(zero, vectorSize);
4447 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4448
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004449#ifdef AMD_EXTENSIONS
4450 case glslang::EOpConvFloat16ToBool:
4451 zero = builder.makeFloat16Constant(0.0F);
4452 zero = makeSmearedConstant(zero, vectorSize);
4453 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4454#endif
4455
John Kessenich140f3df2015-06-26 16:58:36 -06004456 case glslang::EOpConvBoolToFloat:
4457 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004458 zero = builder.makeFloatConstant(0.0F);
4459 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004460 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004461
John Kessenich140f3df2015-06-26 16:58:36 -06004462 case glslang::EOpConvBoolToDouble:
4463 convOp = spv::OpSelect;
4464 zero = builder.makeDoubleConstant(0.0);
4465 one = builder.makeDoubleConstant(1.0);
4466 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004467
4468#ifdef AMD_EXTENSIONS
4469 case glslang::EOpConvBoolToFloat16:
4470 convOp = spv::OpSelect;
4471 zero = builder.makeFloat16Constant(0.0F);
4472 one = builder.makeFloat16Constant(1.0F);
4473 break;
4474#endif
4475
John Kessenich140f3df2015-06-26 16:58:36 -06004476 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004477 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004478#ifdef AMD_EXTENSIONS
4479 case glslang::EOpConvBoolToInt16:
4480#endif
4481 if (op == glslang::EOpConvBoolToInt64)
4482 zero = builder.makeInt64Constant(0);
4483#ifdef AMD_EXTENSIONS
4484 else if (op == glslang::EOpConvBoolToInt16)
4485 zero = builder.makeInt16Constant(0);
4486#endif
4487 else
4488 zero = builder.makeIntConstant(0);
4489
4490 if (op == glslang::EOpConvBoolToInt64)
4491 one = builder.makeInt64Constant(1);
4492#ifdef AMD_EXTENSIONS
4493 else if (op == glslang::EOpConvBoolToInt16)
4494 one = builder.makeInt16Constant(1);
4495#endif
4496 else
4497 one = builder.makeIntConstant(1);
4498
John Kessenich140f3df2015-06-26 16:58:36 -06004499 convOp = spv::OpSelect;
4500 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004501
John Kessenich140f3df2015-06-26 16:58:36 -06004502 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004503 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004504#ifdef AMD_EXTENSIONS
4505 case glslang::EOpConvBoolToUint16:
4506#endif
4507 if (op == glslang::EOpConvBoolToUint64)
4508 zero = builder.makeUint64Constant(0);
4509#ifdef AMD_EXTENSIONS
4510 else if (op == glslang::EOpConvBoolToUint16)
4511 zero = builder.makeUint16Constant(0);
4512#endif
4513 else
4514 zero = builder.makeUintConstant(0);
4515
4516 if (op == glslang::EOpConvBoolToUint64)
4517 one = builder.makeUint64Constant(1);
4518#ifdef AMD_EXTENSIONS
4519 else if (op == glslang::EOpConvBoolToUint16)
4520 one = builder.makeUint16Constant(1);
4521#endif
4522 else
4523 one = builder.makeUintConstant(1);
4524
John Kessenich140f3df2015-06-26 16:58:36 -06004525 convOp = spv::OpSelect;
4526 break;
4527
4528 case glslang::EOpConvIntToFloat:
4529 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004530 case glslang::EOpConvInt64ToFloat:
4531 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004532#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004533 case glslang::EOpConvInt16ToFloat:
4534 case glslang::EOpConvInt16ToDouble:
4535 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004536 case glslang::EOpConvIntToFloat16:
4537 case glslang::EOpConvInt64ToFloat16:
4538#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004539 convOp = spv::OpConvertSToF;
4540 break;
4541
4542 case glslang::EOpConvUintToFloat:
4543 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004544 case glslang::EOpConvUint64ToFloat:
4545 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004546#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004547 case glslang::EOpConvUint16ToFloat:
4548 case glslang::EOpConvUint16ToDouble:
4549 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004550 case glslang::EOpConvUintToFloat16:
4551 case glslang::EOpConvUint64ToFloat16:
4552#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004553 convOp = spv::OpConvertUToF;
4554 break;
4555
4556 case glslang::EOpConvDoubleToFloat:
4557 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004558#ifdef AMD_EXTENSIONS
4559 case glslang::EOpConvDoubleToFloat16:
4560 case glslang::EOpConvFloat16ToDouble:
4561 case glslang::EOpConvFloatToFloat16:
4562 case glslang::EOpConvFloat16ToFloat:
4563#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004564 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004565 if (builder.isMatrixType(destType))
4566 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004567 break;
4568
4569 case glslang::EOpConvFloatToInt:
4570 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004571 case glslang::EOpConvFloatToInt64:
4572 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004573#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004574 case glslang::EOpConvFloatToInt16:
4575 case glslang::EOpConvDoubleToInt16:
4576 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004577 case glslang::EOpConvFloat16ToInt:
4578 case glslang::EOpConvFloat16ToInt64:
4579#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004580 convOp = spv::OpConvertFToS;
4581 break;
4582
4583 case glslang::EOpConvUintToInt:
4584 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004585 case glslang::EOpConvUint64ToInt64:
4586 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004587#ifdef AMD_EXTENSIONS
4588 case glslang::EOpConvUint16ToInt16:
4589 case glslang::EOpConvInt16ToUint16:
4590#endif
qininge24aa5e2016-04-07 15:40:27 -04004591 if (builder.isInSpecConstCodeGenMode()) {
4592 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004593 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4594 zero = builder.makeUint64Constant(0);
4595#ifdef AMD_EXTENSIONS
4596 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4597 zero = builder.makeUint16Constant(0);
4598#endif
4599 else
4600 zero = builder.makeUintConstant(0);
4601
qining189b2032016-04-12 23:16:20 -04004602 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004603 // Use OpIAdd, instead of OpBitcast to do the conversion when
4604 // generating for OpSpecConstantOp instruction.
4605 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4606 }
4607 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004608 convOp = spv::OpBitcast;
4609 break;
4610
4611 case glslang::EOpConvFloatToUint:
4612 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004613 case glslang::EOpConvFloatToUint64:
4614 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004615#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004616 case glslang::EOpConvFloatToUint16:
4617 case glslang::EOpConvDoubleToUint16:
4618 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004619 case glslang::EOpConvFloat16ToUint:
4620 case glslang::EOpConvFloat16ToUint64:
4621#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004622 convOp = spv::OpConvertFToU;
4623 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004624
4625 case glslang::EOpConvIntToInt64:
4626 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004627#ifdef AMD_EXTENSIONS
4628 case glslang::EOpConvIntToInt16:
4629 case glslang::EOpConvInt16ToInt:
4630 case glslang::EOpConvInt64ToInt16:
4631 case glslang::EOpConvInt16ToInt64:
4632#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004633 convOp = spv::OpSConvert;
4634 break;
4635
4636 case glslang::EOpConvUintToUint64:
4637 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004638#ifdef AMD_EXTENSIONS
4639 case glslang::EOpConvUintToUint16:
4640 case glslang::EOpConvUint16ToUint:
4641 case glslang::EOpConvUint64ToUint16:
4642 case glslang::EOpConvUint16ToUint64:
4643#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004644 convOp = spv::OpUConvert;
4645 break;
4646
4647 case glslang::EOpConvIntToUint64:
4648 case glslang::EOpConvInt64ToUint:
4649 case glslang::EOpConvUint64ToInt:
4650 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004651#ifdef AMD_EXTENSIONS
4652 case glslang::EOpConvInt16ToUint:
4653 case glslang::EOpConvUintToInt16:
4654 case glslang::EOpConvInt16ToUint64:
4655 case glslang::EOpConvUint64ToInt16:
4656 case glslang::EOpConvUint16ToInt:
4657 case glslang::EOpConvIntToUint16:
4658 case glslang::EOpConvUint16ToInt64:
4659 case glslang::EOpConvInt64ToUint16:
4660#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004661 // OpSConvert/OpUConvert + OpBitCast
4662 switch (op) {
4663 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004664#ifdef AMD_EXTENSIONS
4665 case glslang::EOpConvInt16ToUint64:
4666#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004667 convOp = spv::OpSConvert;
4668 type = builder.makeIntType(64);
4669 break;
4670 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004671#ifdef AMD_EXTENSIONS
4672 case glslang::EOpConvInt16ToUint:
4673#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004674 convOp = spv::OpSConvert;
4675 type = builder.makeIntType(32);
4676 break;
4677 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004678#ifdef AMD_EXTENSIONS
4679 case glslang::EOpConvUint16ToInt:
4680#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004681 convOp = spv::OpUConvert;
4682 type = builder.makeUintType(32);
4683 break;
4684 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004685#ifdef AMD_EXTENSIONS
4686 case glslang::EOpConvUint16ToInt64:
4687#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004688 convOp = spv::OpUConvert;
4689 type = builder.makeUintType(64);
4690 break;
Rex Xucabbb782017-03-24 13:41:14 +08004691#ifdef AMD_EXTENSIONS
4692 case glslang::EOpConvUintToInt16:
4693 case glslang::EOpConvUint64ToInt16:
4694 convOp = spv::OpUConvert;
4695 type = builder.makeUintType(16);
4696 break;
4697 case glslang::EOpConvIntToUint16:
4698 case glslang::EOpConvInt64ToUint16:
4699 convOp = spv::OpSConvert;
4700 type = builder.makeIntType(16);
4701 break;
4702#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004703 default:
4704 assert(0);
4705 break;
4706 }
4707
4708 if (vectorSize > 0)
4709 type = builder.makeVectorType(type, vectorSize);
4710
4711 operand = builder.createUnaryOp(convOp, type, operand);
4712
4713 if (builder.isInSpecConstCodeGenMode()) {
4714 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004715#ifdef AMD_EXTENSIONS
4716 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4717 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4718 zero = builder.makeUint64Constant(0);
4719 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4720 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4721 zero = builder.makeUint16Constant(0);
4722 else
4723 zero = builder.makeUintConstant(0);
4724#else
4725 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4726 zero = builder.makeUint64Constant(0);
4727 else
4728 zero = builder.makeUintConstant(0);
4729#endif
4730
Rex Xu8ff43de2016-04-22 16:51:45 +08004731 zero = makeSmearedConstant(zero, vectorSize);
4732 // Use OpIAdd, instead of OpBitcast to do the conversion when
4733 // generating for OpSpecConstantOp instruction.
4734 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4735 }
4736 // For normal run-time conversion instruction, use OpBitcast.
4737 convOp = spv::OpBitcast;
4738 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004739 default:
4740 break;
4741 }
4742
4743 spv::Id result = 0;
4744 if (convOp == spv::OpNop)
4745 return result;
4746
4747 if (convOp == spv::OpSelect) {
4748 zero = makeSmearedConstant(zero, vectorSize);
4749 one = makeSmearedConstant(one, vectorSize);
4750 result = builder.createTriOp(convOp, destType, operand, one, zero);
4751 } else
4752 result = builder.createUnaryOp(convOp, destType, operand);
4753
John Kessenich32cfd492016-02-02 12:37:46 -07004754 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004755}
4756
4757spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4758{
4759 if (vectorSize == 0)
4760 return constant;
4761
4762 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4763 std::vector<spv::Id> components;
4764 for (int c = 0; c < vectorSize; ++c)
4765 components.push_back(constant);
4766 return builder.makeCompositeConstant(vectorTypeId, components);
4767}
4768
John Kessenich426394d2015-07-23 10:22:48 -06004769// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004770spv::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 -06004771{
4772 spv::Op opCode = spv::OpNop;
4773
4774 switch (op) {
4775 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004776 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004777 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004778 opCode = spv::OpAtomicIAdd;
4779 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004780 case glslang::EOpAtomicCounterSubtract:
4781 opCode = spv::OpAtomicISub;
4782 break;
John Kessenich426394d2015-07-23 10:22:48 -06004783 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004784 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004785 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08004786 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004787 break;
4788 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004789 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004790 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08004791 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004792 break;
4793 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004794 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004795 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004796 opCode = spv::OpAtomicAnd;
4797 break;
4798 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004799 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004800 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004801 opCode = spv::OpAtomicOr;
4802 break;
4803 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004804 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004805 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004806 opCode = spv::OpAtomicXor;
4807 break;
4808 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004809 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004810 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004811 opCode = spv::OpAtomicExchange;
4812 break;
4813 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004814 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004815 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004816 opCode = spv::OpAtomicCompareExchange;
4817 break;
4818 case glslang::EOpAtomicCounterIncrement:
4819 opCode = spv::OpAtomicIIncrement;
4820 break;
4821 case glslang::EOpAtomicCounterDecrement:
4822 opCode = spv::OpAtomicIDecrement;
4823 break;
4824 case glslang::EOpAtomicCounter:
4825 opCode = spv::OpAtomicLoad;
4826 break;
4827 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004828 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004829 break;
4830 }
4831
Rex Xue8fe8b02017-09-26 15:42:56 +08004832 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
4833 builder.addCapability(spv::CapabilityInt64Atomics);
4834
John Kessenich426394d2015-07-23 10:22:48 -06004835 // Sort out the operands
4836 // - mapping from glslang -> SPV
4837 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004838 // - compare-exchange swaps the value and comparator
4839 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06004840 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06004841 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4842 auto opIt = operands.begin(); // walk the glslang operands
4843 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004844 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4845 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4846 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004847 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4848 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004849 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004850 spvAtomicOperands.push_back(*(opIt + 1));
4851 spvAtomicOperands.push_back(*opIt);
4852 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004853 }
John Kessenich426394d2015-07-23 10:22:48 -06004854
John Kessenich3e60a6f2015-09-14 22:45:16 -06004855 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004856 for (; opIt != operands.end(); ++opIt)
4857 spvAtomicOperands.push_back(*opIt);
4858
John Kessenich48d6e792017-10-06 21:21:48 -06004859 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
4860
4861 // GLSL and HLSL atomic-counter decrement return post-decrement value,
4862 // while SPIR-V returns pre-decrement value. Translate between these semantics.
4863 if (op == glslang::EOpAtomicCounterDecrement)
4864 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
4865
4866 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06004867}
4868
John Kessenich91cef522016-05-05 16:45:40 -06004869// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004870spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004871{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004872#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004873 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004874 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004875#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004876
Rex Xu51596642016-09-21 18:56:12 +08004877 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004878 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004879 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4880
chaocf200da82016-12-20 12:44:35 -08004881 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4882 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004883 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4884 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004885 } else if (op == glslang::EOpAnyInvocation ||
4886 op == glslang::EOpAllInvocations ||
4887 op == glslang::EOpAllInvocationsEqual) {
4888 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4889 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004890 } else {
4891 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004892#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004893 if (op == glslang::EOpMinInvocationsNonUniform ||
4894 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004895 op == glslang::EOpAddInvocationsNonUniform ||
4896 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4897 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4898 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4899 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4900 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4901 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004902 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004903#endif
Rex Xu51596642016-09-21 18:56:12 +08004904
4905 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004906#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004907 switch (op) {
4908 case glslang::EOpMinInvocations:
4909 case glslang::EOpMaxInvocations:
4910 case glslang::EOpAddInvocations:
4911 case glslang::EOpMinInvocationsNonUniform:
4912 case glslang::EOpMaxInvocationsNonUniform:
4913 case glslang::EOpAddInvocationsNonUniform:
4914 groupOperation = spv::GroupOperationReduce;
4915 spvGroupOperands.push_back(groupOperation);
4916 break;
4917 case glslang::EOpMinInvocationsInclusiveScan:
4918 case glslang::EOpMaxInvocationsInclusiveScan:
4919 case glslang::EOpAddInvocationsInclusiveScan:
4920 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4921 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4922 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4923 groupOperation = spv::GroupOperationInclusiveScan;
4924 spvGroupOperands.push_back(groupOperation);
4925 break;
4926 case glslang::EOpMinInvocationsExclusiveScan:
4927 case glslang::EOpMaxInvocationsExclusiveScan:
4928 case glslang::EOpAddInvocationsExclusiveScan:
4929 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4930 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4931 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4932 groupOperation = spv::GroupOperationExclusiveScan;
4933 spvGroupOperands.push_back(groupOperation);
4934 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004935 default:
4936 break;
Rex Xu430ef402016-10-14 17:22:23 +08004937 }
Rex Xu9d93a232016-05-05 12:30:44 +08004938#endif
Rex Xu51596642016-09-21 18:56:12 +08004939 }
4940
4941 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4942 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004943
4944 switch (op) {
4945 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004946 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004947 break;
John Kessenich91cef522016-05-05 16:45:40 -06004948 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004949 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004950 break;
John Kessenich91cef522016-05-05 16:45:40 -06004951 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004952 opCode = spv::OpSubgroupAllEqualKHR;
4953 break;
Rex Xu51596642016-09-21 18:56:12 +08004954 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004955 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004956 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004957 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004958 break;
4959 case glslang::EOpReadFirstInvocation:
4960 opCode = spv::OpSubgroupFirstInvocationKHR;
4961 break;
4962 case glslang::EOpBallot:
4963 {
4964 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4965 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4966 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4967 //
4968 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4969 //
4970 spv::Id uintType = builder.makeUintType(32);
4971 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4972 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4973
4974 std::vector<spv::Id> components;
4975 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4976 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4977
4978 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4979 return builder.createUnaryOp(spv::OpBitcast, typeId,
4980 builder.createCompositeConstruct(uvec2Type, components));
4981 }
4982
Rex Xu9d93a232016-05-05 12:30:44 +08004983#ifdef AMD_EXTENSIONS
4984 case glslang::EOpMinInvocations:
4985 case glslang::EOpMaxInvocations:
4986 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004987 case glslang::EOpMinInvocationsInclusiveScan:
4988 case glslang::EOpMaxInvocationsInclusiveScan:
4989 case glslang::EOpAddInvocationsInclusiveScan:
4990 case glslang::EOpMinInvocationsExclusiveScan:
4991 case glslang::EOpMaxInvocationsExclusiveScan:
4992 case glslang::EOpAddInvocationsExclusiveScan:
4993 if (op == glslang::EOpMinInvocations ||
4994 op == glslang::EOpMinInvocationsInclusiveScan ||
4995 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004996 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004997 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004998 else {
4999 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005000 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005001 else
Rex Xu51596642016-09-21 18:56:12 +08005002 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005003 }
Rex Xu430ef402016-10-14 17:22:23 +08005004 } else if (op == glslang::EOpMaxInvocations ||
5005 op == glslang::EOpMaxInvocationsInclusiveScan ||
5006 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005007 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005008 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005009 else {
5010 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005011 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005012 else
Rex Xu51596642016-09-21 18:56:12 +08005013 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005014 }
5015 } else {
5016 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005017 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005018 else
Rex Xu51596642016-09-21 18:56:12 +08005019 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005020 }
5021
Rex Xu2bbbe062016-08-23 15:41:05 +08005022 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005023 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005024
5025 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005026 case glslang::EOpMinInvocationsNonUniform:
5027 case glslang::EOpMaxInvocationsNonUniform:
5028 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005029 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5030 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5031 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5032 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5033 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5034 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5035 if (op == glslang::EOpMinInvocationsNonUniform ||
5036 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5037 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005038 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005039 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005040 else {
5041 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005042 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005043 else
Rex Xu51596642016-09-21 18:56:12 +08005044 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005045 }
5046 }
Rex Xu430ef402016-10-14 17:22:23 +08005047 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5048 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5049 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005050 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005051 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005052 else {
5053 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005054 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005055 else
Rex Xu51596642016-09-21 18:56:12 +08005056 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005057 }
5058 }
5059 else {
5060 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005061 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005062 else
Rex Xu51596642016-09-21 18:56:12 +08005063 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005064 }
5065
Rex Xu2bbbe062016-08-23 15:41:05 +08005066 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005067 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005068
5069 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005070#endif
John Kessenich91cef522016-05-05 16:45:40 -06005071 default:
5072 logger->missingFunctionality("invocation operation");
5073 return spv::NoResult;
5074 }
Rex Xu51596642016-09-21 18:56:12 +08005075
5076 assert(opCode != spv::OpNop);
5077 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005078}
5079
Rex Xu2bbbe062016-08-23 15:41:05 +08005080// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005081spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005082{
Rex Xub7072052016-09-26 15:53:40 +08005083#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005084 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5085 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005086 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005087 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005088 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5089 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5090 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005091#else
5092 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5093 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005094 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5095 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005096#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005097
5098 // Handle group invocation operations scalar by scalar.
5099 // The result type is the same type as the original type.
5100 // The algorithm is to:
5101 // - break the vector into scalars
5102 // - apply the operation to each scalar
5103 // - make a vector out the scalar results
5104
5105 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005106 int numComponents = builder.getNumComponents(operands[0]);
5107 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005108 std::vector<spv::Id> results;
5109
5110 // do each scalar op
5111 for (int comp = 0; comp < numComponents; ++comp) {
5112 std::vector<unsigned int> indexes;
5113 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005114 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005115 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005116 if (op == spv::OpSubgroupReadInvocationKHR) {
5117 spvGroupOperands.push_back(scalar);
5118 spvGroupOperands.push_back(operands[1]);
5119 } else if (op == spv::OpGroupBroadcast) {
5120 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005121 spvGroupOperands.push_back(scalar);
5122 spvGroupOperands.push_back(operands[1]);
5123 } else {
chaocf200da82016-12-20 12:44:35 -08005124 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005125 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005126 spvGroupOperands.push_back(scalar);
5127 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005128
Rex Xub7072052016-09-26 15:53:40 +08005129 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005130 }
5131
5132 // put the pieces together
5133 return builder.createCompositeConstruct(typeId, results);
5134}
Rex Xu2bbbe062016-08-23 15:41:05 +08005135
John Kessenich5e4b1242015-08-06 22:53:06 -06005136spv::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 -06005137{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005138#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005139 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005140 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5141#else
Rex Xucabbb782017-03-24 13:41:14 +08005142 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005143 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005144#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005145
John Kessenich140f3df2015-06-26 16:58:36 -06005146 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005147 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005148 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005149 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005150 spv::Id typeId0 = 0;
5151 if (consumedOperands > 0)
5152 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005153 spv::Id typeId1 = 0;
5154 if (consumedOperands > 1)
5155 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005156 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005157
5158 switch (op) {
5159 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005160 if (isFloat)
5161 libCall = spv::GLSLstd450FMin;
5162 else if (isUnsigned)
5163 libCall = spv::GLSLstd450UMin;
5164 else
5165 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005166 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005167 break;
5168 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005169 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005170 break;
5171 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005172 if (isFloat)
5173 libCall = spv::GLSLstd450FMax;
5174 else if (isUnsigned)
5175 libCall = spv::GLSLstd450UMax;
5176 else
5177 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005178 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005179 break;
5180 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005181 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005182 break;
5183 case glslang::EOpDot:
5184 opCode = spv::OpDot;
5185 break;
5186 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005187 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005188 break;
5189
5190 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005191 if (isFloat)
5192 libCall = spv::GLSLstd450FClamp;
5193 else if (isUnsigned)
5194 libCall = spv::GLSLstd450UClamp;
5195 else
5196 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005197 builder.promoteScalar(precision, operands.front(), operands[1]);
5198 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005199 break;
5200 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005201 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5202 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005203 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005204 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005205 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005206 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005207 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005208 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005209 break;
5210 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005211 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005212 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005213 break;
5214 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005215 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005216 builder.promoteScalar(precision, operands[0], operands[2]);
5217 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005218 break;
5219
5220 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005221 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005222 break;
5223 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005224 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005225 break;
5226 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005227 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005228 break;
5229 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005230 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005231 break;
5232 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005233 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005234 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005235 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005236 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005237 libCall = spv::GLSLstd450InterpolateAtSample;
5238 break;
5239 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005240 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005241 libCall = spv::GLSLstd450InterpolateAtOffset;
5242 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005243 case glslang::EOpAddCarry:
5244 opCode = spv::OpIAddCarry;
5245 typeId = builder.makeStructResultType(typeId0, typeId0);
5246 consumedOperands = 2;
5247 break;
5248 case glslang::EOpSubBorrow:
5249 opCode = spv::OpISubBorrow;
5250 typeId = builder.makeStructResultType(typeId0, typeId0);
5251 consumedOperands = 2;
5252 break;
5253 case glslang::EOpUMulExtended:
5254 opCode = spv::OpUMulExtended;
5255 typeId = builder.makeStructResultType(typeId0, typeId0);
5256 consumedOperands = 2;
5257 break;
5258 case glslang::EOpIMulExtended:
5259 opCode = spv::OpSMulExtended;
5260 typeId = builder.makeStructResultType(typeId0, typeId0);
5261 consumedOperands = 2;
5262 break;
5263 case glslang::EOpBitfieldExtract:
5264 if (isUnsigned)
5265 opCode = spv::OpBitFieldUExtract;
5266 else
5267 opCode = spv::OpBitFieldSExtract;
5268 break;
5269 case glslang::EOpBitfieldInsert:
5270 opCode = spv::OpBitFieldInsert;
5271 break;
5272
5273 case glslang::EOpFma:
5274 libCall = spv::GLSLstd450Fma;
5275 break;
5276 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005277 {
5278 libCall = spv::GLSLstd450FrexpStruct;
5279 assert(builder.isPointerType(typeId1));
5280 typeId1 = builder.getContainedTypeId(typeId1);
5281#ifdef AMD_EXTENSIONS
5282 int width = builder.getScalarTypeWidth(typeId1);
5283#else
5284 int width = 32;
5285#endif
5286 if (builder.getNumComponents(operands[0]) == 1)
5287 frexpIntType = builder.makeIntegerType(width, true);
5288 else
5289 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5290 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5291 consumedOperands = 1;
5292 }
John Kessenich55e7d112015-11-15 21:33:39 -07005293 break;
5294 case glslang::EOpLdexp:
5295 libCall = spv::GLSLstd450Ldexp;
5296 break;
5297
Rex Xu574ab042016-04-14 16:53:07 +08005298 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005299 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005300
Rex Xu9d93a232016-05-05 12:30:44 +08005301#ifdef AMD_EXTENSIONS
5302 case glslang::EOpSwizzleInvocations:
5303 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5304 libCall = spv::SwizzleInvocationsAMD;
5305 break;
5306 case glslang::EOpSwizzleInvocationsMasked:
5307 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5308 libCall = spv::SwizzleInvocationsMaskedAMD;
5309 break;
5310 case glslang::EOpWriteInvocation:
5311 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5312 libCall = spv::WriteInvocationAMD;
5313 break;
5314
5315 case glslang::EOpMin3:
5316 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5317 if (isFloat)
5318 libCall = spv::FMin3AMD;
5319 else {
5320 if (isUnsigned)
5321 libCall = spv::UMin3AMD;
5322 else
5323 libCall = spv::SMin3AMD;
5324 }
5325 break;
5326 case glslang::EOpMax3:
5327 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5328 if (isFloat)
5329 libCall = spv::FMax3AMD;
5330 else {
5331 if (isUnsigned)
5332 libCall = spv::UMax3AMD;
5333 else
5334 libCall = spv::SMax3AMD;
5335 }
5336 break;
5337 case glslang::EOpMid3:
5338 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5339 if (isFloat)
5340 libCall = spv::FMid3AMD;
5341 else {
5342 if (isUnsigned)
5343 libCall = spv::UMid3AMD;
5344 else
5345 libCall = spv::SMid3AMD;
5346 }
5347 break;
5348
5349 case glslang::EOpInterpolateAtVertex:
5350 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5351 libCall = spv::InterpolateAtVertexAMD;
5352 break;
5353#endif
5354
John Kessenich140f3df2015-06-26 16:58:36 -06005355 default:
5356 return 0;
5357 }
5358
5359 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005360 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005361 // Use an extended instruction from the standard library.
5362 // Construct the call arguments, without modifying the original operands vector.
5363 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5364 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005365 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005366 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005367 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005368 case 0:
5369 // should all be handled by visitAggregate and createNoArgOperation
5370 assert(0);
5371 return 0;
5372 case 1:
5373 // should all be handled by createUnaryOperation
5374 assert(0);
5375 return 0;
5376 case 2:
5377 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5378 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005379 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005380 // anything 3 or over doesn't have l-value operands, so all should be consumed
5381 assert(consumedOperands == operands.size());
5382 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005383 break;
5384 }
5385 }
5386
John Kessenich55e7d112015-11-15 21:33:39 -07005387 // Decode the return types that were structures
5388 switch (op) {
5389 case glslang::EOpAddCarry:
5390 case glslang::EOpSubBorrow:
5391 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5392 id = builder.createCompositeExtract(id, typeId0, 0);
5393 break;
5394 case glslang::EOpUMulExtended:
5395 case glslang::EOpIMulExtended:
5396 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5397 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5398 break;
5399 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005400 {
5401 assert(operands.size() == 2);
5402 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5403 // "exp" is floating-point type (from HLSL intrinsic)
5404 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5405 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5406 builder.createStore(member1, operands[1]);
5407 } else
5408 // "exp" is integer type (from GLSL built-in function)
5409 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5410 id = builder.createCompositeExtract(id, typeId0, 0);
5411 }
John Kessenich55e7d112015-11-15 21:33:39 -07005412 break;
5413 default:
5414 break;
5415 }
5416
John Kessenich32cfd492016-02-02 12:37:46 -07005417 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005418}
5419
Rex Xu9d93a232016-05-05 12:30:44 +08005420// Intrinsics with no arguments (or no return value, and no precision).
5421spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005422{
5423 // TODO: get the barrier operands correct
5424
5425 switch (op) {
5426 case glslang::EOpEmitVertex:
5427 builder.createNoResultOp(spv::OpEmitVertex);
5428 return 0;
5429 case glslang::EOpEndPrimitive:
5430 builder.createNoResultOp(spv::OpEndPrimitive);
5431 return 0;
5432 case glslang::EOpBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005433 if (glslangIntermediate->getStage() == EShLangTessControl) {
5434 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeInvocation, spv::MemorySemanticsMaskNone);
5435 // TODO: prefer the following, when available:
5436 // builder.createControlBarrier(spv::ScopePatch, spv::ScopePatch,
5437 // spv::MemorySemanticsPatchMask |
5438 // spv::MemorySemanticsAcquireReleaseMask);
5439 } else {
5440 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
5441 spv::MemorySemanticsWorkgroupMemoryMask |
5442 spv::MemorySemanticsAcquireReleaseMask);
5443 }
John Kessenich140f3df2015-06-26 16:58:36 -06005444 return 0;
5445 case glslang::EOpMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005446 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory |
5447 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005448 return 0;
5449 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich82979362017-12-11 04:02:24 -07005450 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask |
5451 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005452 return 0;
5453 case glslang::EOpMemoryBarrierBuffer:
John Kessenich82979362017-12-11 04:02:24 -07005454 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5455 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005456 return 0;
5457 case glslang::EOpMemoryBarrierImage:
John Kessenich82979362017-12-11 04:02:24 -07005458 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask |
5459 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005460 return 0;
5461 case glslang::EOpMemoryBarrierShared:
John Kessenich82979362017-12-11 04:02:24 -07005462 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask |
5463 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005464 return 0;
5465 case glslang::EOpGroupMemoryBarrier:
John Kessenich82979362017-12-11 04:02:24 -07005466 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsAllMemory |
5467 spv::MemorySemanticsAcquireReleaseMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005468 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005469 case glslang::EOpAllMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07005470 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice,
John Kessenich82979362017-12-11 04:02:24 -07005471 spv::MemorySemanticsAllMemory |
John Kessenich838d7af2017-12-12 22:50:53 -07005472 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005473 return 0;
John Kessenich838d7af2017-12-12 22:50:53 -07005474 case glslang::EOpDeviceMemoryBarrier:
5475 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5476 spv::MemorySemanticsImageMemoryMask |
5477 spv::MemorySemanticsAcquireReleaseMask);
5478 return 0;
5479 case glslang::EOpDeviceMemoryBarrierWithGroupSync:
5480 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask |
5481 spv::MemorySemanticsImageMemoryMask |
5482 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005483 return 0;
5484 case glslang::EOpWorkgroupMemoryBarrier:
John Kessenich838d7af2017-12-12 22:50:53 -07005485 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask |
5486 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005487 return 0;
5488 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich838d7af2017-12-12 22:50:53 -07005489 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup,
5490 spv::MemorySemanticsWorkgroupMemoryMask |
5491 spv::MemorySemanticsAcquireReleaseMask);
LoopDawg6e72fdd2016-06-15 09:50:24 -06005492 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005493#ifdef AMD_EXTENSIONS
5494 case glslang::EOpTime:
5495 {
5496 std::vector<spv::Id> args; // Dummy arguments
5497 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5498 return builder.setPrecision(id, precision);
5499 }
5500#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005501 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005502 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005503 return 0;
5504 }
5505}
5506
5507spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5508{
John Kessenich2f273362015-07-18 22:34:27 -06005509 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005510 spv::Id id;
5511 if (symbolValues.end() != iter) {
5512 id = iter->second;
5513 return id;
5514 }
5515
5516 // it was not found, create it
5517 id = createSpvVariable(symbol);
5518 symbolValues[symbol->getId()] = id;
5519
Rex Xuc884b4a2016-06-29 15:03:44 +08005520 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005521 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005522 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005523 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005524 if (symbol->getType().getQualifier().hasSpecConstantId())
5525 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005526 if (symbol->getQualifier().hasIndex())
5527 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5528 if (symbol->getQualifier().hasComponent())
5529 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06005530 // atomic counters use this:
5531 if (symbol->getQualifier().hasOffset())
5532 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005533 }
5534
scygan2c864272016-05-18 18:09:17 +02005535 if (symbol->getQualifier().hasLocation())
5536 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005537 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005538 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005539 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005540 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005541 }
John Kessenich140f3df2015-06-26 16:58:36 -06005542 if (symbol->getQualifier().hasSet())
5543 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005544 else if (IsDescriptorResource(symbol->getType())) {
5545 // default to 0
5546 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5547 }
John Kessenich140f3df2015-06-26 16:58:36 -06005548 if (symbol->getQualifier().hasBinding())
5549 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005550 if (symbol->getQualifier().hasAttachment())
5551 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005552 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005553 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005554 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005555 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07005556 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06005557 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07005558 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
5559 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
5560 builder.addDecoration(id, spv::DecorationXfbStride, stride);
5561 }
5562 if (symbol->getQualifier().hasXfbOffset())
5563 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005564 }
5565
Rex Xu1da878f2016-02-21 20:59:01 +08005566 if (symbol->getType().isImage()) {
5567 std::vector<spv::Decoration> memory;
5568 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5569 for (unsigned int i = 0; i < memory.size(); ++i)
5570 addDecoration(id, memory[i]);
5571 }
5572
John Kessenich140f3df2015-06-26 16:58:36 -06005573 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005574 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005575 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005576 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005577
John Kessenichecba76f2017-01-06 00:34:48 -07005578#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005579 if (builtIn == spv::BuiltInSampleMask) {
5580 spv::Decoration decoration;
5581 // GL_NV_sample_mask_override_coverage extension
5582 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005583 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005584 else
5585 decoration = (spv::Decoration)spv::DecorationMax;
5586 addDecoration(id, decoration);
5587 if (decoration != spv::DecorationMax) {
5588 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5589 }
5590 }
chaoc771d89f2017-01-13 01:10:53 -08005591 else if (builtIn == spv::BuiltInLayer) {
5592 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06005593 if (symbol->getQualifier().layoutViewportRelative) {
chaoc771d89f2017-01-13 01:10:53 -08005594 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5595 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5596 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5597 }
John Kessenichb41bff62017-08-11 13:07:17 -06005598 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
chaoc771d89f2017-01-13 01:10:53 -08005599 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5600 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5601 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5602 }
5603 }
5604
chaoc6e5acae2016-12-20 13:28:52 -08005605 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005606 addDecoration(id, spv::DecorationPassthroughNV);
5607 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005608 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5609 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005610#endif
5611
John Kessenich140f3df2015-06-26 16:58:36 -06005612 return id;
5613}
5614
John Kessenich55e7d112015-11-15 21:33:39 -07005615// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005616void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5617{
John Kessenich4016e382016-07-15 11:53:56 -06005618 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005619 builder.addDecoration(id, dec);
5620}
5621
John Kessenich55e7d112015-11-15 21:33:39 -07005622// If 'dec' is valid, add a one-operand decoration to an object
5623void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5624{
John Kessenich4016e382016-07-15 11:53:56 -06005625 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005626 builder.addDecoration(id, dec, value);
5627}
5628
5629// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005630void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5631{
John Kessenich4016e382016-07-15 11:53:56 -06005632 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005633 builder.addMemberDecoration(id, (unsigned)member, dec);
5634}
5635
John Kessenich92187592016-02-01 13:45:25 -07005636// If 'dec' is valid, add a one-operand decoration to a struct member
5637void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5638{
John Kessenich4016e382016-07-15 11:53:56 -06005639 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005640 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5641}
5642
John Kessenich55e7d112015-11-15 21:33:39 -07005643// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005644// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005645//
5646// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5647//
5648// Recursively walk the nodes. The nodes form a tree whose leaves are
5649// regular constants, which themselves are trees that createSpvConstant()
5650// recursively walks. So, this function walks the "top" of the tree:
5651// - emit specialization constant-building instructions for specConstant
5652// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005653spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005654{
John Kessenich7cc0e282016-03-20 00:46:02 -06005655 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005656
qining4f4bb812016-04-03 23:55:17 -04005657 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005658 if (! node.getQualifier().specConstant) {
5659 // hand off to the non-spec-constant path
5660 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5661 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005662 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005663 nextConst, false);
5664 }
5665
5666 // We now know we have a specialization constant to build
5667
John Kessenichd94c0032016-05-30 19:29:40 -06005668 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005669 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5670 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5671 std::vector<spv::Id> dimConstId;
5672 for (int dim = 0; dim < 3; ++dim) {
5673 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5674 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5675 if (specConst)
5676 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5677 }
5678 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5679 }
5680
5681 // An AST node labelled as specialization constant should be a symbol node.
5682 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5683 if (auto* sn = node.getAsSymbolNode()) {
5684 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005685 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5686 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5687 // will set the builder into spec constant op instruction generating mode.
5688 sub_tree->traverse(this);
5689 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005690 } else if (auto* const_union_array = &sn->getConstArray()){
5691 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005692 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5693 builder.addName(id, sn->getName().c_str());
5694 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005695 }
5696 }
qining4f4bb812016-04-03 23:55:17 -04005697
5698 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5699 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005700 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005701 exit(1);
5702 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005703}
5704
John Kessenich140f3df2015-06-26 16:58:36 -06005705// Use 'consts' as the flattened glslang source of scalar constants to recursively
5706// build the aggregate SPIR-V constant.
5707//
5708// If there are not enough elements present in 'consts', 0 will be substituted;
5709// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5710//
qining08408382016-03-21 09:51:37 -04005711spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005712{
5713 // vector of constants for SPIR-V
5714 std::vector<spv::Id> spvConsts;
5715
5716 // Type is used for struct and array constants
5717 spv::Id typeId = convertGlslangToSpvType(glslangType);
5718
5719 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005720 glslang::TType elementType(glslangType, 0);
5721 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005722 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005723 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005724 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005725 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005726 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005727 } else if (glslangType.getStruct()) {
5728 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5729 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005730 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005731 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005732 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5733 bool zero = nextConst >= consts.size();
5734 switch (glslangType.getBasicType()) {
5735 case glslang::EbtInt:
5736 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5737 break;
5738 case glslang::EbtUint:
5739 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5740 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005741 case glslang::EbtInt64:
5742 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5743 break;
5744 case glslang::EbtUint64:
5745 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5746 break;
Rex Xucabbb782017-03-24 13:41:14 +08005747#ifdef AMD_EXTENSIONS
5748 case glslang::EbtInt16:
5749 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5750 break;
5751 case glslang::EbtUint16:
5752 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5753 break;
5754#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005755 case glslang::EbtFloat:
5756 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5757 break;
5758 case glslang::EbtDouble:
5759 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5760 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005761#ifdef AMD_EXTENSIONS
5762 case glslang::EbtFloat16:
5763 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5764 break;
5765#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005766 case glslang::EbtBool:
5767 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5768 break;
5769 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005770 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005771 break;
5772 }
5773 ++nextConst;
5774 }
5775 } else {
5776 // we have a non-aggregate (scalar) constant
5777 bool zero = nextConst >= consts.size();
5778 spv::Id scalar = 0;
5779 switch (glslangType.getBasicType()) {
5780 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005781 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005782 break;
5783 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005784 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005785 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005786 case glslang::EbtInt64:
5787 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5788 break;
5789 case glslang::EbtUint64:
5790 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5791 break;
Rex Xucabbb782017-03-24 13:41:14 +08005792#ifdef AMD_EXTENSIONS
5793 case glslang::EbtInt16:
5794 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5795 break;
5796 case glslang::EbtUint16:
5797 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5798 break;
5799#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005800 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005801 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005802 break;
5803 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005804 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005805 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005806#ifdef AMD_EXTENSIONS
5807 case glslang::EbtFloat16:
5808 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5809 break;
5810#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005811 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005812 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005813 break;
5814 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005815 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005816 break;
5817 }
5818 ++nextConst;
5819 return scalar;
5820 }
5821
5822 return builder.makeCompositeConstant(typeId, spvConsts);
5823}
5824
John Kessenich7c1aa102015-10-15 13:29:11 -06005825// Return true if the node is a constant or symbol whose reading has no
5826// non-trivial observable cost or effect.
5827bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5828{
5829 // don't know what this is
5830 if (node == nullptr)
5831 return false;
5832
5833 // a constant is safe
5834 if (node->getAsConstantUnion() != nullptr)
5835 return true;
5836
5837 // not a symbol means non-trivial
5838 if (node->getAsSymbolNode() == nullptr)
5839 return false;
5840
5841 // a symbol, depends on what's being read
5842 switch (node->getType().getQualifier().storage) {
5843 case glslang::EvqTemporary:
5844 case glslang::EvqGlobal:
5845 case glslang::EvqIn:
5846 case glslang::EvqInOut:
5847 case glslang::EvqConst:
5848 case glslang::EvqConstReadOnly:
5849 case glslang::EvqUniform:
5850 return true;
5851 default:
5852 return false;
5853 }
qining25262b32016-05-06 17:25:16 -04005854}
John Kessenich7c1aa102015-10-15 13:29:11 -06005855
5856// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005857// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005858// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005859// Return true if trivial.
5860bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5861{
5862 if (node == nullptr)
5863 return false;
5864
John Kessenich84cc15f2017-05-24 16:44:47 -06005865 // count non scalars as trivial, as well as anything coming from HLSL
5866 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005867 return true;
5868
John Kessenich7c1aa102015-10-15 13:29:11 -06005869 // symbols and constants are trivial
5870 if (isTrivialLeaf(node))
5871 return true;
5872
5873 // otherwise, it needs to be a simple operation or one or two leaf nodes
5874
5875 // not a simple operation
5876 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5877 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5878 if (binaryNode == nullptr && unaryNode == nullptr)
5879 return false;
5880
5881 // not on leaf nodes
5882 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5883 return false;
5884
5885 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5886 return false;
5887 }
5888
5889 switch (node->getAsOperator()->getOp()) {
5890 case glslang::EOpLogicalNot:
5891 case glslang::EOpConvIntToBool:
5892 case glslang::EOpConvUintToBool:
5893 case glslang::EOpConvFloatToBool:
5894 case glslang::EOpConvDoubleToBool:
5895 case glslang::EOpEqual:
5896 case glslang::EOpNotEqual:
5897 case glslang::EOpLessThan:
5898 case glslang::EOpGreaterThan:
5899 case glslang::EOpLessThanEqual:
5900 case glslang::EOpGreaterThanEqual:
5901 case glslang::EOpIndexDirect:
5902 case glslang::EOpIndexDirectStruct:
5903 case glslang::EOpLogicalXor:
5904 case glslang::EOpAny:
5905 case glslang::EOpAll:
5906 return true;
5907 default:
5908 return false;
5909 }
5910}
5911
5912// Emit short-circuiting code, where 'right' is never evaluated unless
5913// the left side is true (for &&) or false (for ||).
5914spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5915{
5916 spv::Id boolTypeId = builder.makeBoolType();
5917
5918 // emit left operand
5919 builder.clearAccessChain();
5920 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005921 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005922
5923 // Operands to accumulate OpPhi operands
5924 std::vector<spv::Id> phiOperands;
5925 // accumulate left operand's phi information
5926 phiOperands.push_back(leftId);
5927 phiOperands.push_back(builder.getBuildPoint()->getId());
5928
5929 // Make the two kinds of operation symmetric with a "!"
5930 // || => emit "if (! left) result = right"
5931 // && => emit "if ( left) result = right"
5932 //
5933 // TODO: this runtime "not" for || could be avoided by adding functionality
5934 // to 'builder' to have an "else" without an "then"
5935 if (op == glslang::EOpLogicalOr)
5936 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5937
5938 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005939 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005940
5941 // emit right operand as the "then" part of the "if"
5942 builder.clearAccessChain();
5943 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005944 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005945
5946 // accumulate left operand's phi information
5947 phiOperands.push_back(rightId);
5948 phiOperands.push_back(builder.getBuildPoint()->getId());
5949
5950 // finish the "if"
5951 ifBuilder.makeEndIf();
5952
5953 // phi together the two results
5954 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5955}
5956
Rex Xu9d93a232016-05-05 12:30:44 +08005957// Return type Id of the imported set of extended instructions corresponds to the name.
5958// Import this set if it has not been imported yet.
5959spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5960{
5961 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5962 return extBuiltinMap[name];
5963 else {
Rex Xu51596642016-09-21 18:56:12 +08005964 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005965 spv::Id extBuiltins = builder.import(name);
5966 extBuiltinMap[name] = extBuiltins;
5967 return extBuiltins;
5968 }
5969}
5970
John Kessenich140f3df2015-06-26 16:58:36 -06005971}; // end anonymous namespace
5972
5973namespace glslang {
5974
John Kessenich68d78fd2015-07-12 19:28:10 -06005975void GetSpirvVersion(std::string& version)
5976{
John Kessenich9e55f632015-07-15 10:03:39 -06005977 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005978 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005979 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005980 version = buf;
5981}
5982
John Kessenicha372a3e2017-11-02 22:32:14 -06005983// For low-order part of the generator's magic number. Bump up
5984// when there is a change in the style (e.g., if SSA form changes,
5985// or a different instruction sequence to do something gets used).
5986int GetSpirvGeneratorVersion()
5987{
John Kessenichc72e5932017-12-11 08:24:06 -07005988 return 3;
John Kessenicha372a3e2017-11-02 22:32:14 -06005989}
5990
John Kessenich140f3df2015-06-26 16:58:36 -06005991// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005992void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005993{
5994 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005995 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005996 if (out.fail())
5997 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005998 for (int i = 0; i < (int)spirv.size(); ++i) {
5999 unsigned int word = spirv[i];
6000 out.write((const char*)&word, 4);
6001 }
6002 out.close();
6003}
6004
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006005// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08006006void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006007{
6008 std::ofstream out;
6009 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07006010 if (out.fail())
6011 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006012 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08006013 if (varName != nullptr) {
6014 out << "\t #pragma once" << std::endl;
6015 out << "const uint32_t " << varName << "[] = {" << std::endl;
6016 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006017 const int WORDS_PER_LINE = 8;
6018 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
6019 out << "\t";
6020 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
6021 const unsigned int word = spirv[i + j];
6022 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
6023 if (i + j + 1 < (int)spirv.size()) {
6024 out << ",";
6025 }
6026 }
6027 out << std::endl;
6028 }
Flavio15017db2017-02-15 14:29:33 -08006029 if (varName != nullptr) {
6030 out << "};";
6031 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006032 out.close();
6033}
6034
GregFcd1f1692017-09-21 18:40:22 -06006035#ifdef ENABLE_OPT
6036void errHandler(const std::string& str) {
6037 std::cerr << str << std::endl;
6038}
6039#endif
6040
John Kessenich140f3df2015-06-26 16:58:36 -06006041//
6042// Set up the glslang traversal
6043//
John Kessenich121853f2017-05-31 17:11:16 -06006044void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006045{
Lei Zhang17535f72016-05-04 15:55:59 -04006046 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006047 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006048}
6049
John Kessenich121853f2017-05-31 17:11:16 -06006050void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6051 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006052{
John Kessenich140f3df2015-06-26 16:58:36 -06006053 TIntermNode* root = intermediate.getTreeRoot();
6054
6055 if (root == 0)
6056 return;
6057
John Kessenich121853f2017-05-31 17:11:16 -06006058 glslang::SpvOptions defaultOptions;
6059 if (options == nullptr)
6060 options = &defaultOptions;
6061
John Kessenich140f3df2015-06-26 16:58:36 -06006062 glslang::GetThreadPoolAllocator().push();
6063
John Kessenich121853f2017-05-31 17:11:16 -06006064 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006065 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006066 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006067 it.dumpSpv(spirv);
6068
GregFcd1f1692017-09-21 18:40:22 -06006069#ifdef ENABLE_OPT
6070 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6071 // eg. forward and remove memory writes of opaque types.
6072 if ((intermediate.getSource() == EShSourceHlsl ||
6073 options->optimizeSize) &&
6074 !options->disableOptimizer) {
6075 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6076
6077 spvtools::Optimizer optimizer(target_env);
6078 optimizer.SetMessageConsumer([](spv_message_level_t level,
6079 const char* source,
6080 const spv_position_t& position,
6081 const char* message) {
6082 std::cerr << StringifyMessage(level, source, position, message)
6083 << std::endl;
6084 });
6085
6086 optimizer.RegisterPass(CreateInlineExhaustivePass());
6087 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
6088 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
6089 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
6090 optimizer.RegisterPass(CreateInsertExtractElimPass());
6091 optimizer.RegisterPass(CreateAggressiveDCEPass());
6092 optimizer.RegisterPass(CreateDeadBranchElimPass());
GregFcc80d802017-10-23 16:48:42 -06006093 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06006094 optimizer.RegisterPass(CreateBlockMergePass());
6095 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
6096 optimizer.RegisterPass(CreateInsertExtractElimPass());
6097 optimizer.RegisterPass(CreateAggressiveDCEPass());
6098 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
6099 // if (options->optimizeSize)
6100 // optimizer.RegisterPass(CreateCommonUniformElimPass());
6101
6102 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
6103 return;
6104
6105 // Remove dead module-level objects: functions, types, vars
6106 // TODO(greg-lunarg): Switch to spirv-opt versions when available
6107 spv::spirvbin_t Remapper(0);
6108 Remapper.registerErrorHandler(errHandler);
6109 Remapper.remap(spirv, spv::spirvbin_t::DCE_ALL);
6110 }
6111#endif
6112
John Kessenich140f3df2015-06-26 16:58:36 -06006113 glslang::GetThreadPoolAllocator().pop();
6114}
6115
6116}; // end namespace glslang