blob: a0a1c834599bfcff6c088ba134113cf2aea6dfd8 [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"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080050#ifdef NV_EXTENSIONS
51 #include "GLSL.ext.NV.h"
52#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
GregFcd1f1692017-09-21 18:40:22 -060055#ifdef ENABLE_OPT
56 #include "spirv-tools/optimizer.hpp"
57 #include "message.h"
58 #include "SPVRemapper.h"
59#endif
60
61#ifdef ENABLE_OPT
62using namespace spvtools;
63#endif
64
John Kessenich140f3df2015-06-26 16:58:36 -060065// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020066#include "../glslang/MachineIndependent/localintermediate.h"
67#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060068#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050069#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060070
John Kessenich140f3df2015-06-26 16:58:36 -060071#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050072#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040073#include <list>
74#include <map>
75#include <stack>
76#include <string>
77#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060078
79namespace {
80
John Kessenich55e7d112015-11-15 21:33:39 -070081// For low-order part of the generator's magic number. Bump up
82// when there is a change in the style (e.g., if SSA form changes,
83// or a different instruction sequence to do something gets used).
84const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060085
qining4c912612016-04-01 10:35:16 -040086namespace {
87class SpecConstantOpModeGuard {
88public:
89 SpecConstantOpModeGuard(spv::Builder* builder)
90 : builder_(builder) {
91 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040092 }
93 ~SpecConstantOpModeGuard() {
94 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
95 : builder_->setToNormalCodeGenMode();
96 }
qining40887662016-04-03 22:20:42 -040097 void turnOnSpecConstantOpMode() {
98 builder_->setToSpecConstCodeGenMode();
99 }
qining4c912612016-04-01 10:35:16 -0400100
101private:
102 spv::Builder* builder_;
103 bool previous_flag_;
104};
105}
106
John Kessenich140f3df2015-06-26 16:58:36 -0600107//
108// The main holder of information for translating glslang to SPIR-V.
109//
110// Derives from the AST walking base class.
111//
112class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
113public:
John Kessenich121853f2017-05-31 17:11:16 -0600114 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger, glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700115 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600116
117 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
118 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
119 void visitConstantUnion(glslang::TIntermConstantUnion*);
120 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
121 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
122 void visitSymbol(glslang::TIntermSymbol* symbol);
123 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
124 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
125 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
126
John Kessenichfca82622016-11-26 13:23:20 -0700127 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700128 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600129
130protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800131 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800132 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100133 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700134 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
Rex Xu57e65922017-07-04 23:23:40 +0800135 spv::SelectionControlMask TranslateSelectionControl(glslang::TSelectionControl) const;
steve-lunargf1709e72017-05-02 20:14:50 -0600136 spv::LoopControlMask TranslateLoopControl(glslang::TLoopControl) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600137 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600138 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
139 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600140 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
141 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
142 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600143 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700144 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600145 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600146 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
147 glslang::TLayoutPacking, const glslang::TQualifier&);
148 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
149 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700150 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700151 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800152 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600153 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700154 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700155 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
156 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
157 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 +0100158 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600159
John Kessenich6fccb3c2016-09-19 16:01:41 -0600160 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600161 void makeFunctions(const glslang::TIntermSequence&);
162 void makeGlobalInitializers(const glslang::TIntermSequence&);
163 void visitFunctions(const glslang::TIntermSequence&);
164 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800165 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600166 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
167 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600168 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
169
qining25262b32016-05-06 17:25:16 -0400170 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
171 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
172 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800173 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800174 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600175 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800176 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800177 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800178 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600179 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800180 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600181 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
182 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700183 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600184 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700185 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400186 spv::Id createSpvConstant(const glslang::TIntermTyped&);
187 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600188 bool isTrivialLeaf(const glslang::TIntermTyped* node);
189 bool isTrivial(const glslang::TIntermTyped* node);
190 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800191 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600192
John Kessenich121853f2017-05-31 17:11:16 -0600193 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600194 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600195 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700196 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600197 int sequenceDepth;
198
Lei Zhang17535f72016-05-04 15:55:59 -0400199 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400200
John Kessenich140f3df2015-06-26 16:58:36 -0600201 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
202 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700203 bool inEntryPoint;
204 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700205 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 -0700206 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600207 const glslang::TIntermediate* glslangIntermediate;
208 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800209 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600210
John Kessenich2f273362015-07-18 22:34:27 -0600211 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600212 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600213 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700214 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600215 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 -0600216 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600217};
218
219//
220// Helper functions for translating glslang representations to SPIR-V enumerants.
221//
222
223// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700224spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600225{
John Kessenich66e2faf2016-03-12 18:34:36 -0700226 switch (source) {
227 case glslang::EShSourceGlsl:
228 switch (profile) {
229 case ENoProfile:
230 case ECoreProfile:
231 case ECompatibilityProfile:
232 return spv::SourceLanguageGLSL;
233 case EEsProfile:
234 return spv::SourceLanguageESSL;
235 default:
236 return spv::SourceLanguageUnknown;
237 }
238 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600239 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600240 default:
241 return spv::SourceLanguageUnknown;
242 }
243}
244
245// Translate glslang language (stage) to SPIR-V execution model.
246spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
247{
248 switch (stage) {
249 case EShLangVertex: return spv::ExecutionModelVertex;
250 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
251 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
252 case EShLangGeometry: return spv::ExecutionModelGeometry;
253 case EShLangFragment: return spv::ExecutionModelFragment;
254 case EShLangCompute: return spv::ExecutionModelGLCompute;
255 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700256 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600257 return spv::ExecutionModelFragment;
258 }
259}
260
John Kessenich140f3df2015-06-26 16:58:36 -0600261// Translate glslang sampler type to SPIR-V dimensionality.
262spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
263{
264 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700265 case glslang::Esd1D: return spv::Dim1D;
266 case glslang::Esd2D: return spv::Dim2D;
267 case glslang::Esd3D: return spv::Dim3D;
268 case glslang::EsdCube: return spv::DimCube;
269 case glslang::EsdRect: return spv::DimRect;
270 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700271 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600272 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700273 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600274 return spv::Dim2D;
275 }
276}
277
John Kessenichf6640762016-08-01 19:44:00 -0600278// Translate glslang precision to SPIR-V precision decorations.
279spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600280{
John Kessenichf6640762016-08-01 19:44:00 -0600281 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700282 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600283 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600284 default:
285 return spv::NoPrecision;
286 }
287}
288
John Kessenichf6640762016-08-01 19:44:00 -0600289// Translate glslang type to SPIR-V precision decorations.
290spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
291{
292 return TranslatePrecisionDecoration(type.getQualifier().precision);
293}
294
John Kessenich140f3df2015-06-26 16:58:36 -0600295// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600296spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600297{
298 if (type.getBasicType() == glslang::EbtBlock) {
299 switch (type.getQualifier().storage) {
300 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600301 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600302 case glslang::EvqVaryingIn: return spv::DecorationBlock;
303 case glslang::EvqVaryingOut: return spv::DecorationBlock;
304 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700305 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600306 break;
307 }
308 }
309
John Kessenich4016e382016-07-15 11:53:56 -0600310 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600311}
312
Rex Xu1da878f2016-02-21 20:59:01 +0800313// Translate glslang type to SPIR-V memory decorations.
314void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
315{
316 if (qualifier.coherent)
317 memory.push_back(spv::DecorationCoherent);
318 if (qualifier.volatil)
319 memory.push_back(spv::DecorationVolatile);
320 if (qualifier.restrict)
321 memory.push_back(spv::DecorationRestrict);
322 if (qualifier.readonly)
323 memory.push_back(spv::DecorationNonWritable);
324 if (qualifier.writeonly)
325 memory.push_back(spv::DecorationNonReadable);
326}
327
John Kessenich140f3df2015-06-26 16:58:36 -0600328// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700329spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600330{
331 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700332 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600333 case glslang::ElmRowMajor:
334 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700335 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600336 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700337 default:
338 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600339 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600340 }
341 } else {
342 switch (type.getBasicType()) {
343 default:
John Kessenich4016e382016-07-15 11:53:56 -0600344 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600345 break;
346 case glslang::EbtBlock:
347 switch (type.getQualifier().storage) {
348 case glslang::EvqUniform:
349 case glslang::EvqBuffer:
350 switch (type.getQualifier().layoutPacking) {
351 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600352 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
353 default:
John Kessenich4016e382016-07-15 11:53:56 -0600354 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600355 }
356 case glslang::EvqVaryingIn:
357 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700358 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600359 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600360 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700361 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600362 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600363 }
364 }
365 }
366}
367
368// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600369// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700370// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800371spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600372{
Rex Xubbceed72016-05-21 09:40:44 +0800373 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700374 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600375 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800376 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700377 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700378 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600379 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800380#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800381 else if (qualifier.explicitInterp) {
382 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800383 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800384 }
Rex Xu9d93a232016-05-05 12:30:44 +0800385#endif
Rex Xubbceed72016-05-21 09:40:44 +0800386 else
John Kessenich4016e382016-07-15 11:53:56 -0600387 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800388}
389
390// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600391// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800392// should be applied.
393spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
394{
395 if (qualifier.patch)
396 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700397 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600398 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700399 else if (qualifier.sample) {
400 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600401 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700402 } else
John Kessenich4016e382016-07-15 11:53:56 -0600403 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600404}
405
John Kessenich92187592016-02-01 13:45:25 -0700406// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700407spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600408{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700409 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600410 return spv::DecorationInvariant;
411 else
John Kessenich4016e382016-07-15 11:53:56 -0600412 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600413}
414
qining9220dbb2016-05-04 17:34:38 -0400415// If glslang type is noContraction, return SPIR-V NoContraction decoration.
416spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
417{
418 if (qualifier.noContraction)
419 return spv::DecorationNoContraction;
420 else
John Kessenich4016e382016-07-15 11:53:56 -0600421 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400422}
423
David Netoa901ffe2016-06-08 14:11:40 +0100424// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
425// associated capabilities when required. For some built-in variables, a capability
426// is generated only when using the variable in an executable instruction, but not when
427// just declaring a struct member variable with it. This is true for PointSize,
428// ClipDistance, and CullDistance.
429spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600430{
431 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700432 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600433 // Defer adding the capability until the built-in is actually used.
434 if (! memberDeclaration) {
435 switch (glslangIntermediate->getStage()) {
436 case EShLangGeometry:
437 builder.addCapability(spv::CapabilityGeometryPointSize);
438 break;
439 case EShLangTessControl:
440 case EShLangTessEvaluation:
441 builder.addCapability(spv::CapabilityTessellationPointSize);
442 break;
443 default:
444 break;
445 }
John Kessenich92187592016-02-01 13:45:25 -0700446 }
447 return spv::BuiltInPointSize;
448
John Kessenichebb50532016-05-16 19:22:05 -0600449 // These *Distance capabilities logically belong here, but if the member is declared and
450 // then never used, consumers of SPIR-V prefer the capability not be declared.
451 // They are now generated when used, rather than here when declared.
452 // Potentially, the specification should be more clear what the minimum
453 // use needed is to trigger the capability.
454 //
John Kessenich92187592016-02-01 13:45:25 -0700455 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100456 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800457 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700458 return spv::BuiltInClipDistance;
459
460 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100461 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800462 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700463 return spv::BuiltInCullDistance;
464
465 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600466 builder.addCapability(spv::CapabilityMultiViewport);
467 if (glslangIntermediate->getStage() == EShLangVertex ||
468 glslangIntermediate->getStage() == EShLangTessControl ||
469 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800470
John Kessenichba6a3c22017-09-13 13:22:50 -0600471 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
472 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800473 }
John Kessenich92187592016-02-01 13:45:25 -0700474 return spv::BuiltInViewportIndex;
475
John Kessenich5e801132016-02-15 11:09:46 -0700476 case glslang::EbvSampleId:
477 builder.addCapability(spv::CapabilitySampleRateShading);
478 return spv::BuiltInSampleId;
479
480 case glslang::EbvSamplePosition:
481 builder.addCapability(spv::CapabilitySampleRateShading);
482 return spv::BuiltInSamplePosition;
483
484 case glslang::EbvSampleMask:
485 builder.addCapability(spv::CapabilitySampleRateShading);
486 return spv::BuiltInSampleMask;
487
John Kessenich78a45572016-07-08 14:05:15 -0600488 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600489 builder.addCapability(spv::CapabilityGeometry);
490 if (glslangIntermediate->getStage() == EShLangVertex ||
491 glslangIntermediate->getStage() == EShLangTessControl ||
492 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800493
John Kessenichba6a3c22017-09-13 13:22:50 -0600494 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
495 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800496 }
John Kessenich78a45572016-07-08 14:05:15 -0600497 return spv::BuiltInLayer;
498
John Kessenich140f3df2015-06-26 16:58:36 -0600499 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600500 case glslang::EbvVertexId: return spv::BuiltInVertexId;
501 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700502 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
503 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800504
John Kessenichda581a22015-10-14 14:10:30 -0600505 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800506 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
507 builder.addCapability(spv::CapabilityDrawParameters);
508 return spv::BuiltInBaseVertex;
509
John Kessenichda581a22015-10-14 14:10:30 -0600510 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800511 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
512 builder.addCapability(spv::CapabilityDrawParameters);
513 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200514
John Kessenichda581a22015-10-14 14:10:30 -0600515 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800516 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
517 builder.addCapability(spv::CapabilityDrawParameters);
518 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200519
520 case glslang::EbvPrimitiveId:
521 if (glslangIntermediate->getStage() == EShLangFragment)
522 builder.addCapability(spv::CapabilityGeometry);
523 return spv::BuiltInPrimitiveId;
524
Rex Xu37cdcee2017-06-29 17:46:34 +0800525 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800526 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
527 builder.addCapability(spv::CapabilityStencilExportEXT);
528 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800529
John Kessenich140f3df2015-06-26 16:58:36 -0600530 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600531 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
532 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
533 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
534 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
535 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
536 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
537 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600538 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
539 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
540 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
541 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
542 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
543 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
544 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
545 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800546
Rex Xu574ab042016-04-14 16:53:07 +0800547 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800548 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800549 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
550 return spv::BuiltInSubgroupSize;
551
Rex Xu574ab042016-04-14 16:53:07 +0800552 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800553 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800554 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
555 return spv::BuiltInSubgroupLocalInvocationId;
556
Rex Xu574ab042016-04-14 16:53:07 +0800557 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800558 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
559 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
560 return spv::BuiltInSubgroupEqMaskKHR;
561
Rex Xu574ab042016-04-14 16:53:07 +0800562 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800563 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
564 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
565 return spv::BuiltInSubgroupGeMaskKHR;
566
Rex Xu574ab042016-04-14 16:53:07 +0800567 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800568 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
569 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
570 return spv::BuiltInSubgroupGtMaskKHR;
571
Rex Xu574ab042016-04-14 16:53:07 +0800572 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800573 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
574 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
575 return spv::BuiltInSubgroupLeMaskKHR;
576
Rex Xu574ab042016-04-14 16:53:07 +0800577 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800578 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
579 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
580 return spv::BuiltInSubgroupLtMaskKHR;
581
Rex Xu9d93a232016-05-05 12:30:44 +0800582#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800583 case glslang::EbvBaryCoordNoPersp:
584 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
585 return spv::BuiltInBaryCoordNoPerspAMD;
586
587 case glslang::EbvBaryCoordNoPerspCentroid:
588 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
589 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
590
591 case glslang::EbvBaryCoordNoPerspSample:
592 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
593 return spv::BuiltInBaryCoordNoPerspSampleAMD;
594
595 case glslang::EbvBaryCoordSmooth:
596 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
597 return spv::BuiltInBaryCoordSmoothAMD;
598
599 case glslang::EbvBaryCoordSmoothCentroid:
600 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
601 return spv::BuiltInBaryCoordSmoothCentroidAMD;
602
603 case glslang::EbvBaryCoordSmoothSample:
604 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
605 return spv::BuiltInBaryCoordSmoothSampleAMD;
606
607 case glslang::EbvBaryCoordPullModel:
608 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
609 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800610#endif
chaoc771d89f2017-01-13 01:10:53 -0800611
John Kessenich6c8aaac2017-02-27 01:20:51 -0700612 case glslang::EbvDeviceIndex:
613 builder.addExtension(spv::E_SPV_KHR_device_group);
614 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700615 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700616
617 case glslang::EbvViewIndex:
618 builder.addExtension(spv::E_SPV_KHR_multiview);
619 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700620 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700621
chaoc771d89f2017-01-13 01:10:53 -0800622#ifdef NV_EXTENSIONS
623 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800624 if (!memberDeclaration) {
625 builder.addExtension(spv::E_SPV_NV_viewport_array2);
626 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
627 }
chaoc771d89f2017-01-13 01:10:53 -0800628 return spv::BuiltInViewportMaskNV;
629 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800630 if (!memberDeclaration) {
631 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
632 builder.addCapability(spv::CapabilityShaderStereoViewNV);
633 }
chaoc771d89f2017-01-13 01:10:53 -0800634 return spv::BuiltInSecondaryPositionNV;
635 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800636 if (!memberDeclaration) {
637 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
638 builder.addCapability(spv::CapabilityShaderStereoViewNV);
639 }
chaoc771d89f2017-01-13 01:10:53 -0800640 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800641 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800642 if (!memberDeclaration) {
643 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
644 builder.addCapability(spv::CapabilityPerViewAttributesNV);
645 }
chaocdf3956c2017-02-14 14:52:34 -0800646 return spv::BuiltInPositionPerViewNV;
647 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800648 if (!memberDeclaration) {
649 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
650 builder.addCapability(spv::CapabilityPerViewAttributesNV);
651 }
chaocdf3956c2017-02-14 14:52:34 -0800652 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800653#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800654 default:
655 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600656 }
657}
658
Rex Xufc618912015-09-09 16:42:49 +0800659// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700660spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800661{
662 assert(type.getBasicType() == glslang::EbtSampler);
663
John Kessenich5d0fa972016-02-15 11:57:00 -0700664 // Check for capabilities
665 switch (type.getQualifier().layoutFormat) {
666 case glslang::ElfRg32f:
667 case glslang::ElfRg16f:
668 case glslang::ElfR11fG11fB10f:
669 case glslang::ElfR16f:
670 case glslang::ElfRgba16:
671 case glslang::ElfRgb10A2:
672 case glslang::ElfRg16:
673 case glslang::ElfRg8:
674 case glslang::ElfR16:
675 case glslang::ElfR8:
676 case glslang::ElfRgba16Snorm:
677 case glslang::ElfRg16Snorm:
678 case glslang::ElfRg8Snorm:
679 case glslang::ElfR16Snorm:
680 case glslang::ElfR8Snorm:
681
682 case glslang::ElfRg32i:
683 case glslang::ElfRg16i:
684 case glslang::ElfRg8i:
685 case glslang::ElfR16i:
686 case glslang::ElfR8i:
687
688 case glslang::ElfRgb10a2ui:
689 case glslang::ElfRg32ui:
690 case glslang::ElfRg16ui:
691 case glslang::ElfRg8ui:
692 case glslang::ElfR16ui:
693 case glslang::ElfR8ui:
694 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
695 break;
696
697 default:
698 break;
699 }
700
701 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800702 switch (type.getQualifier().layoutFormat) {
703 case glslang::ElfNone: return spv::ImageFormatUnknown;
704 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
705 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
706 case glslang::ElfR32f: return spv::ImageFormatR32f;
707 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
708 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
709 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
710 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
711 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
712 case glslang::ElfR16f: return spv::ImageFormatR16f;
713 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
714 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
715 case glslang::ElfRg16: return spv::ImageFormatRg16;
716 case glslang::ElfRg8: return spv::ImageFormatRg8;
717 case glslang::ElfR16: return spv::ImageFormatR16;
718 case glslang::ElfR8: return spv::ImageFormatR8;
719 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
720 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
721 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
722 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
723 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
724 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
725 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
726 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
727 case glslang::ElfR32i: return spv::ImageFormatR32i;
728 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
729 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
730 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
731 case glslang::ElfR16i: return spv::ImageFormatR16i;
732 case glslang::ElfR8i: return spv::ImageFormatR8i;
733 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
734 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
735 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
736 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
737 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
738 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
739 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
740 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
741 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
742 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600743 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800744 }
745}
746
Rex Xu57e65922017-07-04 23:23:40 +0800747spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(glslang::TSelectionControl selectionControl) const
748{
749 switch (selectionControl) {
750 case glslang::ESelectionControlNone: return spv::SelectionControlMaskNone;
751 case glslang::ESelectionControlFlatten: return spv::SelectionControlFlattenMask;
752 case glslang::ESelectionControlDontFlatten: return spv::SelectionControlDontFlattenMask;
753 default: return spv::SelectionControlMaskNone;
754 }
755}
756
steve-lunargf1709e72017-05-02 20:14:50 -0600757spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
758{
759 switch (loopControl) {
760 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
761 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
762 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
763 // TODO: DependencyInfinite
764 // TODO: DependencyLength
765 default: return spv::LoopControlMaskNone;
766 }
767}
768
John Kessenicha5c5fb62017-05-05 05:09:58 -0600769// Translate glslang type to SPIR-V storage class.
770spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
771{
772 if (type.getQualifier().isPipeInput())
773 return spv::StorageClassInput;
774 else if (type.getQualifier().isPipeOutput())
775 return spv::StorageClassOutput;
776 else if (type.getBasicType() == glslang::EbtAtomicUint)
777 return spv::StorageClassAtomicCounter;
778 else if (type.containsOpaque())
779 return spv::StorageClassUniformConstant;
780 else if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
781 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
782 return spv::StorageClassStorageBuffer;
783 } else if (type.getQualifier().isUniformOrBuffer()) {
784 if (type.getQualifier().layoutPushConstant)
785 return spv::StorageClassPushConstant;
786 if (type.getBasicType() == glslang::EbtBlock)
787 return spv::StorageClassUniform;
788 else
789 return spv::StorageClassUniformConstant;
790 } else {
791 switch (type.getQualifier().storage) {
792 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
793 case glslang::EvqGlobal: return spv::StorageClassPrivate;
794 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
795 case glslang::EvqTemporary: return spv::StorageClassFunction;
796 default:
797 assert(0);
798 return spv::StorageClassFunction;
799 }
800 }
801}
802
qining25262b32016-05-06 17:25:16 -0400803// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700804// descriptor set.
805bool IsDescriptorResource(const glslang::TType& type)
806{
John Kessenichf7497e22016-03-08 21:36:22 -0700807 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700808 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700809 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700810
811 // non block...
812 // basically samplerXXX/subpass/sampler/texture are all included
813 // if they are the global-scope-class, not the function parameter
814 // (or local, if they ever exist) class.
815 if (type.getBasicType() == glslang::EbtSampler)
816 return type.getQualifier().isUniformOrBuffer();
817
818 // None of the above.
819 return false;
820}
821
John Kesseniche0b6cad2015-12-24 10:30:13 -0700822void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
823{
824 if (child.layoutMatrix == glslang::ElmNone)
825 child.layoutMatrix = parent.layoutMatrix;
826
827 if (parent.invariant)
828 child.invariant = true;
829 if (parent.nopersp)
830 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800831#ifdef AMD_EXTENSIONS
832 if (parent.explicitInterp)
833 child.explicitInterp = true;
834#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700835 if (parent.flat)
836 child.flat = true;
837 if (parent.centroid)
838 child.centroid = true;
839 if (parent.patch)
840 child.patch = true;
841 if (parent.sample)
842 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800843 if (parent.coherent)
844 child.coherent = true;
845 if (parent.volatil)
846 child.volatil = true;
847 if (parent.restrict)
848 child.restrict = true;
849 if (parent.readonly)
850 child.readonly = true;
851 if (parent.writeonly)
852 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700853}
854
John Kessenichf2b7f332016-09-01 17:05:23 -0600855bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700856{
John Kessenich7b9fa252016-01-21 18:56:57 -0700857 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600858 // - struct members might inherit from a struct declaration
859 // (note that non-block structs don't explicitly inherit,
860 // only implicitly, meaning no decoration involved)
861 // - affect decorations on the struct members
862 // (note smooth does not, and expecting something like volatile
863 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700864 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600865 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700866}
867
John Kessenich140f3df2015-06-26 16:58:36 -0600868//
869// Implement the TGlslangToSpvTraverser class.
870//
871
John Kessenich121853f2017-05-31 17:11:16 -0600872TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate,
873 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
874 : TIntermTraverser(true, false, true),
875 options(options),
876 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600877 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400878 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700879 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600880 glslangIntermediate(glslangIntermediate)
881{
882 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
883
884 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600885 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
886 glslangIntermediate->getVersion());
887
John Kessenich121853f2017-05-31 17:11:16 -0600888 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600889 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600890 builder.setSourceFile(glslangIntermediate->getSourceFile());
891
892 // Set the source shader's text. If for SPV version 1.0, include
893 // a preamble in comments stating the OpModuleProcessed instructions.
894 // Otherwise, emit those as actual instructions.
895 std::string text;
896 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
897 for (int p = 0; p < (int)processes.size(); ++p) {
898 if (glslangIntermediate->getSpv().spv < 0x00010100) {
899 text.append("// OpModuleProcessed ");
900 text.append(processes[p]);
901 text.append("\n");
902 } else
903 builder.addModuleProcessed(processes[p]);
904 }
905 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
906 text.append("#line 1\n");
907 text.append(glslangIntermediate->getSourceText());
908 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600909 }
John Kessenich140f3df2015-06-26 16:58:36 -0600910 stdBuiltins = builder.import("GLSL.std.450");
911 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600912 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
913 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600914
915 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600916 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
917 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600918 builder.addSourceExtension(it->c_str());
919
920 // Add the top-level modes for this shader.
921
John Kessenich92187592016-02-01 13:45:25 -0700922 if (glslangIntermediate->getXfbMode()) {
923 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600924 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700925 }
John Kessenich140f3df2015-06-26 16:58:36 -0600926
927 unsigned int mode;
928 switch (glslangIntermediate->getStage()) {
929 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600930 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600931 break;
932
steve-lunarge7412492017-03-23 11:56:07 -0600933 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600934 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600935 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600936
steve-lunarge7412492017-03-23 11:56:07 -0600937 glslang::TLayoutGeometry primitive;
938
939 if (glslangIntermediate->getStage() == EShLangTessControl) {
940 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
941 primitive = glslangIntermediate->getOutputPrimitive();
942 } else {
943 primitive = glslangIntermediate->getInputPrimitive();
944 }
945
946 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700947 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
948 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
949 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600950 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600951 }
John Kessenich4016e382016-07-15 11:53:56 -0600952 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600953 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
954
John Kesseniche6903322015-10-13 16:29:02 -0600955 switch (glslangIntermediate->getVertexSpacing()) {
956 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
957 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
958 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600959 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600960 }
John Kessenich4016e382016-07-15 11:53:56 -0600961 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600962 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
963
964 switch (glslangIntermediate->getVertexOrder()) {
965 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
966 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600967 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600968 }
John Kessenich4016e382016-07-15 11:53:56 -0600969 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600970 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
971
972 if (glslangIntermediate->getPointMode())
973 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600974 break;
975
976 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600977 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600978 switch (glslangIntermediate->getInputPrimitive()) {
979 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
980 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
981 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700982 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600983 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600984 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600985 }
John Kessenich4016e382016-07-15 11:53:56 -0600986 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600987 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600988
John Kessenich140f3df2015-06-26 16:58:36 -0600989 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
990
991 switch (glslangIntermediate->getOutputPrimitive()) {
992 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
993 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
994 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600995 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600996 }
John Kessenich4016e382016-07-15 11:53:56 -0600997 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600998 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
999 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1000 break;
1001
1002 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001003 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001004 if (glslangIntermediate->getPixelCenterInteger())
1005 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001006
John Kessenich140f3df2015-06-26 16:58:36 -06001007 if (glslangIntermediate->getOriginUpperLeft())
1008 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001009 else
1010 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001011
1012 if (glslangIntermediate->getEarlyFragmentTests())
1013 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1014
chaocc1204522017-06-30 17:14:30 -07001015 if (glslangIntermediate->getPostDepthCoverage()) {
1016 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1017 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1018 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1019 }
1020
John Kesseniche6903322015-10-13 16:29:02 -06001021 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001022 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1023 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001024 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001025 }
John Kessenich4016e382016-07-15 11:53:56 -06001026 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001027 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1028
1029 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1030 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001031 break;
1032
1033 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001034 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001035 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1036 glslangIntermediate->getLocalSize(1),
1037 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001038 break;
1039
1040 default:
1041 break;
1042 }
John Kessenich140f3df2015-06-26 16:58:36 -06001043}
1044
John Kessenichfca82622016-11-26 13:23:20 -07001045// Finish creating SPV, after the traversal is complete.
1046void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001047{
John Kessenich517fe7a2016-11-26 13:31:47 -07001048 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001049 builder.setBuildPoint(shaderEntry->getLastBlock());
1050 builder.leaveFunction();
1051 }
1052
John Kessenich7ba63412015-12-20 17:37:07 -07001053 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001054 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1055 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001056
qiningda397332016-03-09 19:54:03 -05001057 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001058}
1059
John Kessenichfca82622016-11-26 13:23:20 -07001060// Write the SPV into 'out'.
1061void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001062{
John Kessenichfca82622016-11-26 13:23:20 -07001063 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001064}
1065
1066//
1067// Implement the traversal functions.
1068//
1069// Return true from interior nodes to have the external traversal
1070// continue on to children. Return false if children were
1071// already processed.
1072//
1073
1074//
qining25262b32016-05-06 17:25:16 -04001075// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001076// - uniform/input reads
1077// - output writes
1078// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1079// - something simple that degenerates into the last bullet
1080//
1081void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1082{
qining75d1d802016-04-06 14:42:01 -04001083 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1084 if (symbol->getType().getQualifier().isSpecConstant())
1085 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1086
John Kessenich140f3df2015-06-26 16:58:36 -06001087 // getSymbolId() will set up all the IO decorations on the first call.
1088 // Formal function parameters were mapped during makeFunctions().
1089 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001090
1091 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1092 if (builder.isPointer(id)) {
1093 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001094 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1095 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1096 iOSet.insert(id);
1097 }
John Kessenich7ba63412015-12-20 17:37:07 -07001098 }
1099
1100 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001101 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001102 // Prepare to generate code for the access
1103
1104 // L-value chains will be computed left to right. We're on the symbol now,
1105 // which is the left-most part of the access chain, so now is "clear" time,
1106 // followed by setting the base.
1107 builder.clearAccessChain();
1108
1109 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001110 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001111 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001112 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001113 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001114 // These are also pure R-values.
1115 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001116 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001117 builder.setAccessChainRValue(id);
1118 else
1119 builder.setAccessChainLValue(id);
1120 }
1121}
1122
1123bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1124{
John Kesseniche485c7a2017-05-31 18:50:53 -06001125 builder.setLine(node->getLoc().line);
1126
qining40887662016-04-03 22:20:42 -04001127 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1128 if (node->getType().getQualifier().isSpecConstant())
1129 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1130
John Kessenich140f3df2015-06-26 16:58:36 -06001131 // First, handle special cases
1132 switch (node->getOp()) {
1133 case glslang::EOpAssign:
1134 case glslang::EOpAddAssign:
1135 case glslang::EOpSubAssign:
1136 case glslang::EOpMulAssign:
1137 case glslang::EOpVectorTimesMatrixAssign:
1138 case glslang::EOpVectorTimesScalarAssign:
1139 case glslang::EOpMatrixTimesScalarAssign:
1140 case glslang::EOpMatrixTimesMatrixAssign:
1141 case glslang::EOpDivAssign:
1142 case glslang::EOpModAssign:
1143 case glslang::EOpAndAssign:
1144 case glslang::EOpInclusiveOrAssign:
1145 case glslang::EOpExclusiveOrAssign:
1146 case glslang::EOpLeftShiftAssign:
1147 case glslang::EOpRightShiftAssign:
1148 // A bin-op assign "a += b" means the same thing as "a = a + b"
1149 // where a is evaluated before b. For a simple assignment, GLSL
1150 // says to evaluate the left before the right. So, always, left
1151 // node then right node.
1152 {
1153 // get the left l-value, save it away
1154 builder.clearAccessChain();
1155 node->getLeft()->traverse(this);
1156 spv::Builder::AccessChain lValue = builder.getAccessChain();
1157
1158 // evaluate the right
1159 builder.clearAccessChain();
1160 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001161 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001162
1163 if (node->getOp() != glslang::EOpAssign) {
1164 // the left is also an r-value
1165 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001166 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001167
1168 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001169 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001170 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001171 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1172 node->getType().getBasicType());
1173
1174 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001175 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001176 }
1177
1178 // store the result
1179 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001180 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001181
1182 // assignments are expressions having an rValue after they are evaluated...
1183 builder.clearAccessChain();
1184 builder.setAccessChainRValue(rValue);
1185 }
1186 return false;
1187 case glslang::EOpIndexDirect:
1188 case glslang::EOpIndexDirectStruct:
1189 {
1190 // Get the left part of the access chain.
1191 node->getLeft()->traverse(this);
1192
1193 // Add the next element in the chain
1194
David Netoa901ffe2016-06-08 14:11:40 +01001195 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001196 if (! node->getLeft()->getType().isArray() &&
1197 node->getLeft()->getType().isVector() &&
1198 node->getOp() == glslang::EOpIndexDirect) {
1199 // This is essentially a hard-coded vector swizzle of size 1,
1200 // so short circuit the access-chain stuff with a swizzle.
1201 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001202 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001203 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001204 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001205 int spvIndex = glslangIndex;
1206 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1207 node->getOp() == glslang::EOpIndexDirectStruct)
1208 {
1209 // This may be, e.g., an anonymous block-member selection, which generally need
1210 // index remapping due to hidden members in anonymous blocks.
1211 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1212 assert(remapper.size() > 0);
1213 spvIndex = remapper[glslangIndex];
1214 }
John Kessenichebb50532016-05-16 19:22:05 -06001215
David Netoa901ffe2016-06-08 14:11:40 +01001216 // normal case for indexing array or structure or block
1217 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1218
1219 // Add capabilities here for accessing PointSize and clip/cull distance.
1220 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001221 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001222 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001223 }
1224 }
1225 return false;
1226 case glslang::EOpIndexIndirect:
1227 {
1228 // Structure or array or vector indirection.
1229 // Will use native SPIR-V access-chain for struct and array indirection;
1230 // matrices are arrays of vectors, so will also work for a matrix.
1231 // Will use the access chain's 'component' for variable index into a vector.
1232
1233 // This adapter is building access chains left to right.
1234 // Set up the access chain to the left.
1235 node->getLeft()->traverse(this);
1236
1237 // save it so that computing the right side doesn't trash it
1238 spv::Builder::AccessChain partial = builder.getAccessChain();
1239
1240 // compute the next index in the chain
1241 builder.clearAccessChain();
1242 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001243 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001244
1245 // restore the saved access chain
1246 builder.setAccessChain(partial);
1247
1248 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001249 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001250 else
John Kessenichfa668da2015-09-13 14:46:30 -06001251 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001252 }
1253 return false;
1254 case glslang::EOpVectorSwizzle:
1255 {
1256 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001257 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001258 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001259 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001260 }
1261 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001262 case glslang::EOpMatrixSwizzle:
1263 logger->missingFunctionality("matrix swizzle");
1264 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001265 case glslang::EOpLogicalOr:
1266 case glslang::EOpLogicalAnd:
1267 {
1268
1269 // These may require short circuiting, but can sometimes be done as straight
1270 // binary operations. The right operand must be short circuited if it has
1271 // side effects, and should probably be if it is complex.
1272 if (isTrivial(node->getRight()->getAsTyped()))
1273 break; // handle below as a normal binary operation
1274 // otherwise, we need to do dynamic short circuiting on the right operand
1275 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1276 builder.clearAccessChain();
1277 builder.setAccessChainRValue(result);
1278 }
1279 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001280 default:
1281 break;
1282 }
1283
1284 // Assume generic binary op...
1285
John Kessenich32cfd492016-02-02 12:37:46 -07001286 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001287 builder.clearAccessChain();
1288 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001289 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001290
John Kessenich32cfd492016-02-02 12:37:46 -07001291 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001292 builder.clearAccessChain();
1293 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001294 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001295
John Kessenich32cfd492016-02-02 12:37:46 -07001296 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001297 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001298 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001299 convertGlslangToSpvType(node->getType()), left, right,
1300 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001301
John Kessenich50e57562015-12-21 21:21:11 -07001302 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001303 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001304 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001305 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001306 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001307 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001308 return false;
1309 }
John Kessenich140f3df2015-06-26 16:58:36 -06001310}
1311
1312bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1313{
John Kesseniche485c7a2017-05-31 18:50:53 -06001314 builder.setLine(node->getLoc().line);
1315
qining40887662016-04-03 22:20:42 -04001316 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1317 if (node->getType().getQualifier().isSpecConstant())
1318 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1319
John Kessenichfc51d282015-08-19 13:34:18 -06001320 spv::Id result = spv::NoResult;
1321
1322 // try texturing first
1323 result = createImageTextureFunctionCall(node);
1324 if (result != spv::NoResult) {
1325 builder.clearAccessChain();
1326 builder.setAccessChainRValue(result);
1327
1328 return false; // done with this node
1329 }
1330
1331 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001332
1333 if (node->getOp() == glslang::EOpArrayLength) {
1334 // Quite special; won't want to evaluate the operand.
1335
1336 // Normal .length() would have been constant folded by the front-end.
1337 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001338 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001339 assert(node->getOperand()->getType().isRuntimeSizedArray());
1340 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1341 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001342 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1343 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001344
1345 builder.clearAccessChain();
1346 builder.setAccessChainRValue(length);
1347
1348 return false;
1349 }
1350
John Kessenichfc51d282015-08-19 13:34:18 -06001351 // Start by evaluating the operand
1352
John Kessenich8c8505c2016-07-26 12:50:38 -06001353 // Does it need a swizzle inversion? If so, evaluation is inverted;
1354 // operate first on the swizzle base, then apply the swizzle.
1355 spv::Id invertedType = spv::NoType;
1356 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1357 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1358 invertedType = getInvertedSwizzleType(*node->getOperand());
1359
John Kessenich140f3df2015-06-26 16:58:36 -06001360 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001361 if (invertedType != spv::NoType)
1362 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1363 else
1364 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001365
Rex Xufc618912015-09-09 16:42:49 +08001366 spv::Id operand = spv::NoResult;
1367
1368 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1369 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001370 node->getOp() == glslang::EOpAtomicCounter ||
1371 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001372 operand = builder.accessChainGetLValue(); // Special case l-value operands
1373 else
John Kessenich32cfd492016-02-02 12:37:46 -07001374 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001375
John Kessenichf6640762016-08-01 19:44:00 -06001376 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001377 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001378
1379 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001380 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001381 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001382
1383 // if not, then possibly an operation
1384 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001385 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001386
1387 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001388 if (invertedType)
1389 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1390
John Kessenich140f3df2015-06-26 16:58:36 -06001391 builder.clearAccessChain();
1392 builder.setAccessChainRValue(result);
1393
1394 return false; // done with this node
1395 }
1396
1397 // it must be a special case, check...
1398 switch (node->getOp()) {
1399 case glslang::EOpPostIncrement:
1400 case glslang::EOpPostDecrement:
1401 case glslang::EOpPreIncrement:
1402 case glslang::EOpPreDecrement:
1403 {
1404 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001405 spv::Id one = 0;
1406 if (node->getBasicType() == glslang::EbtFloat)
1407 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001408 else if (node->getBasicType() == glslang::EbtDouble)
1409 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001410#ifdef AMD_EXTENSIONS
1411 else if (node->getBasicType() == glslang::EbtFloat16)
1412 one = builder.makeFloat16Constant(1.0F);
1413#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001414 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1415 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001416#ifdef AMD_EXTENSIONS
1417 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1418 one = builder.makeInt16Constant(1);
1419#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001420 else
1421 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001422 glslang::TOperator op;
1423 if (node->getOp() == glslang::EOpPreIncrement ||
1424 node->getOp() == glslang::EOpPostIncrement)
1425 op = glslang::EOpAdd;
1426 else
1427 op = glslang::EOpSub;
1428
John Kessenichf6640762016-08-01 19:44:00 -06001429 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001430 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001431 convertGlslangToSpvType(node->getType()), operand, one,
1432 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001433 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001434
1435 // The result of operation is always stored, but conditionally the
1436 // consumed result. The consumed result is always an r-value.
1437 builder.accessChainStore(result);
1438 builder.clearAccessChain();
1439 if (node->getOp() == glslang::EOpPreIncrement ||
1440 node->getOp() == glslang::EOpPreDecrement)
1441 builder.setAccessChainRValue(result);
1442 else
1443 builder.setAccessChainRValue(operand);
1444 }
1445
1446 return false;
1447
1448 case glslang::EOpEmitStreamVertex:
1449 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1450 return false;
1451 case glslang::EOpEndStreamPrimitive:
1452 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1453 return false;
1454
1455 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001456 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001457 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001458 }
John Kessenich140f3df2015-06-26 16:58:36 -06001459}
1460
1461bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1462{
qining27e04a02016-04-14 16:40:20 -04001463 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1464 if (node->getType().getQualifier().isSpecConstant())
1465 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1466
John Kessenichfc51d282015-08-19 13:34:18 -06001467 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001468 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1469 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001470
1471 // try texturing
1472 result = createImageTextureFunctionCall(node);
1473 if (result != spv::NoResult) {
1474 builder.clearAccessChain();
1475 builder.setAccessChainRValue(result);
1476
1477 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001478#ifdef AMD_EXTENSIONS
1479 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1480#else
John Kessenich56bab042015-09-16 10:54:31 -06001481 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001482#endif
Rex Xufc618912015-09-09 16:42:49 +08001483 // "imageStore" is a special case, which has no result
1484 return false;
1485 }
John Kessenichfc51d282015-08-19 13:34:18 -06001486
John Kessenich140f3df2015-06-26 16:58:36 -06001487 glslang::TOperator binOp = glslang::EOpNull;
1488 bool reduceComparison = true;
1489 bool isMatrix = false;
1490 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001491 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001492
1493 assert(node->getOp());
1494
John Kessenichf6640762016-08-01 19:44:00 -06001495 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001496
1497 switch (node->getOp()) {
1498 case glslang::EOpSequence:
1499 {
1500 if (preVisit)
1501 ++sequenceDepth;
1502 else
1503 --sequenceDepth;
1504
1505 if (sequenceDepth == 1) {
1506 // If this is the parent node of all the functions, we want to see them
1507 // early, so all call points have actual SPIR-V functions to reference.
1508 // In all cases, still let the traverser visit the children for us.
1509 makeFunctions(node->getAsAggregate()->getSequence());
1510
John Kessenich6fccb3c2016-09-19 16:01:41 -06001511 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001512 // anything else gets there, so visit out of order, doing them all now.
1513 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1514
John Kessenich6a60c2f2016-12-08 21:01:59 -07001515 // 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 -06001516 // so do them manually.
1517 visitFunctions(node->getAsAggregate()->getSequence());
1518
1519 return false;
1520 }
1521
1522 return true;
1523 }
1524 case glslang::EOpLinkerObjects:
1525 {
1526 if (visit == glslang::EvPreVisit)
1527 linkageOnly = true;
1528 else
1529 linkageOnly = false;
1530
1531 return true;
1532 }
1533 case glslang::EOpComma:
1534 {
1535 // processing from left to right naturally leaves the right-most
1536 // lying around in the access chain
1537 glslang::TIntermSequence& glslangOperands = node->getSequence();
1538 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1539 glslangOperands[i]->traverse(this);
1540
1541 return false;
1542 }
1543 case glslang::EOpFunction:
1544 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001545 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001546 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001547 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001548 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001549 } else {
1550 handleFunctionEntry(node);
1551 }
1552 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001553 if (inEntryPoint)
1554 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001555 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001556 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001557 }
1558
1559 return true;
1560 case glslang::EOpParameters:
1561 // Parameters will have been consumed by EOpFunction processing, but not
1562 // the body, so we still visited the function node's children, making this
1563 // child redundant.
1564 return false;
1565 case glslang::EOpFunctionCall:
1566 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001567 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001568 if (node->isUserDefined())
1569 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001570 // 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 -07001571 if (result) {
1572 builder.clearAccessChain();
1573 builder.setAccessChainRValue(result);
1574 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001575 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001576
1577 return false;
1578 }
1579 case glslang::EOpConstructMat2x2:
1580 case glslang::EOpConstructMat2x3:
1581 case glslang::EOpConstructMat2x4:
1582 case glslang::EOpConstructMat3x2:
1583 case glslang::EOpConstructMat3x3:
1584 case glslang::EOpConstructMat3x4:
1585 case glslang::EOpConstructMat4x2:
1586 case glslang::EOpConstructMat4x3:
1587 case glslang::EOpConstructMat4x4:
1588 case glslang::EOpConstructDMat2x2:
1589 case glslang::EOpConstructDMat2x3:
1590 case glslang::EOpConstructDMat2x4:
1591 case glslang::EOpConstructDMat3x2:
1592 case glslang::EOpConstructDMat3x3:
1593 case glslang::EOpConstructDMat3x4:
1594 case glslang::EOpConstructDMat4x2:
1595 case glslang::EOpConstructDMat4x3:
1596 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001597 case glslang::EOpConstructIMat2x2:
1598 case glslang::EOpConstructIMat2x3:
1599 case glslang::EOpConstructIMat2x4:
1600 case glslang::EOpConstructIMat3x2:
1601 case glslang::EOpConstructIMat3x3:
1602 case glslang::EOpConstructIMat3x4:
1603 case glslang::EOpConstructIMat4x2:
1604 case glslang::EOpConstructIMat4x3:
1605 case glslang::EOpConstructIMat4x4:
1606 case glslang::EOpConstructUMat2x2:
1607 case glslang::EOpConstructUMat2x3:
1608 case glslang::EOpConstructUMat2x4:
1609 case glslang::EOpConstructUMat3x2:
1610 case glslang::EOpConstructUMat3x3:
1611 case glslang::EOpConstructUMat3x4:
1612 case glslang::EOpConstructUMat4x2:
1613 case glslang::EOpConstructUMat4x3:
1614 case glslang::EOpConstructUMat4x4:
1615 case glslang::EOpConstructBMat2x2:
1616 case glslang::EOpConstructBMat2x3:
1617 case glslang::EOpConstructBMat2x4:
1618 case glslang::EOpConstructBMat3x2:
1619 case glslang::EOpConstructBMat3x3:
1620 case glslang::EOpConstructBMat3x4:
1621 case glslang::EOpConstructBMat4x2:
1622 case glslang::EOpConstructBMat4x3:
1623 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001624#ifdef AMD_EXTENSIONS
1625 case glslang::EOpConstructF16Mat2x2:
1626 case glslang::EOpConstructF16Mat2x3:
1627 case glslang::EOpConstructF16Mat2x4:
1628 case glslang::EOpConstructF16Mat3x2:
1629 case glslang::EOpConstructF16Mat3x3:
1630 case glslang::EOpConstructF16Mat3x4:
1631 case glslang::EOpConstructF16Mat4x2:
1632 case glslang::EOpConstructF16Mat4x3:
1633 case glslang::EOpConstructF16Mat4x4:
1634#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001635 isMatrix = true;
1636 // fall through
1637 case glslang::EOpConstructFloat:
1638 case glslang::EOpConstructVec2:
1639 case glslang::EOpConstructVec3:
1640 case glslang::EOpConstructVec4:
1641 case glslang::EOpConstructDouble:
1642 case glslang::EOpConstructDVec2:
1643 case glslang::EOpConstructDVec3:
1644 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001645#ifdef AMD_EXTENSIONS
1646 case glslang::EOpConstructFloat16:
1647 case glslang::EOpConstructF16Vec2:
1648 case glslang::EOpConstructF16Vec3:
1649 case glslang::EOpConstructF16Vec4:
1650#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001651 case glslang::EOpConstructBool:
1652 case glslang::EOpConstructBVec2:
1653 case glslang::EOpConstructBVec3:
1654 case glslang::EOpConstructBVec4:
1655 case glslang::EOpConstructInt:
1656 case glslang::EOpConstructIVec2:
1657 case glslang::EOpConstructIVec3:
1658 case glslang::EOpConstructIVec4:
1659 case glslang::EOpConstructUint:
1660 case glslang::EOpConstructUVec2:
1661 case glslang::EOpConstructUVec3:
1662 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001663 case glslang::EOpConstructInt64:
1664 case glslang::EOpConstructI64Vec2:
1665 case glslang::EOpConstructI64Vec3:
1666 case glslang::EOpConstructI64Vec4:
1667 case glslang::EOpConstructUint64:
1668 case glslang::EOpConstructU64Vec2:
1669 case glslang::EOpConstructU64Vec3:
1670 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001671#ifdef AMD_EXTENSIONS
1672 case glslang::EOpConstructInt16:
1673 case glslang::EOpConstructI16Vec2:
1674 case glslang::EOpConstructI16Vec3:
1675 case glslang::EOpConstructI16Vec4:
1676 case glslang::EOpConstructUint16:
1677 case glslang::EOpConstructU16Vec2:
1678 case glslang::EOpConstructU16Vec3:
1679 case glslang::EOpConstructU16Vec4:
1680#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001681 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001682 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001683 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001684 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001685 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001686 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001687 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001688 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001689 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001690 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001691 std::vector<spv::Id> constituents;
1692 for (int c = 0; c < (int)arguments.size(); ++c)
1693 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001694 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001695 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001696 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001697 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001698 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001699
1700 builder.clearAccessChain();
1701 builder.setAccessChainRValue(constructed);
1702
1703 return false;
1704 }
1705
1706 // These six are component-wise compares with component-wise results.
1707 // Forward on to createBinaryOperation(), requesting a vector result.
1708 case glslang::EOpLessThan:
1709 case glslang::EOpGreaterThan:
1710 case glslang::EOpLessThanEqual:
1711 case glslang::EOpGreaterThanEqual:
1712 case glslang::EOpVectorEqual:
1713 case glslang::EOpVectorNotEqual:
1714 {
1715 // Map the operation to a binary
1716 binOp = node->getOp();
1717 reduceComparison = false;
1718 switch (node->getOp()) {
1719 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1720 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1721 default: binOp = node->getOp(); break;
1722 }
1723
1724 break;
1725 }
1726 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001727 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001728 binOp = glslang::EOpMul;
1729 break;
1730 case glslang::EOpOuterProduct:
1731 // two vectors multiplied to make a matrix
1732 binOp = glslang::EOpOuterProduct;
1733 break;
1734 case glslang::EOpDot:
1735 {
qining25262b32016-05-06 17:25:16 -04001736 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001737 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001738 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001739 binOp = glslang::EOpMul;
1740 break;
1741 }
1742 case glslang::EOpMod:
1743 // when an aggregate, this is the floating-point mod built-in function,
1744 // which can be emitted by the one in createBinaryOperation()
1745 binOp = glslang::EOpMod;
1746 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001747 case glslang::EOpEmitVertex:
1748 case glslang::EOpEndPrimitive:
1749 case glslang::EOpBarrier:
1750 case glslang::EOpMemoryBarrier:
1751 case glslang::EOpMemoryBarrierAtomicCounter:
1752 case glslang::EOpMemoryBarrierBuffer:
1753 case glslang::EOpMemoryBarrierImage:
1754 case glslang::EOpMemoryBarrierShared:
1755 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001756 case glslang::EOpAllMemoryBarrierWithGroupSync:
1757 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1758 case glslang::EOpWorkgroupMemoryBarrier:
1759 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001760 noReturnValue = true;
1761 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1762 break;
1763
John Kessenich426394d2015-07-23 10:22:48 -06001764 case glslang::EOpAtomicAdd:
1765 case glslang::EOpAtomicMin:
1766 case glslang::EOpAtomicMax:
1767 case glslang::EOpAtomicAnd:
1768 case glslang::EOpAtomicOr:
1769 case glslang::EOpAtomicXor:
1770 case glslang::EOpAtomicExchange:
1771 case glslang::EOpAtomicCompSwap:
1772 atomic = true;
1773 break;
1774
John Kessenich0d0c6d32017-07-23 16:08:26 -06001775 case glslang::EOpAtomicCounterAdd:
1776 case glslang::EOpAtomicCounterSubtract:
1777 case glslang::EOpAtomicCounterMin:
1778 case glslang::EOpAtomicCounterMax:
1779 case glslang::EOpAtomicCounterAnd:
1780 case glslang::EOpAtomicCounterOr:
1781 case glslang::EOpAtomicCounterXor:
1782 case glslang::EOpAtomicCounterExchange:
1783 case glslang::EOpAtomicCounterCompSwap:
1784 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1785 builder.addCapability(spv::CapabilityAtomicStorageOps);
1786 atomic = true;
1787 break;
1788
John Kessenich140f3df2015-06-26 16:58:36 -06001789 default:
1790 break;
1791 }
1792
1793 //
1794 // See if it maps to a regular operation.
1795 //
John Kessenich140f3df2015-06-26 16:58:36 -06001796 if (binOp != glslang::EOpNull) {
1797 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1798 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1799 assert(left && right);
1800
1801 builder.clearAccessChain();
1802 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001803 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001804
1805 builder.clearAccessChain();
1806 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001807 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001808
John Kesseniche485c7a2017-05-31 18:50:53 -06001809 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001810 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001811 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001812 left->getType().getBasicType(), reduceComparison);
1813
1814 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001815 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001816 builder.clearAccessChain();
1817 builder.setAccessChainRValue(result);
1818
1819 return false;
1820 }
1821
John Kessenich426394d2015-07-23 10:22:48 -06001822 //
1823 // Create the list of operands.
1824 //
John Kessenich140f3df2015-06-26 16:58:36 -06001825 glslang::TIntermSequence& glslangOperands = node->getSequence();
1826 std::vector<spv::Id> operands;
1827 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001828 // special case l-value operands; there are just a few
1829 bool lvalue = false;
1830 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001831 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001832 case glslang::EOpModf:
1833 if (arg == 1)
1834 lvalue = true;
1835 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001836 case glslang::EOpInterpolateAtSample:
1837 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001838#ifdef AMD_EXTENSIONS
1839 case glslang::EOpInterpolateAtVertex:
1840#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001841 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001842 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001843
1844 // Does it need a swizzle inversion? If so, evaluation is inverted;
1845 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001846 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001847 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1848 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1849 }
Rex Xu7a26c172015-12-08 17:12:09 +08001850 break;
Rex Xud4782c12015-09-06 16:30:11 +08001851 case glslang::EOpAtomicAdd:
1852 case glslang::EOpAtomicMin:
1853 case glslang::EOpAtomicMax:
1854 case glslang::EOpAtomicAnd:
1855 case glslang::EOpAtomicOr:
1856 case glslang::EOpAtomicXor:
1857 case glslang::EOpAtomicExchange:
1858 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001859 case glslang::EOpAtomicCounterAdd:
1860 case glslang::EOpAtomicCounterSubtract:
1861 case glslang::EOpAtomicCounterMin:
1862 case glslang::EOpAtomicCounterMax:
1863 case glslang::EOpAtomicCounterAnd:
1864 case glslang::EOpAtomicCounterOr:
1865 case glslang::EOpAtomicCounterXor:
1866 case glslang::EOpAtomicCounterExchange:
1867 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001868 if (arg == 0)
1869 lvalue = true;
1870 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001871 case glslang::EOpAddCarry:
1872 case glslang::EOpSubBorrow:
1873 if (arg == 2)
1874 lvalue = true;
1875 break;
1876 case glslang::EOpUMulExtended:
1877 case glslang::EOpIMulExtended:
1878 if (arg >= 2)
1879 lvalue = true;
1880 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001881 default:
1882 break;
1883 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001884 builder.clearAccessChain();
1885 if (invertedType != spv::NoType && arg == 0)
1886 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1887 else
1888 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001889 if (lvalue)
1890 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001891 else {
1892 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001893 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001894 }
John Kessenich140f3df2015-06-26 16:58:36 -06001895 }
John Kessenich426394d2015-07-23 10:22:48 -06001896
John Kesseniche485c7a2017-05-31 18:50:53 -06001897 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001898 if (atomic) {
1899 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001900 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001901 } else {
1902 // Pass through to generic operations.
1903 switch (glslangOperands.size()) {
1904 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001905 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001906 break;
1907 case 1:
qining25262b32016-05-06 17:25:16 -04001908 result = createUnaryOperation(
1909 node->getOp(), precision,
1910 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001911 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001912 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001913 break;
1914 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001915 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001916 break;
1917 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001918 if (invertedType)
1919 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001920 }
1921
1922 if (noReturnValue)
1923 return false;
1924
1925 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001926 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001927 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001928 } else {
1929 builder.clearAccessChain();
1930 builder.setAccessChainRValue(result);
1931 return false;
1932 }
1933}
1934
John Kessenich433e9ff2017-01-26 20:31:11 -07001935// This path handles both if-then-else and ?:
1936// The if-then-else has a node type of void, while
1937// ?: has either a void or a non-void node type
1938//
1939// Leaving the result, when not void:
1940// GLSL only has r-values as the result of a :?, but
1941// if we have an l-value, that can be more efficient if it will
1942// become the base of a complex r-value expression, because the
1943// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001944bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1945{
John Kessenich433e9ff2017-01-26 20:31:11 -07001946 // See if it simple and safe to generate OpSelect instead of using control flow.
1947 // Crucially, side effects must be avoided, and there are performance trade-offs.
1948 // Return true if good idea (and safe) for OpSelect, false otherwise.
1949 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001950 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1951 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001952 return false;
1953
1954 if (node->getTrueBlock() == nullptr ||
1955 node->getFalseBlock() == nullptr)
1956 return false;
1957
1958 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1959 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1960
1961 // return true if a single operand to ? : is okay for OpSelect
1962 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001963 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001964 };
1965
1966 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1967 operandOkay(node->getFalseBlock()->getAsTyped());
1968 };
1969
1970 // Emit OpSelect for this selection.
1971 const auto handleAsOpSelect = [&]() {
1972 node->getCondition()->traverse(this);
1973 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1974 node->getTrueBlock()->traverse(this);
1975 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1976 node->getFalseBlock()->traverse(this);
1977 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1978
John Kesseniche485c7a2017-05-31 18:50:53 -06001979 builder.setLine(node->getLoc().line);
1980
John Kesseniche434ad92017-03-30 10:09:28 -06001981 // smear condition to vector, if necessary (AST is always scalar)
1982 if (builder.isVector(trueValue))
1983 condition = builder.smearScalar(spv::NoPrecision, condition,
1984 builder.makeVectorType(builder.makeBoolType(),
1985 builder.getNumComponents(trueValue)));
1986
1987 spv::Id select = builder.createTriOp(spv::OpSelect,
1988 convertGlslangToSpvType(node->getType()), condition,
1989 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001990 builder.clearAccessChain();
1991 builder.setAccessChainRValue(select);
1992 };
1993
1994 // Try for OpSelect
1995
1996 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001997 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1998 if (node->getType().getQualifier().isSpecConstant())
1999 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2000
John Kessenich433e9ff2017-01-26 20:31:11 -07002001 handleAsOpSelect();
2002 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002003 }
2004
Rex Xu57e65922017-07-04 23:23:40 +08002005 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07002006 // Don't handle results as temporaries, because there will be two names
2007 // and better to leave SSA to later passes.
2008 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
2009 ? spv::NoResult
2010 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2011
John Kessenich140f3df2015-06-26 16:58:36 -06002012 // emit the condition before doing anything with selection
2013 node->getCondition()->traverse(this);
2014
Rex Xu57e65922017-07-04 23:23:40 +08002015 // Selection control:
2016 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2017
John Kessenich140f3df2015-06-26 16:58:36 -06002018 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08002019 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06002020
John Kessenich433e9ff2017-01-26 20:31:11 -07002021 // emit the "then" statement
2022 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002023 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002024 if (result != spv::NoResult)
2025 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002026 }
2027
John Kessenich433e9ff2017-01-26 20:31:11 -07002028 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002029 ifBuilder.makeBeginElse();
2030 // emit the "else" statement
2031 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002032 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07002033 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002034 }
2035
John Kessenich433e9ff2017-01-26 20:31:11 -07002036 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06002037 ifBuilder.makeEndIf();
2038
John Kessenich433e9ff2017-01-26 20:31:11 -07002039 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06002040 // GLSL only has r-values as the result of a :?, but
2041 // if we have an l-value, that can be more efficient if it will
2042 // become the base of a complex r-value expression, because the
2043 // next layer copies r-values into memory to use the access-chain mechanism
2044 builder.clearAccessChain();
2045 builder.setAccessChainLValue(result);
2046 }
2047
2048 return false;
2049}
2050
2051bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2052{
2053 // emit and get the condition before doing anything with switch
2054 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002055 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002056
Rex Xu57e65922017-07-04 23:23:40 +08002057 // Selection control:
2058 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2059
John Kessenich140f3df2015-06-26 16:58:36 -06002060 // browse the children to sort out code segments
2061 int defaultSegment = -1;
2062 std::vector<TIntermNode*> codeSegments;
2063 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2064 std::vector<int> caseValues;
2065 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2066 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2067 TIntermNode* child = *c;
2068 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002069 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002070 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002071 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002072 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2073 } else
2074 codeSegments.push_back(child);
2075 }
2076
qining25262b32016-05-06 17:25:16 -04002077 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002078 // statements between the last case and the end of the switch statement
2079 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2080 (int)codeSegments.size() == defaultSegment)
2081 codeSegments.push_back(nullptr);
2082
2083 // make the switch statement
2084 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002085 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002086
2087 // emit all the code in the segments
2088 breakForLoop.push(false);
2089 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2090 builder.nextSwitchSegment(segmentBlocks, s);
2091 if (codeSegments[s])
2092 codeSegments[s]->traverse(this);
2093 else
2094 builder.addSwitchBreak();
2095 }
2096 breakForLoop.pop();
2097
2098 builder.endSwitch(segmentBlocks);
2099
2100 return false;
2101}
2102
2103void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2104{
2105 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002106 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002107
2108 builder.clearAccessChain();
2109 builder.setAccessChainRValue(constant);
2110}
2111
2112bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2113{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002114 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002115 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002116
2117 // Loop control:
2118 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2119
2120 // TODO: dependency length
2121
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002122 // Spec requires back edges to target header blocks, and every header block
2123 // must dominate its merge block. Make a header block first to ensure these
2124 // conditions are met. By definition, it will contain OpLoopMerge, followed
2125 // by a block-ending branch. But we don't want to put any other body/test
2126 // instructions in it, since the body/test may have arbitrary instructions,
2127 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002128 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002129 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002130 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002131 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002132 spv::Block& test = builder.makeNewBlock();
2133 builder.createBranch(&test);
2134
2135 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002136 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002137 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002138 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2139
2140 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002141 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002142 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002143 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002144 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002145 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002146
2147 builder.setBuildPoint(&blocks.continue_target);
2148 if (node->getTerminal())
2149 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002150 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002151 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002152 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002153 builder.createBranch(&blocks.body);
2154
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002155 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002156 builder.setBuildPoint(&blocks.body);
2157 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002158 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002159 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002160 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002161
2162 builder.setBuildPoint(&blocks.continue_target);
2163 if (node->getTerminal())
2164 node->getTerminal()->traverse(this);
2165 if (node->getTest()) {
2166 node->getTest()->traverse(this);
2167 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002168 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002169 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002170 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002171 // TODO: unless there was a break/return/discard instruction
2172 // somewhere in the body, this is an infinite loop, so we should
2173 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002174 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002175 }
John Kessenich140f3df2015-06-26 16:58:36 -06002176 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002177 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002178 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002179 return false;
2180}
2181
2182bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2183{
2184 if (node->getExpression())
2185 node->getExpression()->traverse(this);
2186
John Kesseniche485c7a2017-05-31 18:50:53 -06002187 builder.setLine(node->getLoc().line);
2188
John Kessenich140f3df2015-06-26 16:58:36 -06002189 switch (node->getFlowOp()) {
2190 case glslang::EOpKill:
2191 builder.makeDiscard();
2192 break;
2193 case glslang::EOpBreak:
2194 if (breakForLoop.top())
2195 builder.createLoopExit();
2196 else
2197 builder.addSwitchBreak();
2198 break;
2199 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002200 builder.createLoopContinue();
2201 break;
2202 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002203 if (node->getExpression()) {
2204 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2205 spv::Id returnId = accessChainLoad(glslangReturnType);
2206 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2207 builder.clearAccessChain();
2208 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2209 builder.setAccessChainLValue(copyId);
2210 multiTypeStore(glslangReturnType, returnId);
2211 returnId = builder.createLoad(copyId);
2212 }
2213 builder.makeReturn(false, returnId);
2214 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002215 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002216
2217 builder.clearAccessChain();
2218 break;
2219
2220 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002221 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002222 break;
2223 }
2224
2225 return false;
2226}
2227
2228spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2229{
qining25262b32016-05-06 17:25:16 -04002230 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002231 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002232 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002233 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002234 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002235 }
2236
2237 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002238 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002239 spv::Id spvType = convertGlslangToSpvType(node->getType());
2240
Rex Xuf89ad982017-04-07 23:22:33 +08002241#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002242 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2243 node->getType().containsBasicType(glslang::EbtInt16) ||
2244 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002245 if (contains16BitType) {
2246 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2247 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2248 builder.addCapability(spv::CapabilityStorageInputOutput16);
2249 } else if (storageClass == spv::StorageClassPushConstant) {
2250 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2251 builder.addCapability(spv::CapabilityStoragePushConstant16);
2252 } else if (storageClass == spv::StorageClassUniform) {
2253 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2254 builder.addCapability(spv::CapabilityStorageUniform16);
2255 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2256 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2257 }
2258 }
2259#endif
2260
John Kessenich140f3df2015-06-26 16:58:36 -06002261 const char* name = node->getName().c_str();
2262 if (glslang::IsAnonymous(name))
2263 name = "";
2264
2265 return builder.createVariable(storageClass, spvType, name);
2266}
2267
2268// Return type Id of the sampled type.
2269spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2270{
2271 switch (sampler.type) {
2272 case glslang::EbtFloat: return builder.makeFloatType(32);
2273 case glslang::EbtInt: return builder.makeIntType(32);
2274 case glslang::EbtUint: return builder.makeUintType(32);
2275 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002276 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002277 return builder.makeFloatType(32);
2278 }
2279}
2280
John Kessenich8c8505c2016-07-26 12:50:38 -06002281// If node is a swizzle operation, return the type that should be used if
2282// the swizzle base is first consumed by another operation, before the swizzle
2283// is applied.
2284spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2285{
John Kessenichecba76f2017-01-06 00:34:48 -07002286 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002287 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2288 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2289 else
2290 return spv::NoType;
2291}
2292
2293// When inverting a swizzle with a parent op, this function
2294// will apply the swizzle operation to a completed parent operation.
2295spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2296{
2297 std::vector<unsigned> swizzle;
2298 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2299 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2300}
2301
John Kessenich8c8505c2016-07-26 12:50:38 -06002302// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2303void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2304{
2305 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2306 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2307 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2308}
2309
John Kessenich3ac051e2015-12-20 11:29:16 -07002310// Convert from a glslang type to an SPV type, by calling into a
2311// recursive version of this function. This establishes the inherited
2312// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002313spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2314{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002315 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002316}
2317
2318// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002319// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002320// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002321spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002322{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002323 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002324
2325 switch (type.getBasicType()) {
2326 case glslang::EbtVoid:
2327 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002328 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002329 break;
2330 case glslang::EbtFloat:
2331 spvType = builder.makeFloatType(32);
2332 break;
2333 case glslang::EbtDouble:
2334 spvType = builder.makeFloatType(64);
2335 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002336#ifdef AMD_EXTENSIONS
2337 case glslang::EbtFloat16:
2338 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002339 spvType = builder.makeFloatType(16);
2340 break;
2341#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002342 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002343 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2344 // a 32-bit int where non-0 means true.
2345 if (explicitLayout != glslang::ElpNone)
2346 spvType = builder.makeUintType(32);
2347 else
2348 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002349 break;
2350 case glslang::EbtInt:
2351 spvType = builder.makeIntType(32);
2352 break;
2353 case glslang::EbtUint:
2354 spvType = builder.makeUintType(32);
2355 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002356 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002357 spvType = builder.makeIntType(64);
2358 break;
2359 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002360 spvType = builder.makeUintType(64);
2361 break;
Rex Xucabbb782017-03-24 13:41:14 +08002362#ifdef AMD_EXTENSIONS
2363 case glslang::EbtInt16:
2364 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2365 spvType = builder.makeIntType(16);
2366 break;
2367 case glslang::EbtUint16:
2368 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2369 spvType = builder.makeUintType(16);
2370 break;
2371#endif
John Kessenich426394d2015-07-23 10:22:48 -06002372 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002373 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002374 spvType = builder.makeUintType(32);
2375 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002376 case glslang::EbtSampler:
2377 {
2378 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002379 if (sampler.sampler) {
2380 // pure sampler
2381 spvType = builder.makeSamplerType();
2382 } else {
2383 // an image is present, make its type
2384 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2385 sampler.image ? 2 : 1, TranslateImageFormat(type));
2386 if (sampler.combined) {
2387 // already has both image and sampler, make the combined type
2388 spvType = builder.makeSampledImageType(spvType);
2389 }
John Kessenich55e7d112015-11-15 21:33:39 -07002390 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002391 }
John Kessenich140f3df2015-06-26 16:58:36 -06002392 break;
2393 case glslang::EbtStruct:
2394 case glslang::EbtBlock:
2395 {
2396 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002397 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002398
2399 // Try to share structs for different layouts, but not yet for other
2400 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002401 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002402 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002403 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002404 break;
2405
2406 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002407 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002408 memberRemapper[glslangMembers].resize(glslangMembers->size());
2409 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002410 }
2411 break;
2412 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002413 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002414 break;
2415 }
2416
2417 if (type.isMatrix())
2418 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2419 else {
2420 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2421 if (type.getVectorSize() > 1)
2422 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2423 }
2424
2425 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002426 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2427
John Kessenichc9a80832015-09-12 12:17:44 -06002428 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002429 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002430 // We need to decorate array strides for types needing explicit layout, except blocks.
2431 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002432 // Use a dummy glslang type for querying internal strides of
2433 // arrays of arrays, but using just a one-dimensional array.
2434 glslang::TType simpleArrayType(type, 0); // deference type of the array
2435 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2436 simpleArrayType.getArraySizes().dereference();
2437
2438 // Will compute the higher-order strides here, rather than making a whole
2439 // pile of types and doing repetitive recursion on their contents.
2440 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2441 }
John Kessenichf8842e52016-01-04 19:22:56 -07002442
2443 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002444 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002445 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002446 if (stride > 0)
2447 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002448 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002449 }
2450 } else {
2451 // single-dimensional array, and don't yet have stride
2452
John Kessenichf8842e52016-01-04 19:22:56 -07002453 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002454 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2455 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002456 }
John Kessenich31ed4832015-09-09 17:51:38 -06002457
John Kessenichc9a80832015-09-12 12:17:44 -06002458 // Do the outer dimension, which might not be known for a runtime-sized array
2459 if (type.isRuntimeSizedArray()) {
2460 spvType = builder.makeRuntimeArray(spvType);
2461 } else {
2462 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002463 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002464 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002465 if (stride > 0)
2466 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002467 }
2468
2469 return spvType;
2470}
2471
John Kessenich0e737842017-03-24 18:38:16 -06002472// TODO: this functionality should exist at a higher level, in creating the AST
2473//
2474// Identify interface members that don't have their required extension turned on.
2475//
2476bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2477{
2478 auto& extensions = glslangIntermediate->getRequestedExtensions();
2479
Rex Xubcf291a2017-03-29 23:01:36 +08002480 if (member.getFieldName() == "gl_ViewportMask" &&
2481 extensions.find("GL_NV_viewport_array2") == extensions.end())
2482 return true;
2483 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2484 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2485 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002486 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2487 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2488 return true;
2489 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2490 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2491 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002492 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2493 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2494 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002495
2496 return false;
2497};
2498
John Kessenich6090df02016-06-30 21:18:02 -06002499// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2500// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2501// Mutually recursive with convertGlslangToSpvType().
2502spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2503 const glslang::TTypeList* glslangMembers,
2504 glslang::TLayoutPacking explicitLayout,
2505 const glslang::TQualifier& qualifier)
2506{
2507 // Create a vector of struct types for SPIR-V to consume
2508 std::vector<spv::Id> spvMembers;
2509 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 -06002510 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2511 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2512 if (glslangMember.hiddenMember()) {
2513 ++memberDelta;
2514 if (type.getBasicType() == glslang::EbtBlock)
2515 memberRemapper[glslangMembers][i] = -1;
2516 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002517 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002518 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002519 if (filterMember(glslangMember))
2520 continue;
2521 }
John Kessenich6090df02016-06-30 21:18:02 -06002522 // modify just this child's view of the qualifier
2523 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2524 InheritQualifiers(memberQualifier, qualifier);
2525
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002526 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002527 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002528 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002529
2530 // recurse
2531 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2532 }
2533 }
2534
2535 // Make the SPIR-V type
2536 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002537 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002538 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2539
2540 // Decorate it
2541 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2542
2543 return spvType;
2544}
2545
2546void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2547 const glslang::TTypeList* glslangMembers,
2548 glslang::TLayoutPacking explicitLayout,
2549 const glslang::TQualifier& qualifier,
2550 spv::Id spvType)
2551{
2552 // Name and decorate the non-hidden members
2553 int offset = -1;
2554 int locationOffset = 0; // for use within the members of this struct
2555 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2556 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2557 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002558 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002559 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002560 if (filterMember(glslangMember))
2561 continue;
2562 }
John Kessenich6090df02016-06-30 21:18:02 -06002563
2564 // modify just this child's view of the qualifier
2565 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2566 InheritQualifiers(memberQualifier, qualifier);
2567
2568 // using -1 above to indicate a hidden member
2569 if (member >= 0) {
2570 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2571 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2572 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2573 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002574 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2575 type.getQualifier().storage == glslang::EvqVaryingOut) {
2576 if (type.getBasicType() == glslang::EbtBlock ||
2577 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002578 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2579 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2580 }
2581 }
2582 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2583
Rex Xu286ca432017-07-27 14:33:16 +08002584 if (type.getBasicType() == glslang::EbtBlock &&
2585 qualifier.storage == glslang::EvqBuffer) {
2586 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002587 std::vector<spv::Decoration> memory;
2588 TranslateMemoryDecoration(memberQualifier, memory);
2589 for (unsigned int i = 0; i < memory.size(); ++i)
2590 addMemberDecoration(spvType, member, memory[i]);
2591 }
2592
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002593 // Location assignment was already completed correctly by the front end,
2594 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002595 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002596 // ill-specified and decisions have been made to not allow this.
2597 if (! type.isArray() && memberQualifier.hasLocation())
2598 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002599
John Kessenich2f47bc92016-06-30 21:47:35 -06002600 if (qualifier.hasLocation()) // track for upcoming inheritance
2601 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2602
John Kessenich6090df02016-06-30 21:18:02 -06002603 // component, XFB, others
2604 if (glslangMember.getQualifier().hasComponent())
2605 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2606 if (glslangMember.getQualifier().hasXfbOffset())
2607 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2608 else if (explicitLayout != glslang::ElpNone) {
2609 // figure out what to do with offset, which is accumulating
2610 int nextOffset;
2611 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2612 if (offset >= 0)
2613 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2614 offset = nextOffset;
2615 }
2616
2617 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2618 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2619
2620 // built-in variable decorations
2621 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002622 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002623 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002624
2625#ifdef NV_EXTENSIONS
2626 if (builtIn == spv::BuiltInLayer) {
2627 // SPV_NV_viewport_array2 extension
2628 if (glslangMember.getQualifier().layoutViewportRelative){
2629 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2630 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2631 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2632 }
2633 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2634 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2635 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2636 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2637 }
2638 }
chaocdf3956c2017-02-14 14:52:34 -08002639 if (glslangMember.getQualifier().layoutPassthrough) {
2640 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2641 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2642 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2643 }
chaoc771d89f2017-01-13 01:10:53 -08002644#endif
John Kessenich6090df02016-06-30 21:18:02 -06002645 }
2646 }
2647
2648 // Decorate the structure
2649 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002650 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002651 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2652 builder.addCapability(spv::CapabilityGeometryStreams);
2653 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2654 }
2655 if (glslangIntermediate->getXfbMode()) {
2656 builder.addCapability(spv::CapabilityTransformFeedback);
2657 if (type.getQualifier().hasXfbStride())
2658 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2659 if (type.getQualifier().hasXfbBuffer())
2660 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2661 }
2662}
2663
John Kessenich6c292d32016-02-15 20:58:50 -07002664// Turn the expression forming the array size into an id.
2665// This is not quite trivial, because of specialization constants.
2666// Sometimes, a raw constant is turned into an Id, and sometimes
2667// a specialization constant expression is.
2668spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2669{
2670 // First, see if this is sized with a node, meaning a specialization constant:
2671 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2672 if (specNode != nullptr) {
2673 builder.clearAccessChain();
2674 specNode->traverse(this);
2675 return accessChainLoad(specNode->getAsTyped()->getType());
2676 }
qining25262b32016-05-06 17:25:16 -04002677
John Kessenich6c292d32016-02-15 20:58:50 -07002678 // Otherwise, need a compile-time (front end) size, get it:
2679 int size = arraySizes.getDimSize(dim);
2680 assert(size > 0);
2681 return builder.makeUintConstant(size);
2682}
2683
John Kessenich103bef92016-02-08 21:38:15 -07002684// Wrap the builder's accessChainLoad to:
2685// - localize handling of RelaxedPrecision
2686// - use the SPIR-V inferred type instead of another conversion of the glslang type
2687// (avoids unnecessary work and possible type punning for structures)
2688// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002689spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2690{
John Kessenich103bef92016-02-08 21:38:15 -07002691 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2692 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2693
2694 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002695 if (type.getBasicType() == glslang::EbtBool) {
2696 if (builder.isScalarType(nominalTypeId)) {
2697 // Conversion for bool
2698 spv::Id boolType = builder.makeBoolType();
2699 if (nominalTypeId != boolType)
2700 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2701 } else if (builder.isVectorType(nominalTypeId)) {
2702 // Conversion for bvec
2703 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2704 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2705 if (nominalTypeId != bvecType)
2706 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2707 }
2708 }
John Kessenich103bef92016-02-08 21:38:15 -07002709
2710 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002711}
2712
Rex Xu27253232016-02-23 17:51:09 +08002713// Wrap the builder's accessChainStore to:
2714// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002715//
2716// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002717void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2718{
2719 // Need to convert to abstract types when necessary
2720 if (type.getBasicType() == glslang::EbtBool) {
2721 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2722
2723 if (builder.isScalarType(nominalTypeId)) {
2724 // Conversion for bool
2725 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002726 if (nominalTypeId != boolType) {
2727 // keep these outside arguments, for determinant order-of-evaluation
2728 spv::Id one = builder.makeUintConstant(1);
2729 spv::Id zero = builder.makeUintConstant(0);
2730 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2731 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002732 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002733 } else if (builder.isVectorType(nominalTypeId)) {
2734 // Conversion for bvec
2735 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2736 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002737 if (nominalTypeId != bvecType) {
2738 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002739 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2740 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2741 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002742 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002743 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2744 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002745 }
2746 }
2747
2748 builder.accessChainStore(rvalue);
2749}
2750
John Kessenich4bf71552016-09-02 11:20:21 -06002751// For storing when types match at the glslang level, but not might match at the
2752// SPIR-V level.
2753//
2754// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002755// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002756// as in a member-decorated way.
2757//
2758// NOTE: This function can handle any store request; if it's not special it
2759// simplifies to a simple OpStore.
2760//
2761// Implicitly uses the existing builder.accessChain as the storage target.
2762void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2763{
John Kessenichb3e24e42016-09-11 12:33:43 -06002764 // we only do the complex path here if it's an aggregate
2765 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002766 accessChainStore(type, rValue);
2767 return;
2768 }
2769
John Kessenichb3e24e42016-09-11 12:33:43 -06002770 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002771 spv::Id rType = builder.getTypeId(rValue);
2772 spv::Id lValue = builder.accessChainGetLValue();
2773 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2774 if (lType == rType) {
2775 accessChainStore(type, rValue);
2776 return;
2777 }
2778
John Kessenichb3e24e42016-09-11 12:33:43 -06002779 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002780 // where the two types were the same type in GLSL. This requires member
2781 // by member copy, recursively.
2782
John Kessenichb3e24e42016-09-11 12:33:43 -06002783 // If an array, copy element by element.
2784 if (type.isArray()) {
2785 glslang::TType glslangElementType(type, 0);
2786 spv::Id elementRType = builder.getContainedTypeId(rType);
2787 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2788 // get the source member
2789 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002790
John Kessenichb3e24e42016-09-11 12:33:43 -06002791 // set up the target storage
2792 builder.clearAccessChain();
2793 builder.setAccessChainLValue(lValue);
2794 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002795
John Kessenichb3e24e42016-09-11 12:33:43 -06002796 // store the member
2797 multiTypeStore(glslangElementType, elementRValue);
2798 }
2799 } else {
2800 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002801
John Kessenichb3e24e42016-09-11 12:33:43 -06002802 // loop over structure members
2803 const glslang::TTypeList& members = *type.getStruct();
2804 for (int m = 0; m < (int)members.size(); ++m) {
2805 const glslang::TType& glslangMemberType = *members[m].type;
2806
2807 // get the source member
2808 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2809 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2810
2811 // set up the target storage
2812 builder.clearAccessChain();
2813 builder.setAccessChainLValue(lValue);
2814 builder.accessChainPush(builder.makeIntConstant(m));
2815
2816 // store the member
2817 multiTypeStore(glslangMemberType, memberRValue);
2818 }
John Kessenich4bf71552016-09-02 11:20:21 -06002819 }
2820}
2821
John Kessenichf85e8062015-12-19 13:57:10 -07002822// Decide whether or not this type should be
2823// decorated with offsets and strides, and if so
2824// whether std140 or std430 rules should be applied.
2825glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002826{
John Kessenichf85e8062015-12-19 13:57:10 -07002827 // has to be a block
2828 if (type.getBasicType() != glslang::EbtBlock)
2829 return glslang::ElpNone;
2830
2831 // has to be a uniform or buffer block
2832 if (type.getQualifier().storage != glslang::EvqUniform &&
2833 type.getQualifier().storage != glslang::EvqBuffer)
2834 return glslang::ElpNone;
2835
2836 // return the layout to use
2837 switch (type.getQualifier().layoutPacking) {
2838 case glslang::ElpStd140:
2839 case glslang::ElpStd430:
2840 return type.getQualifier().layoutPacking;
2841 default:
2842 return glslang::ElpNone;
2843 }
John Kessenich31ed4832015-09-09 17:51:38 -06002844}
2845
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002846// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002847int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002848{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002849 int size;
John Kessenich49987892015-12-29 17:11:44 -07002850 int stride;
2851 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002852
2853 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002854}
2855
John Kessenich49987892015-12-29 17:11:44 -07002856// 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 -07002857// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002858int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002859{
John Kessenich49987892015-12-29 17:11:44 -07002860 glslang::TType elementType;
2861 elementType.shallowCopy(matrixType);
2862 elementType.clearArraySizes();
2863
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002864 int size;
John Kessenich49987892015-12-29 17:11:44 -07002865 int stride;
2866 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2867
2868 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002869}
2870
John Kessenich5e4b1242015-08-06 22:53:06 -06002871// Given a member type of a struct, realign the current offset for it, and compute
2872// the next (not yet aligned) offset for the next member, which will get aligned
2873// on the next call.
2874// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2875// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2876// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002877void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002878 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002879{
2880 // this will get a positive value when deemed necessary
2881 nextOffset = -1;
2882
John Kessenich5e4b1242015-08-06 22:53:06 -06002883 // override anything in currentOffset with user-set offset
2884 if (memberType.getQualifier().hasOffset())
2885 currentOffset = memberType.getQualifier().layoutOffset;
2886
2887 // It could be that current linker usage in glslang updated all the layoutOffset,
2888 // in which case the following code does not matter. But, that's not quite right
2889 // once cross-compilation unit GLSL validation is done, as the original user
2890 // settings are needed in layoutOffset, and then the following will come into play.
2891
John Kessenichf85e8062015-12-19 13:57:10 -07002892 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002893 if (! memberType.getQualifier().hasOffset())
2894 currentOffset = -1;
2895
2896 return;
2897 }
2898
John Kessenichf85e8062015-12-19 13:57:10 -07002899 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002900 if (currentOffset < 0)
2901 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002902
John Kessenich5e4b1242015-08-06 22:53:06 -06002903 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2904 // but possibly not yet correctly aligned.
2905
2906 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002907 int dummyStride;
2908 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002909
2910 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002911 // TODO: make this consistent in early phases of code:
2912 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2913 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2914 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002915 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002916 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002917 int dummySize;
2918 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2919 if (componentAlignment <= 4)
2920 memberAlignment = componentAlignment;
2921 }
2922
2923 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002924 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002925
2926 // Bump up to vec4 if there is a bad straddle
2927 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2928 glslang::RoundToPow2(currentOffset, 16);
2929
John Kessenich5e4b1242015-08-06 22:53:06 -06002930 nextOffset = currentOffset + memberSize;
2931}
2932
David Netoa901ffe2016-06-08 14:11:40 +01002933void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002934{
David Netoa901ffe2016-06-08 14:11:40 +01002935 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2936 switch (glslangBuiltIn)
2937 {
2938 case glslang::EbvClipDistance:
2939 case glslang::EbvCullDistance:
2940 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002941#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08002942 case glslang::EbvViewportMaskNV:
2943 case glslang::EbvSecondaryPositionNV:
2944 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002945 case glslang::EbvPositionPerViewNV:
2946 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002947#endif
David Netoa901ffe2016-06-08 14:11:40 +01002948 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2949 // Alternately, we could just call this for any glslang built-in, since the
2950 // capability already guards against duplicates.
2951 TranslateBuiltInDecoration(glslangBuiltIn, false);
2952 break;
2953 default:
2954 // Capabilities were already generated when the struct was declared.
2955 break;
2956 }
John Kessenichebb50532016-05-16 19:22:05 -06002957}
2958
John Kessenich6fccb3c2016-09-19 16:01:41 -06002959bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002960{
John Kessenicheee9d532016-09-19 18:09:30 -06002961 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002962}
2963
2964// Make all the functions, skeletally, without actually visiting their bodies.
2965void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2966{
John Kessenichfad62972017-07-18 02:35:46 -06002967 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
2968 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
2969 if (paramPrecision != spv::NoPrecision)
2970 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06002971 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06002972 };
2973
John Kessenich140f3df2015-06-26 16:58:36 -06002974 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2975 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002976 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002977 continue;
2978
2979 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002980 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002981 //
qining25262b32016-05-06 17:25:16 -04002982 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002983 // function. What it is an address of varies:
2984 //
John Kessenich4bf71552016-09-02 11:20:21 -06002985 // - "in" parameters not marked as "const" can be written to without modifying the calling
2986 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002987 //
2988 // - "const in" parameters can just be the r-value, as no writes need occur.
2989 //
John Kessenich4bf71552016-09-02 11:20:21 -06002990 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2991 // 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 -06002992
2993 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06002994 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06002995 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2996
John Kessenichfad62972017-07-18 02:35:46 -06002997 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
2998 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06002999
John Kessenichfad62972017-07-18 02:35:46 -06003000 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003001 for (int p = 0; p < (int)parameters.size(); ++p) {
3002 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3003 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06003004 // can we pass by reference?
3005 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06003006 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06003007 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06003008 (p == 0 && implicitThis)) // implicit 'this'
John Kessenicha5c5fb62017-05-05 05:09:58 -06003009 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07003010 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003011 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3012 else
John Kessenich4bf71552016-09-02 11:20:21 -06003013 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003014 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003015 paramTypes.push_back(typeId);
3016 }
3017
3018 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003019 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3020 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003021 glslFunction->getName().c_str(), paramTypes,
3022 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003023 if (implicitThis)
3024 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003025
3026 // Track function to emit/call later
3027 functionMap[glslFunction->getName().c_str()] = function;
3028
3029 // Set the parameter id's
3030 for (int p = 0; p < (int)parameters.size(); ++p) {
3031 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3032 // give a name too
3033 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3034 }
3035 }
3036}
3037
3038// Process all the initializers, while skipping the functions and link objects
3039void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3040{
3041 builder.setBuildPoint(shaderEntry->getLastBlock());
3042 for (int i = 0; i < (int)initializers.size(); ++i) {
3043 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3044 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3045
3046 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003047 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003048 initializer->traverse(this);
3049 }
3050 }
3051}
3052
3053// Process all the functions, while skipping initializers.
3054void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3055{
3056 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3057 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003058 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003059 node->traverse(this);
3060 }
3061}
3062
3063void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3064{
qining25262b32016-05-06 17:25:16 -04003065 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003066 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003067 currentFunction = functionMap[node->getName().c_str()];
3068 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003069 builder.setBuildPoint(functionBlock);
3070}
3071
Rex Xu04db3f52015-09-16 11:44:02 +08003072void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003073{
Rex Xufc618912015-09-09 16:42:49 +08003074 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003075
3076 glslang::TSampler sampler = {};
3077 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003078 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003079 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3080 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3081 }
3082
John Kessenich140f3df2015-06-26 16:58:36 -06003083 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3084 builder.clearAccessChain();
3085 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003086
3087 // Special case l-value operands
3088 bool lvalue = false;
3089 switch (node.getOp()) {
3090 case glslang::EOpImageAtomicAdd:
3091 case glslang::EOpImageAtomicMin:
3092 case glslang::EOpImageAtomicMax:
3093 case glslang::EOpImageAtomicAnd:
3094 case glslang::EOpImageAtomicOr:
3095 case glslang::EOpImageAtomicXor:
3096 case glslang::EOpImageAtomicExchange:
3097 case glslang::EOpImageAtomicCompSwap:
3098 if (i == 0)
3099 lvalue = true;
3100 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003101 case glslang::EOpSparseImageLoad:
3102 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3103 lvalue = true;
3104 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003105 case glslang::EOpSparseTexture:
3106 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3107 lvalue = true;
3108 break;
3109 case glslang::EOpSparseTextureClamp:
3110 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3111 lvalue = true;
3112 break;
3113 case glslang::EOpSparseTextureLod:
3114 case glslang::EOpSparseTextureOffset:
3115 if (i == 3)
3116 lvalue = true;
3117 break;
3118 case glslang::EOpSparseTextureFetch:
3119 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3120 lvalue = true;
3121 break;
3122 case glslang::EOpSparseTextureFetchOffset:
3123 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3124 lvalue = true;
3125 break;
3126 case glslang::EOpSparseTextureLodOffset:
3127 case glslang::EOpSparseTextureGrad:
3128 case glslang::EOpSparseTextureOffsetClamp:
3129 if (i == 4)
3130 lvalue = true;
3131 break;
3132 case glslang::EOpSparseTextureGradOffset:
3133 case glslang::EOpSparseTextureGradClamp:
3134 if (i == 5)
3135 lvalue = true;
3136 break;
3137 case glslang::EOpSparseTextureGradOffsetClamp:
3138 if (i == 6)
3139 lvalue = true;
3140 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003141 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003142 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3143 lvalue = true;
3144 break;
3145 case glslang::EOpSparseTextureGatherOffset:
3146 case glslang::EOpSparseTextureGatherOffsets:
3147 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3148 lvalue = true;
3149 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003150#ifdef AMD_EXTENSIONS
3151 case glslang::EOpSparseTextureGatherLod:
3152 if (i == 3)
3153 lvalue = true;
3154 break;
3155 case glslang::EOpSparseTextureGatherLodOffset:
3156 case glslang::EOpSparseTextureGatherLodOffsets:
3157 if (i == 4)
3158 lvalue = true;
3159 break;
Rex Xu129799a2017-07-05 17:23:28 +08003160 case glslang::EOpSparseImageLoadLod:
3161 if (i == 3)
3162 lvalue = true;
3163 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003164#endif
Rex Xufc618912015-09-09 16:42:49 +08003165 default:
3166 break;
3167 }
3168
Rex Xu6b86d492015-09-16 17:48:22 +08003169 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003170 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003171 else
John Kessenich32cfd492016-02-02 12:37:46 -07003172 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003173 }
3174}
3175
John Kessenichfc51d282015-08-19 13:34:18 -06003176void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003177{
John Kessenichfc51d282015-08-19 13:34:18 -06003178 builder.clearAccessChain();
3179 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003180 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003181}
John Kessenich140f3df2015-06-26 16:58:36 -06003182
John Kessenichfc51d282015-08-19 13:34:18 -06003183spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3184{
John Kesseniche485c7a2017-05-31 18:50:53 -06003185 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003186 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003187
3188 builder.setLine(node->getLoc().line);
3189
John Kessenich8c8505c2016-07-26 12:50:38 -06003190 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003191
John Kessenichfc51d282015-08-19 13:34:18 -06003192 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003193 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3194 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3195 std::vector<spv::Id> arguments;
3196 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003197 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003198 else
3199 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003200 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003201
3202 spv::Builder::TextureParameters params = { };
3203 params.sampler = arguments[0];
3204
Rex Xu04db3f52015-09-16 11:44:02 +08003205 glslang::TCrackedTextureOp cracked;
3206 node->crackTexture(sampler, cracked);
3207
amhagan05506bb2017-06-13 16:53:02 -04003208 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003209
John Kessenichfc51d282015-08-19 13:34:18 -06003210 // Check for queries
3211 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003212 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3213 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003214 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003215
John Kessenichfc51d282015-08-19 13:34:18 -06003216 switch (node->getOp()) {
3217 case glslang::EOpImageQuerySize:
3218 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003219 if (arguments.size() > 1) {
3220 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003221 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003222 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003223 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003224 case glslang::EOpImageQuerySamples:
3225 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003226 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003227 case glslang::EOpTextureQueryLod:
3228 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003229 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003230 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003231 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003232 case glslang::EOpSparseTexelsResident:
3233 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003234 default:
3235 assert(0);
3236 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003237 }
John Kessenich140f3df2015-06-26 16:58:36 -06003238 }
3239
Rex Xufc618912015-09-09 16:42:49 +08003240 // Check for image functions other than queries
3241 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003242 std::vector<spv::Id> operands;
3243 auto opIt = arguments.begin();
3244 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003245
3246 // Handle subpass operations
3247 // TODO: GLSL should change to have the "MS" only on the type rather than the
3248 // built-in function.
3249 if (cracked.subpass) {
3250 // add on the (0,0) coordinate
3251 spv::Id zero = builder.makeIntConstant(0);
3252 std::vector<spv::Id> comps;
3253 comps.push_back(zero);
3254 comps.push_back(zero);
3255 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3256 if (sampler.ms) {
3257 operands.push_back(spv::ImageOperandsSampleMask);
3258 operands.push_back(*(opIt++));
3259 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003260 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003261 }
3262
John Kessenich56bab042015-09-16 10:54:31 -06003263 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003264#ifdef AMD_EXTENSIONS
3265 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3266#else
John Kessenich56bab042015-09-16 10:54:31 -06003267 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003268#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003269 if (sampler.ms) {
3270 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003271 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003272#ifdef AMD_EXTENSIONS
3273 } else if (cracked.lod) {
3274 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3275 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3276
3277 operands.push_back(spv::ImageOperandsLodMask);
3278 operands.push_back(*opIt);
3279#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003280 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003281 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3282 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003283 return builder.createOp(spv::OpImageRead, resultType(), operands);
Rex Xu129799a2017-07-05 17:23:28 +08003284#ifdef AMD_EXTENSIONS
3285 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3286#else
John Kessenich56bab042015-09-16 10:54:31 -06003287 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003288#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003289 if (sampler.ms) {
3290 operands.push_back(*(opIt + 1));
3291 operands.push_back(spv::ImageOperandsSampleMask);
3292 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003293#ifdef AMD_EXTENSIONS
3294 } else if (cracked.lod) {
3295 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3296 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3297
3298 operands.push_back(*(opIt + 1));
3299 operands.push_back(spv::ImageOperandsLodMask);
3300 operands.push_back(*opIt);
3301#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003302 } else
3303 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003304 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003305 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3306 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003307 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003308#ifdef AMD_EXTENSIONS
3309 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3310#else
Rex Xu5eafa472016-02-19 22:24:03 +08003311 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003312#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003313 builder.addCapability(spv::CapabilitySparseResidency);
3314 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3315 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3316
3317 if (sampler.ms) {
3318 operands.push_back(spv::ImageOperandsSampleMask);
3319 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003320#ifdef AMD_EXTENSIONS
3321 } else if (cracked.lod) {
3322 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3323 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3324
3325 operands.push_back(spv::ImageOperandsLodMask);
3326 operands.push_back(*opIt++);
3327#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003328 }
3329
3330 // Create the return type that was a special structure
3331 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003332 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003333 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3334 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3335
3336 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3337
3338 // Decode the return type
3339 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3340 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003341 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003342 // Process image atomic operations
3343
3344 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3345 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003346 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003347
John Kessenich8c8505c2016-07-26 12:50:38 -06003348 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003349 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003350
3351 std::vector<spv::Id> operands;
3352 operands.push_back(pointer);
3353 for (; opIt != arguments.end(); ++opIt)
3354 operands.push_back(*opIt);
3355
John Kessenich8c8505c2016-07-26 12:50:38 -06003356 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003357 }
3358 }
3359
amhagan05506bb2017-06-13 16:53:02 -04003360#ifdef AMD_EXTENSIONS
3361 // Check for fragment mask functions other than queries
3362 if (cracked.fragMask) {
3363 assert(sampler.ms);
3364
3365 auto opIt = arguments.begin();
3366 std::vector<spv::Id> operands;
3367
3368 // Extract the image if necessary
3369 if (builder.isSampledImage(params.sampler))
3370 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3371
3372 operands.push_back(params.sampler);
3373 ++opIt;
3374
3375 if (sampler.isSubpass()) {
3376 // add on the (0,0) coordinate
3377 spv::Id zero = builder.makeIntConstant(0);
3378 std::vector<spv::Id> comps;
3379 comps.push_back(zero);
3380 comps.push_back(zero);
3381 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3382 }
3383
3384 for (; opIt != arguments.end(); ++opIt)
3385 operands.push_back(*opIt);
3386
3387 spv::Op fragMaskOp = spv::OpNop;
3388 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3389 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3390 else if (node->getOp() == glslang::EOpFragmentFetch)
3391 fragMaskOp = spv::OpFragmentFetchAMD;
3392
3393 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3394 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3395 return builder.createOp(fragMaskOp, resultType(), operands);
3396 }
3397#endif
3398
Rex Xufc618912015-09-09 16:42:49 +08003399 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003400 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003401 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3402
John Kessenichfc51d282015-08-19 13:34:18 -06003403 // check for bias argument
3404 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003405#ifdef AMD_EXTENSIONS
3406 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3407#else
Rex Xu71519fe2015-11-11 15:35:47 +08003408 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003409#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003410 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003411#ifdef AMD_EXTENSIONS
3412 if (cracked.gather)
3413 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3414#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003415 if (cracked.offset)
3416 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003417#ifdef AMD_EXTENSIONS
3418 else if (cracked.offsets)
3419 ++nonBiasArgCount;
3420#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003421 if (cracked.grad)
3422 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003423 if (cracked.lodClamp)
3424 ++nonBiasArgCount;
3425 if (sparse)
3426 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003427
3428 if ((int)arguments.size() > nonBiasArgCount)
3429 bias = true;
3430 }
3431
John Kessenicha5c33d62016-06-02 23:45:21 -06003432 // See if the sampler param should really be just the SPV image part
3433 if (cracked.fetch) {
3434 // a fetch needs to have the image extracted first
3435 if (builder.isSampledImage(params.sampler))
3436 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3437 }
3438
Rex Xu225e0fc2016-11-17 17:47:59 +08003439#ifdef AMD_EXTENSIONS
3440 if (cracked.gather) {
3441 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3442 if (bias || cracked.lod ||
3443 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3444 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003445 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003446 }
3447 }
3448#endif
3449
John Kessenichfc51d282015-08-19 13:34:18 -06003450 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003451
John Kessenichfc51d282015-08-19 13:34:18 -06003452 params.coords = arguments[1];
3453 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003454 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003455
3456 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003457 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003458 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003459 ++extraArgs;
3460 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003461 params.Dref = arguments[2];
3462 ++extraArgs;
3463 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003464 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003465 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003466 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003467 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003468 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003469 dRefComp = builder.getNumComponents(params.coords) - 1;
3470 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003471 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3472 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003473
3474 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003475 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003476 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003477 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003478 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3479 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3480 noImplicitLod = true;
3481 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003482
3483 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003484 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003485 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003486 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003487 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003488
3489 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003490 if (cracked.grad) {
3491 params.gradX = arguments[2 + extraArgs];
3492 params.gradY = arguments[3 + extraArgs];
3493 extraArgs += 2;
3494 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003495
3496 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003497 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003498 params.offset = arguments[2 + extraArgs];
3499 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003500 } else if (cracked.offsets) {
3501 params.offsets = arguments[2 + extraArgs];
3502 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003503 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003504
3505 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003506 if (cracked.lodClamp) {
3507 params.lodClamp = arguments[2 + extraArgs];
3508 ++extraArgs;
3509 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003510
3511 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003512 if (sparse) {
3513 params.texelOut = arguments[2 + extraArgs];
3514 ++extraArgs;
3515 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003516
John Kessenich76d4dfc2016-06-16 12:43:23 -06003517 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003518 if (cracked.gather && ! sampler.shadow) {
3519 // default component is 0, if missing, otherwise an argument
3520 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003521 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003522 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003523 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003524 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003525 }
3526
3527 // bias
3528 if (bias) {
3529 params.bias = arguments[2 + extraArgs];
3530 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003531 }
John Kessenichfc51d282015-08-19 13:34:18 -06003532
John Kessenich65336482016-06-16 14:06:26 -06003533 // projective component (might not to move)
3534 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3535 // are divided by the last component of P."
3536 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3537 // unused components will appear after all used components."
3538 if (cracked.proj) {
3539 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3540 int projTargetComp;
3541 switch (sampler.dim) {
3542 case glslang::Esd1D: projTargetComp = 1; break;
3543 case glslang::Esd2D: projTargetComp = 2; break;
3544 case glslang::EsdRect: projTargetComp = 2; break;
3545 default: projTargetComp = projSourceComp; break;
3546 }
3547 // copy the projective coordinate if we have to
3548 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003549 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003550 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3551 projSourceComp);
3552 params.coords = builder.createCompositeInsert(projComp, params.coords,
3553 builder.getTypeId(params.coords), projTargetComp);
3554 }
3555 }
3556
John Kessenich8c8505c2016-07-26 12:50:38 -06003557 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003558}
3559
3560spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3561{
3562 // Grab the function's pointer from the previously created function
3563 spv::Function* function = functionMap[node->getName().c_str()];
3564 if (! function)
3565 return 0;
3566
3567 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3568 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3569
LoopDawga5d86162017-09-10 09:46:55 -06003570 // Encapsulate lvalue logic, used in several places below, for safety.
LoopDawg76117922017-09-06 14:59:06 -06003571 const auto isLValue = [](int qualifier, const glslang::TType& paramType) -> bool {
3572 return qualifier != glslang::EvqConstReadOnly || paramType.containsOpaque();
3573 };
3574
John Kessenich140f3df2015-06-26 16:58:36 -06003575 // See comments in makeFunctions() for details about the semantics for parameter passing.
3576 //
3577 // These imply we need a four step process:
3578 // 1. Evaluate the arguments
3579 // 2. Allocate and make copies of in, out, and inout arguments
3580 // 3. Make the call
3581 // 4. Copy back the results
3582
3583 // 1. Evaluate the arguments
3584 std::vector<spv::Builder::AccessChain> lValues;
3585 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003586 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003587 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003588 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003589 // build l-value
3590 builder.clearAccessChain();
3591 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003592 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003593 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
LoopDawg76117922017-09-06 14:59:06 -06003594 if (isLValue(qualifiers[a], paramType)) {
John Kessenich140f3df2015-06-26 16:58:36 -06003595 // save l-value
3596 lValues.push_back(builder.getAccessChain());
3597 } else {
3598 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003599 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003600 }
3601 }
3602
3603 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3604 // copy the original into that space.
3605 //
3606 // Also, build up the list of actual arguments to pass in for the call
3607 int lValueCount = 0;
3608 int rValueCount = 0;
3609 std::vector<spv::Id> spvArgs;
3610 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 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003613 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003614 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3615 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003616 builder.setAccessChain(lValues[lValueCount]);
3617 arg = builder.accessChainGetLValue();
3618 ++lValueCount;
LoopDawg76117922017-09-06 14:59:06 -06003619 } else if (isLValue(qualifiers[a], paramType)) {
John Kessenich140f3df2015-06-26 16:58:36 -06003620 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003621 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3622 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3623 // need to copy the input into output space
3624 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003625 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003626 builder.clearAccessChain();
3627 builder.setAccessChainLValue(arg);
3628 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003629 }
3630 ++lValueCount;
3631 } else {
3632 arg = rValues[rValueCount];
3633 ++rValueCount;
3634 }
3635 spvArgs.push_back(arg);
3636 }
3637
3638 // 3. Make the call.
3639 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003640 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003641
3642 // 4. Copy back out an "out" arguments.
3643 lValueCount = 0;
3644 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003645 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
LoopDawg76117922017-09-06 14:59:06 -06003646 if (isLValue(qualifiers[a], paramType)) {
John Kessenich140f3df2015-06-26 16:58:36 -06003647 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3648 spv::Id copy = builder.createLoad(spvArgs[a]);
3649 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003650 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003651 }
3652 ++lValueCount;
3653 }
3654 }
3655
3656 return result;
3657}
3658
3659// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003660spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3661 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003662 spv::Id typeId, spv::Id left, spv::Id right,
3663 glslang::TBasicType typeProxy, bool reduceComparison)
3664{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003665#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003666 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003667 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3668#else
Rex Xucabbb782017-03-24 13:41:14 +08003669 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003670 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003671#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003672 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003673
3674 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003675 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003676 bool comparison = false;
3677
3678 switch (op) {
3679 case glslang::EOpAdd:
3680 case glslang::EOpAddAssign:
3681 if (isFloat)
3682 binOp = spv::OpFAdd;
3683 else
3684 binOp = spv::OpIAdd;
3685 break;
3686 case glslang::EOpSub:
3687 case glslang::EOpSubAssign:
3688 if (isFloat)
3689 binOp = spv::OpFSub;
3690 else
3691 binOp = spv::OpISub;
3692 break;
3693 case glslang::EOpMul:
3694 case glslang::EOpMulAssign:
3695 if (isFloat)
3696 binOp = spv::OpFMul;
3697 else
3698 binOp = spv::OpIMul;
3699 break;
3700 case glslang::EOpVectorTimesScalar:
3701 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003702 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003703 if (builder.isVector(right))
3704 std::swap(left, right);
3705 assert(builder.isScalar(right));
3706 needMatchingVectors = false;
3707 binOp = spv::OpVectorTimesScalar;
3708 } else
3709 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003710 break;
3711 case glslang::EOpVectorTimesMatrix:
3712 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003713 binOp = spv::OpVectorTimesMatrix;
3714 break;
3715 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003716 binOp = spv::OpMatrixTimesVector;
3717 break;
3718 case glslang::EOpMatrixTimesScalar:
3719 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003720 binOp = spv::OpMatrixTimesScalar;
3721 break;
3722 case glslang::EOpMatrixTimesMatrix:
3723 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003724 binOp = spv::OpMatrixTimesMatrix;
3725 break;
3726 case glslang::EOpOuterProduct:
3727 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003728 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003729 break;
3730
3731 case glslang::EOpDiv:
3732 case glslang::EOpDivAssign:
3733 if (isFloat)
3734 binOp = spv::OpFDiv;
3735 else if (isUnsigned)
3736 binOp = spv::OpUDiv;
3737 else
3738 binOp = spv::OpSDiv;
3739 break;
3740 case glslang::EOpMod:
3741 case glslang::EOpModAssign:
3742 if (isFloat)
3743 binOp = spv::OpFMod;
3744 else if (isUnsigned)
3745 binOp = spv::OpUMod;
3746 else
3747 binOp = spv::OpSMod;
3748 break;
3749 case glslang::EOpRightShift:
3750 case glslang::EOpRightShiftAssign:
3751 if (isUnsigned)
3752 binOp = spv::OpShiftRightLogical;
3753 else
3754 binOp = spv::OpShiftRightArithmetic;
3755 break;
3756 case glslang::EOpLeftShift:
3757 case glslang::EOpLeftShiftAssign:
3758 binOp = spv::OpShiftLeftLogical;
3759 break;
3760 case glslang::EOpAnd:
3761 case glslang::EOpAndAssign:
3762 binOp = spv::OpBitwiseAnd;
3763 break;
3764 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003765 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003766 binOp = spv::OpLogicalAnd;
3767 break;
3768 case glslang::EOpInclusiveOr:
3769 case glslang::EOpInclusiveOrAssign:
3770 binOp = spv::OpBitwiseOr;
3771 break;
3772 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003773 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003774 binOp = spv::OpLogicalOr;
3775 break;
3776 case glslang::EOpExclusiveOr:
3777 case glslang::EOpExclusiveOrAssign:
3778 binOp = spv::OpBitwiseXor;
3779 break;
3780 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003781 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003782 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003783 break;
3784
3785 case glslang::EOpLessThan:
3786 case glslang::EOpGreaterThan:
3787 case glslang::EOpLessThanEqual:
3788 case glslang::EOpGreaterThanEqual:
3789 case glslang::EOpEqual:
3790 case glslang::EOpNotEqual:
3791 case glslang::EOpVectorEqual:
3792 case glslang::EOpVectorNotEqual:
3793 comparison = true;
3794 break;
3795 default:
3796 break;
3797 }
3798
John Kessenich7c1aa102015-10-15 13:29:11 -06003799 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003800 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003801 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003802 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003803 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003804
3805 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003806 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003807 builder.promoteScalar(precision, left, right);
3808
qining25262b32016-05-06 17:25:16 -04003809 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3810 addDecoration(result, noContraction);
3811 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003812 }
3813
3814 if (! comparison)
3815 return 0;
3816
John Kessenich7c1aa102015-10-15 13:29:11 -06003817 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003818
John Kessenich4583b612016-08-07 19:14:22 -06003819 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3820 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003821 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003822
3823 switch (op) {
3824 case glslang::EOpLessThan:
3825 if (isFloat)
3826 binOp = spv::OpFOrdLessThan;
3827 else if (isUnsigned)
3828 binOp = spv::OpULessThan;
3829 else
3830 binOp = spv::OpSLessThan;
3831 break;
3832 case glslang::EOpGreaterThan:
3833 if (isFloat)
3834 binOp = spv::OpFOrdGreaterThan;
3835 else if (isUnsigned)
3836 binOp = spv::OpUGreaterThan;
3837 else
3838 binOp = spv::OpSGreaterThan;
3839 break;
3840 case glslang::EOpLessThanEqual:
3841 if (isFloat)
3842 binOp = spv::OpFOrdLessThanEqual;
3843 else if (isUnsigned)
3844 binOp = spv::OpULessThanEqual;
3845 else
3846 binOp = spv::OpSLessThanEqual;
3847 break;
3848 case glslang::EOpGreaterThanEqual:
3849 if (isFloat)
3850 binOp = spv::OpFOrdGreaterThanEqual;
3851 else if (isUnsigned)
3852 binOp = spv::OpUGreaterThanEqual;
3853 else
3854 binOp = spv::OpSGreaterThanEqual;
3855 break;
3856 case glslang::EOpEqual:
3857 case glslang::EOpVectorEqual:
3858 if (isFloat)
3859 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003860 else if (isBool)
3861 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003862 else
3863 binOp = spv::OpIEqual;
3864 break;
3865 case glslang::EOpNotEqual:
3866 case glslang::EOpVectorNotEqual:
3867 if (isFloat)
3868 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003869 else if (isBool)
3870 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003871 else
3872 binOp = spv::OpINotEqual;
3873 break;
3874 default:
3875 break;
3876 }
3877
qining25262b32016-05-06 17:25:16 -04003878 if (binOp != spv::OpNop) {
3879 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3880 addDecoration(result, noContraction);
3881 return builder.setPrecision(result, precision);
3882 }
John Kessenich140f3df2015-06-26 16:58:36 -06003883
3884 return 0;
3885}
3886
John Kessenich04bb8a02015-12-12 12:28:14 -07003887//
3888// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3889// These can be any of:
3890//
3891// matrix * scalar
3892// scalar * matrix
3893// matrix * matrix linear algebraic
3894// matrix * vector
3895// vector * matrix
3896// matrix * matrix componentwise
3897// matrix op matrix op in {+, -, /}
3898// matrix op scalar op in {+, -, /}
3899// scalar op matrix op in {+, -, /}
3900//
qining25262b32016-05-06 17:25:16 -04003901spv::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 -07003902{
3903 bool firstClass = true;
3904
3905 // First, handle first-class matrix operations (* and matrix/scalar)
3906 switch (op) {
3907 case spv::OpFDiv:
3908 if (builder.isMatrix(left) && builder.isScalar(right)) {
3909 // turn matrix / scalar into a multiply...
3910 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3911 op = spv::OpMatrixTimesScalar;
3912 } else
3913 firstClass = false;
3914 break;
3915 case spv::OpMatrixTimesScalar:
3916 if (builder.isMatrix(right))
3917 std::swap(left, right);
3918 assert(builder.isScalar(right));
3919 break;
3920 case spv::OpVectorTimesMatrix:
3921 assert(builder.isVector(left));
3922 assert(builder.isMatrix(right));
3923 break;
3924 case spv::OpMatrixTimesVector:
3925 assert(builder.isMatrix(left));
3926 assert(builder.isVector(right));
3927 break;
3928 case spv::OpMatrixTimesMatrix:
3929 assert(builder.isMatrix(left));
3930 assert(builder.isMatrix(right));
3931 break;
3932 default:
3933 firstClass = false;
3934 break;
3935 }
3936
qining25262b32016-05-06 17:25:16 -04003937 if (firstClass) {
3938 spv::Id result = builder.createBinOp(op, typeId, left, right);
3939 addDecoration(result, noContraction);
3940 return builder.setPrecision(result, precision);
3941 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003942
LoopDawg592860c2016-06-09 08:57:35 -06003943 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003944 // The result type of all of them is the same type as the (a) matrix operand.
3945 // The algorithm is to:
3946 // - break the matrix(es) into vectors
3947 // - smear any scalar to a vector
3948 // - do vector operations
3949 // - make a matrix out the vector results
3950 switch (op) {
3951 case spv::OpFAdd:
3952 case spv::OpFSub:
3953 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003954 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003955 case spv::OpFMul:
3956 {
3957 // one time set up...
3958 bool leftMat = builder.isMatrix(left);
3959 bool rightMat = builder.isMatrix(right);
3960 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3961 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3962 spv::Id scalarType = builder.getScalarTypeId(typeId);
3963 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3964 std::vector<spv::Id> results;
3965 spv::Id smearVec = spv::NoResult;
3966 if (builder.isScalar(left))
3967 smearVec = builder.smearScalar(precision, left, vecType);
3968 else if (builder.isScalar(right))
3969 smearVec = builder.smearScalar(precision, right, vecType);
3970
3971 // do each vector op
3972 for (unsigned int c = 0; c < numCols; ++c) {
3973 std::vector<unsigned int> indexes;
3974 indexes.push_back(c);
3975 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3976 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003977 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3978 addDecoration(result, noContraction);
3979 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003980 }
3981
3982 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003983 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003984 }
3985 default:
3986 assert(0);
3987 return spv::NoResult;
3988 }
3989}
3990
qining25262b32016-05-06 17:25:16 -04003991spv::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 -06003992{
3993 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003994 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003995 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003996#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003997 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003998 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3999#else
Rex Xucabbb782017-03-24 13:41:14 +08004000 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08004001 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004002#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004003
4004 switch (op) {
4005 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004006 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004007 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004008 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04004009 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004010 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004011 unaryOp = spv::OpSNegate;
4012 break;
4013
4014 case glslang::EOpLogicalNot:
4015 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004016 unaryOp = spv::OpLogicalNot;
4017 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004018 case glslang::EOpBitwiseNot:
4019 unaryOp = spv::OpNot;
4020 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004021
John Kessenich140f3df2015-06-26 16:58:36 -06004022 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004023 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004024 break;
4025 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004026 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004027 break;
4028 case glslang::EOpTranspose:
4029 unaryOp = spv::OpTranspose;
4030 break;
4031
4032 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004033 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004034 break;
4035 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004036 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004037 break;
4038 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004039 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004040 break;
4041 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004042 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004043 break;
4044 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004045 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004046 break;
4047 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004048 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004049 break;
4050 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004051 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004052 break;
4053 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004054 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004055 break;
4056
4057 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004058 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004059 break;
4060 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004061 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004062 break;
4063 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004064 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004065 break;
4066 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004067 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004068 break;
4069 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004070 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004071 break;
4072 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004073 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004074 break;
4075
4076 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004077 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004078 break;
4079 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004080 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004081 break;
4082
4083 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004084 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004085 break;
4086 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004087 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004088 break;
4089 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004090 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004091 break;
4092 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004093 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004094 break;
4095 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004096 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004097 break;
4098 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004099 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004100 break;
4101
4102 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004103 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004104 break;
4105 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004106 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004107 break;
4108 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004109 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004110 break;
4111 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004112 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004113 break;
4114 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004115 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004116 break;
4117 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004118 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004119 break;
4120
4121 case glslang::EOpIsNan:
4122 unaryOp = spv::OpIsNan;
4123 break;
4124 case glslang::EOpIsInf:
4125 unaryOp = spv::OpIsInf;
4126 break;
LoopDawg592860c2016-06-09 08:57:35 -06004127 case glslang::EOpIsFinite:
4128 unaryOp = spv::OpIsFinite;
4129 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004130
Rex Xucbc426e2015-12-15 16:03:10 +08004131 case glslang::EOpFloatBitsToInt:
4132 case glslang::EOpFloatBitsToUint:
4133 case glslang::EOpIntBitsToFloat:
4134 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004135 case glslang::EOpDoubleBitsToInt64:
4136 case glslang::EOpDoubleBitsToUint64:
4137 case glslang::EOpInt64BitsToDouble:
4138 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004139#ifdef AMD_EXTENSIONS
4140 case glslang::EOpFloat16BitsToInt16:
4141 case glslang::EOpFloat16BitsToUint16:
4142 case glslang::EOpInt16BitsToFloat16:
4143 case glslang::EOpUint16BitsToFloat16:
4144#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004145 unaryOp = spv::OpBitcast;
4146 break;
4147
John Kessenich140f3df2015-06-26 16:58:36 -06004148 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004149 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004150 break;
4151 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004152 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004153 break;
4154 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004155 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004156 break;
4157 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004158 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004159 break;
4160 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004161 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004162 break;
4163 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004164 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004165 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004166 case glslang::EOpPackSnorm4x8:
4167 libCall = spv::GLSLstd450PackSnorm4x8;
4168 break;
4169 case glslang::EOpUnpackSnorm4x8:
4170 libCall = spv::GLSLstd450UnpackSnorm4x8;
4171 break;
4172 case glslang::EOpPackUnorm4x8:
4173 libCall = spv::GLSLstd450PackUnorm4x8;
4174 break;
4175 case glslang::EOpUnpackUnorm4x8:
4176 libCall = spv::GLSLstd450UnpackUnorm4x8;
4177 break;
4178 case glslang::EOpPackDouble2x32:
4179 libCall = spv::GLSLstd450PackDouble2x32;
4180 break;
4181 case glslang::EOpUnpackDouble2x32:
4182 libCall = spv::GLSLstd450UnpackDouble2x32;
4183 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004184
Rex Xu8ff43de2016-04-22 16:51:45 +08004185 case glslang::EOpPackInt2x32:
4186 case glslang::EOpUnpackInt2x32:
4187 case glslang::EOpPackUint2x32:
4188 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004189 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004190 break;
4191
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004192#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004193 case glslang::EOpPackInt2x16:
4194 case glslang::EOpUnpackInt2x16:
4195 case glslang::EOpPackUint2x16:
4196 case glslang::EOpUnpackUint2x16:
4197 case glslang::EOpPackInt4x16:
4198 case glslang::EOpUnpackInt4x16:
4199 case glslang::EOpPackUint4x16:
4200 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004201 case glslang::EOpPackFloat2x16:
4202 case glslang::EOpUnpackFloat2x16:
4203 unaryOp = spv::OpBitcast;
4204 break;
4205#endif
4206
John Kessenich140f3df2015-06-26 16:58:36 -06004207 case glslang::EOpDPdx:
4208 unaryOp = spv::OpDPdx;
4209 break;
4210 case glslang::EOpDPdy:
4211 unaryOp = spv::OpDPdy;
4212 break;
4213 case glslang::EOpFwidth:
4214 unaryOp = spv::OpFwidth;
4215 break;
4216 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004217 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004218 unaryOp = spv::OpDPdxFine;
4219 break;
4220 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004221 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004222 unaryOp = spv::OpDPdyFine;
4223 break;
4224 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004225 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004226 unaryOp = spv::OpFwidthFine;
4227 break;
4228 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004229 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004230 unaryOp = spv::OpDPdxCoarse;
4231 break;
4232 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004233 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004234 unaryOp = spv::OpDPdyCoarse;
4235 break;
4236 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004237 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004238 unaryOp = spv::OpFwidthCoarse;
4239 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004240 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004241 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004242 libCall = spv::GLSLstd450InterpolateAtCentroid;
4243 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004244 case glslang::EOpAny:
4245 unaryOp = spv::OpAny;
4246 break;
4247 case glslang::EOpAll:
4248 unaryOp = spv::OpAll;
4249 break;
4250
4251 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004252 if (isFloat)
4253 libCall = spv::GLSLstd450FAbs;
4254 else
4255 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004256 break;
4257 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004258 if (isFloat)
4259 libCall = spv::GLSLstd450FSign;
4260 else
4261 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004262 break;
4263
John Kessenichfc51d282015-08-19 13:34:18 -06004264 case glslang::EOpAtomicCounterIncrement:
4265 case glslang::EOpAtomicCounterDecrement:
4266 case glslang::EOpAtomicCounter:
4267 {
4268 // Handle all of the atomics in one place, in createAtomicOperation()
4269 std::vector<spv::Id> operands;
4270 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004271 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004272 }
4273
John Kessenichfc51d282015-08-19 13:34:18 -06004274 case glslang::EOpBitFieldReverse:
4275 unaryOp = spv::OpBitReverse;
4276 break;
4277 case glslang::EOpBitCount:
4278 unaryOp = spv::OpBitCount;
4279 break;
4280 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004281 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004282 break;
4283 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004284 if (isUnsigned)
4285 libCall = spv::GLSLstd450FindUMsb;
4286 else
4287 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004288 break;
4289
Rex Xu574ab042016-04-14 16:53:07 +08004290 case glslang::EOpBallot:
4291 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004292 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004293 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004294 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004295#ifdef AMD_EXTENSIONS
4296 case glslang::EOpMinInvocations:
4297 case glslang::EOpMaxInvocations:
4298 case glslang::EOpAddInvocations:
4299 case glslang::EOpMinInvocationsNonUniform:
4300 case glslang::EOpMaxInvocationsNonUniform:
4301 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004302 case glslang::EOpMinInvocationsInclusiveScan:
4303 case glslang::EOpMaxInvocationsInclusiveScan:
4304 case glslang::EOpAddInvocationsInclusiveScan:
4305 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4306 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4307 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4308 case glslang::EOpMinInvocationsExclusiveScan:
4309 case glslang::EOpMaxInvocationsExclusiveScan:
4310 case glslang::EOpAddInvocationsExclusiveScan:
4311 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4312 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4313 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004314#endif
Rex Xu51596642016-09-21 18:56:12 +08004315 {
4316 std::vector<spv::Id> operands;
4317 operands.push_back(operand);
4318 return createInvocationsOperation(op, typeId, operands, typeProxy);
4319 }
Rex Xu9d93a232016-05-05 12:30:44 +08004320
4321#ifdef AMD_EXTENSIONS
4322 case glslang::EOpMbcnt:
4323 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4324 libCall = spv::MbcntAMD;
4325 break;
4326
4327 case glslang::EOpCubeFaceIndex:
4328 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4329 libCall = spv::CubeFaceIndexAMD;
4330 break;
4331
4332 case glslang::EOpCubeFaceCoord:
4333 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4334 libCall = spv::CubeFaceCoordAMD;
4335 break;
4336#endif
Rex Xu338b1852016-05-05 20:38:33 +08004337
John Kessenich140f3df2015-06-26 16:58:36 -06004338 default:
4339 return 0;
4340 }
4341
4342 spv::Id id;
4343 if (libCall >= 0) {
4344 std::vector<spv::Id> args;
4345 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004346 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004347 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004348 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004349 }
John Kessenich140f3df2015-06-26 16:58:36 -06004350
qining25262b32016-05-06 17:25:16 -04004351 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004352 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004353}
4354
John Kessenich7a53f762016-01-20 11:19:27 -07004355// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004356spv::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 -07004357{
4358 // Handle unary operations vector by vector.
4359 // The result type is the same type as the original type.
4360 // The algorithm is to:
4361 // - break the matrix into vectors
4362 // - apply the operation to each vector
4363 // - make a matrix out the vector results
4364
4365 // get the types sorted out
4366 int numCols = builder.getNumColumns(operand);
4367 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004368 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4369 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004370 std::vector<spv::Id> results;
4371
4372 // do each vector op
4373 for (int c = 0; c < numCols; ++c) {
4374 std::vector<unsigned int> indexes;
4375 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004376 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4377 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4378 addDecoration(destVec, noContraction);
4379 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004380 }
4381
4382 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004383 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004384}
4385
Rex Xu73e3ce72016-04-27 18:48:17 +08004386spv::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 -06004387{
4388 spv::Op convOp = spv::OpNop;
4389 spv::Id zero = 0;
4390 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004391 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004392
4393 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4394
4395 switch (op) {
4396 case glslang::EOpConvIntToBool:
4397 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004398 case glslang::EOpConvInt64ToBool:
4399 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004400#ifdef AMD_EXTENSIONS
4401 case glslang::EOpConvInt16ToBool:
4402 case glslang::EOpConvUint16ToBool:
4403#endif
4404 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4405 zero = builder.makeUint64Constant(0);
4406#ifdef AMD_EXTENSIONS
4407 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4408 zero = builder.makeUint16Constant(0);
4409#endif
4410 else
4411 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004412 zero = makeSmearedConstant(zero, vectorSize);
4413 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4414
4415 case glslang::EOpConvFloatToBool:
4416 zero = builder.makeFloatConstant(0.0F);
4417 zero = makeSmearedConstant(zero, vectorSize);
4418 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4419
4420 case glslang::EOpConvDoubleToBool:
4421 zero = builder.makeDoubleConstant(0.0);
4422 zero = makeSmearedConstant(zero, vectorSize);
4423 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4424
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004425#ifdef AMD_EXTENSIONS
4426 case glslang::EOpConvFloat16ToBool:
4427 zero = builder.makeFloat16Constant(0.0F);
4428 zero = makeSmearedConstant(zero, vectorSize);
4429 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4430#endif
4431
John Kessenich140f3df2015-06-26 16:58:36 -06004432 case glslang::EOpConvBoolToFloat:
4433 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004434 zero = builder.makeFloatConstant(0.0F);
4435 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004436 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004437
John Kessenich140f3df2015-06-26 16:58:36 -06004438 case glslang::EOpConvBoolToDouble:
4439 convOp = spv::OpSelect;
4440 zero = builder.makeDoubleConstant(0.0);
4441 one = builder.makeDoubleConstant(1.0);
4442 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004443
4444#ifdef AMD_EXTENSIONS
4445 case glslang::EOpConvBoolToFloat16:
4446 convOp = spv::OpSelect;
4447 zero = builder.makeFloat16Constant(0.0F);
4448 one = builder.makeFloat16Constant(1.0F);
4449 break;
4450#endif
4451
John Kessenich140f3df2015-06-26 16:58:36 -06004452 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004453 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004454#ifdef AMD_EXTENSIONS
4455 case glslang::EOpConvBoolToInt16:
4456#endif
4457 if (op == glslang::EOpConvBoolToInt64)
4458 zero = builder.makeInt64Constant(0);
4459#ifdef AMD_EXTENSIONS
4460 else if (op == glslang::EOpConvBoolToInt16)
4461 zero = builder.makeInt16Constant(0);
4462#endif
4463 else
4464 zero = builder.makeIntConstant(0);
4465
4466 if (op == glslang::EOpConvBoolToInt64)
4467 one = builder.makeInt64Constant(1);
4468#ifdef AMD_EXTENSIONS
4469 else if (op == glslang::EOpConvBoolToInt16)
4470 one = builder.makeInt16Constant(1);
4471#endif
4472 else
4473 one = builder.makeIntConstant(1);
4474
John Kessenich140f3df2015-06-26 16:58:36 -06004475 convOp = spv::OpSelect;
4476 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004477
John Kessenich140f3df2015-06-26 16:58:36 -06004478 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004479 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004480#ifdef AMD_EXTENSIONS
4481 case glslang::EOpConvBoolToUint16:
4482#endif
4483 if (op == glslang::EOpConvBoolToUint64)
4484 zero = builder.makeUint64Constant(0);
4485#ifdef AMD_EXTENSIONS
4486 else if (op == glslang::EOpConvBoolToUint16)
4487 zero = builder.makeUint16Constant(0);
4488#endif
4489 else
4490 zero = builder.makeUintConstant(0);
4491
4492 if (op == glslang::EOpConvBoolToUint64)
4493 one = builder.makeUint64Constant(1);
4494#ifdef AMD_EXTENSIONS
4495 else if (op == glslang::EOpConvBoolToUint16)
4496 one = builder.makeUint16Constant(1);
4497#endif
4498 else
4499 one = builder.makeUintConstant(1);
4500
John Kessenich140f3df2015-06-26 16:58:36 -06004501 convOp = spv::OpSelect;
4502 break;
4503
4504 case glslang::EOpConvIntToFloat:
4505 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004506 case glslang::EOpConvInt64ToFloat:
4507 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004508#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004509 case glslang::EOpConvInt16ToFloat:
4510 case glslang::EOpConvInt16ToDouble:
4511 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004512 case glslang::EOpConvIntToFloat16:
4513 case glslang::EOpConvInt64ToFloat16:
4514#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004515 convOp = spv::OpConvertSToF;
4516 break;
4517
4518 case glslang::EOpConvUintToFloat:
4519 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004520 case glslang::EOpConvUint64ToFloat:
4521 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004522#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004523 case glslang::EOpConvUint16ToFloat:
4524 case glslang::EOpConvUint16ToDouble:
4525 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004526 case glslang::EOpConvUintToFloat16:
4527 case glslang::EOpConvUint64ToFloat16:
4528#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004529 convOp = spv::OpConvertUToF;
4530 break;
4531
4532 case glslang::EOpConvDoubleToFloat:
4533 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004534#ifdef AMD_EXTENSIONS
4535 case glslang::EOpConvDoubleToFloat16:
4536 case glslang::EOpConvFloat16ToDouble:
4537 case glslang::EOpConvFloatToFloat16:
4538 case glslang::EOpConvFloat16ToFloat:
4539#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004540 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004541 if (builder.isMatrixType(destType))
4542 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004543 break;
4544
4545 case glslang::EOpConvFloatToInt:
4546 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004547 case glslang::EOpConvFloatToInt64:
4548 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004549#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004550 case glslang::EOpConvFloatToInt16:
4551 case glslang::EOpConvDoubleToInt16:
4552 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004553 case glslang::EOpConvFloat16ToInt:
4554 case glslang::EOpConvFloat16ToInt64:
4555#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004556 convOp = spv::OpConvertFToS;
4557 break;
4558
4559 case glslang::EOpConvUintToInt:
4560 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004561 case glslang::EOpConvUint64ToInt64:
4562 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004563#ifdef AMD_EXTENSIONS
4564 case glslang::EOpConvUint16ToInt16:
4565 case glslang::EOpConvInt16ToUint16:
4566#endif
qininge24aa5e2016-04-07 15:40:27 -04004567 if (builder.isInSpecConstCodeGenMode()) {
4568 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004569 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4570 zero = builder.makeUint64Constant(0);
4571#ifdef AMD_EXTENSIONS
4572 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4573 zero = builder.makeUint16Constant(0);
4574#endif
4575 else
4576 zero = builder.makeUintConstant(0);
4577
qining189b2032016-04-12 23:16:20 -04004578 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004579 // Use OpIAdd, instead of OpBitcast to do the conversion when
4580 // generating for OpSpecConstantOp instruction.
4581 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4582 }
4583 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004584 convOp = spv::OpBitcast;
4585 break;
4586
4587 case glslang::EOpConvFloatToUint:
4588 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004589 case glslang::EOpConvFloatToUint64:
4590 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004591#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004592 case glslang::EOpConvFloatToUint16:
4593 case glslang::EOpConvDoubleToUint16:
4594 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004595 case glslang::EOpConvFloat16ToUint:
4596 case glslang::EOpConvFloat16ToUint64:
4597#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004598 convOp = spv::OpConvertFToU;
4599 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004600
4601 case glslang::EOpConvIntToInt64:
4602 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004603#ifdef AMD_EXTENSIONS
4604 case glslang::EOpConvIntToInt16:
4605 case glslang::EOpConvInt16ToInt:
4606 case glslang::EOpConvInt64ToInt16:
4607 case glslang::EOpConvInt16ToInt64:
4608#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004609 convOp = spv::OpSConvert;
4610 break;
4611
4612 case glslang::EOpConvUintToUint64:
4613 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004614#ifdef AMD_EXTENSIONS
4615 case glslang::EOpConvUintToUint16:
4616 case glslang::EOpConvUint16ToUint:
4617 case glslang::EOpConvUint64ToUint16:
4618 case glslang::EOpConvUint16ToUint64:
4619#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004620 convOp = spv::OpUConvert;
4621 break;
4622
4623 case glslang::EOpConvIntToUint64:
4624 case glslang::EOpConvInt64ToUint:
4625 case glslang::EOpConvUint64ToInt:
4626 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004627#ifdef AMD_EXTENSIONS
4628 case glslang::EOpConvInt16ToUint:
4629 case glslang::EOpConvUintToInt16:
4630 case glslang::EOpConvInt16ToUint64:
4631 case glslang::EOpConvUint64ToInt16:
4632 case glslang::EOpConvUint16ToInt:
4633 case glslang::EOpConvIntToUint16:
4634 case glslang::EOpConvUint16ToInt64:
4635 case glslang::EOpConvInt64ToUint16:
4636#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004637 // OpSConvert/OpUConvert + OpBitCast
4638 switch (op) {
4639 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004640#ifdef AMD_EXTENSIONS
4641 case glslang::EOpConvInt16ToUint64:
4642#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004643 convOp = spv::OpSConvert;
4644 type = builder.makeIntType(64);
4645 break;
4646 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004647#ifdef AMD_EXTENSIONS
4648 case glslang::EOpConvInt16ToUint:
4649#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004650 convOp = spv::OpSConvert;
4651 type = builder.makeIntType(32);
4652 break;
4653 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004654#ifdef AMD_EXTENSIONS
4655 case glslang::EOpConvUint16ToInt:
4656#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004657 convOp = spv::OpUConvert;
4658 type = builder.makeUintType(32);
4659 break;
4660 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004661#ifdef AMD_EXTENSIONS
4662 case glslang::EOpConvUint16ToInt64:
4663#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004664 convOp = spv::OpUConvert;
4665 type = builder.makeUintType(64);
4666 break;
Rex Xucabbb782017-03-24 13:41:14 +08004667#ifdef AMD_EXTENSIONS
4668 case glslang::EOpConvUintToInt16:
4669 case glslang::EOpConvUint64ToInt16:
4670 convOp = spv::OpUConvert;
4671 type = builder.makeUintType(16);
4672 break;
4673 case glslang::EOpConvIntToUint16:
4674 case glslang::EOpConvInt64ToUint16:
4675 convOp = spv::OpSConvert;
4676 type = builder.makeIntType(16);
4677 break;
4678#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004679 default:
4680 assert(0);
4681 break;
4682 }
4683
4684 if (vectorSize > 0)
4685 type = builder.makeVectorType(type, vectorSize);
4686
4687 operand = builder.createUnaryOp(convOp, type, operand);
4688
4689 if (builder.isInSpecConstCodeGenMode()) {
4690 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004691#ifdef AMD_EXTENSIONS
4692 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4693 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4694 zero = builder.makeUint64Constant(0);
4695 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4696 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4697 zero = builder.makeUint16Constant(0);
4698 else
4699 zero = builder.makeUintConstant(0);
4700#else
4701 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4702 zero = builder.makeUint64Constant(0);
4703 else
4704 zero = builder.makeUintConstant(0);
4705#endif
4706
Rex Xu8ff43de2016-04-22 16:51:45 +08004707 zero = makeSmearedConstant(zero, vectorSize);
4708 // Use OpIAdd, instead of OpBitcast to do the conversion when
4709 // generating for OpSpecConstantOp instruction.
4710 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4711 }
4712 // For normal run-time conversion instruction, use OpBitcast.
4713 convOp = spv::OpBitcast;
4714 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004715 default:
4716 break;
4717 }
4718
4719 spv::Id result = 0;
4720 if (convOp == spv::OpNop)
4721 return result;
4722
4723 if (convOp == spv::OpSelect) {
4724 zero = makeSmearedConstant(zero, vectorSize);
4725 one = makeSmearedConstant(one, vectorSize);
4726 result = builder.createTriOp(convOp, destType, operand, one, zero);
4727 } else
4728 result = builder.createUnaryOp(convOp, destType, operand);
4729
John Kessenich32cfd492016-02-02 12:37:46 -07004730 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004731}
4732
4733spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4734{
4735 if (vectorSize == 0)
4736 return constant;
4737
4738 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4739 std::vector<spv::Id> components;
4740 for (int c = 0; c < vectorSize; ++c)
4741 components.push_back(constant);
4742 return builder.makeCompositeConstant(vectorTypeId, components);
4743}
4744
John Kessenich426394d2015-07-23 10:22:48 -06004745// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004746spv::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 -06004747{
4748 spv::Op opCode = spv::OpNop;
4749
4750 switch (op) {
4751 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004752 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004753 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004754 opCode = spv::OpAtomicIAdd;
4755 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004756 case glslang::EOpAtomicCounterSubtract:
4757 opCode = spv::OpAtomicISub;
4758 break;
John Kessenich426394d2015-07-23 10:22:48 -06004759 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004760 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004761 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08004762 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004763 break;
4764 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004765 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004766 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08004767 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004768 break;
4769 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004770 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004771 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004772 opCode = spv::OpAtomicAnd;
4773 break;
4774 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004775 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004776 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004777 opCode = spv::OpAtomicOr;
4778 break;
4779 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004780 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004781 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004782 opCode = spv::OpAtomicXor;
4783 break;
4784 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004785 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004786 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004787 opCode = spv::OpAtomicExchange;
4788 break;
4789 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004790 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004791 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004792 opCode = spv::OpAtomicCompareExchange;
4793 break;
4794 case glslang::EOpAtomicCounterIncrement:
4795 opCode = spv::OpAtomicIIncrement;
4796 break;
4797 case glslang::EOpAtomicCounterDecrement:
4798 opCode = spv::OpAtomicIDecrement;
4799 break;
4800 case glslang::EOpAtomicCounter:
4801 opCode = spv::OpAtomicLoad;
4802 break;
4803 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004804 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004805 break;
4806 }
4807
Rex Xue8fe8b02017-09-26 15:42:56 +08004808 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
4809 builder.addCapability(spv::CapabilityInt64Atomics);
4810
John Kessenich426394d2015-07-23 10:22:48 -06004811 // Sort out the operands
4812 // - mapping from glslang -> SPV
4813 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004814 // - compare-exchange swaps the value and comparator
4815 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004816 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4817 auto opIt = operands.begin(); // walk the glslang operands
4818 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004819 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4820 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4821 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004822 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4823 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004824 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004825 spvAtomicOperands.push_back(*(opIt + 1));
4826 spvAtomicOperands.push_back(*opIt);
4827 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004828 }
John Kessenich426394d2015-07-23 10:22:48 -06004829
John Kessenich3e60a6f2015-09-14 22:45:16 -06004830 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004831 for (; opIt != operands.end(); ++opIt)
4832 spvAtomicOperands.push_back(*opIt);
4833
4834 return builder.createOp(opCode, typeId, spvAtomicOperands);
4835}
4836
John Kessenich91cef522016-05-05 16:45:40 -06004837// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004838spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004839{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004840#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004841 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004842 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004843#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004844
Rex Xu51596642016-09-21 18:56:12 +08004845 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004846 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004847 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4848
chaocf200da82016-12-20 12:44:35 -08004849 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4850 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004851 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4852 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004853 } else if (op == glslang::EOpAnyInvocation ||
4854 op == glslang::EOpAllInvocations ||
4855 op == glslang::EOpAllInvocationsEqual) {
4856 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4857 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004858 } else {
4859 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004860#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004861 if (op == glslang::EOpMinInvocationsNonUniform ||
4862 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004863 op == glslang::EOpAddInvocationsNonUniform ||
4864 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4865 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4866 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4867 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4868 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4869 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004870 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004871#endif
Rex Xu51596642016-09-21 18:56:12 +08004872
4873 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004874#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004875 switch (op) {
4876 case glslang::EOpMinInvocations:
4877 case glslang::EOpMaxInvocations:
4878 case glslang::EOpAddInvocations:
4879 case glslang::EOpMinInvocationsNonUniform:
4880 case glslang::EOpMaxInvocationsNonUniform:
4881 case glslang::EOpAddInvocationsNonUniform:
4882 groupOperation = spv::GroupOperationReduce;
4883 spvGroupOperands.push_back(groupOperation);
4884 break;
4885 case glslang::EOpMinInvocationsInclusiveScan:
4886 case glslang::EOpMaxInvocationsInclusiveScan:
4887 case glslang::EOpAddInvocationsInclusiveScan:
4888 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4889 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4890 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4891 groupOperation = spv::GroupOperationInclusiveScan;
4892 spvGroupOperands.push_back(groupOperation);
4893 break;
4894 case glslang::EOpMinInvocationsExclusiveScan:
4895 case glslang::EOpMaxInvocationsExclusiveScan:
4896 case glslang::EOpAddInvocationsExclusiveScan:
4897 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4898 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4899 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4900 groupOperation = spv::GroupOperationExclusiveScan;
4901 spvGroupOperands.push_back(groupOperation);
4902 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004903 default:
4904 break;
Rex Xu430ef402016-10-14 17:22:23 +08004905 }
Rex Xu9d93a232016-05-05 12:30:44 +08004906#endif
Rex Xu51596642016-09-21 18:56:12 +08004907 }
4908
4909 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4910 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004911
4912 switch (op) {
4913 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004914 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004915 break;
John Kessenich91cef522016-05-05 16:45:40 -06004916 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004917 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004918 break;
John Kessenich91cef522016-05-05 16:45:40 -06004919 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004920 opCode = spv::OpSubgroupAllEqualKHR;
4921 break;
Rex Xu51596642016-09-21 18:56:12 +08004922 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004923 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004924 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004925 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004926 break;
4927 case glslang::EOpReadFirstInvocation:
4928 opCode = spv::OpSubgroupFirstInvocationKHR;
4929 break;
4930 case glslang::EOpBallot:
4931 {
4932 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4933 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4934 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4935 //
4936 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4937 //
4938 spv::Id uintType = builder.makeUintType(32);
4939 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4940 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4941
4942 std::vector<spv::Id> components;
4943 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4944 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4945
4946 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4947 return builder.createUnaryOp(spv::OpBitcast, typeId,
4948 builder.createCompositeConstruct(uvec2Type, components));
4949 }
4950
Rex Xu9d93a232016-05-05 12:30:44 +08004951#ifdef AMD_EXTENSIONS
4952 case glslang::EOpMinInvocations:
4953 case glslang::EOpMaxInvocations:
4954 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004955 case glslang::EOpMinInvocationsInclusiveScan:
4956 case glslang::EOpMaxInvocationsInclusiveScan:
4957 case glslang::EOpAddInvocationsInclusiveScan:
4958 case glslang::EOpMinInvocationsExclusiveScan:
4959 case glslang::EOpMaxInvocationsExclusiveScan:
4960 case glslang::EOpAddInvocationsExclusiveScan:
4961 if (op == glslang::EOpMinInvocations ||
4962 op == glslang::EOpMinInvocationsInclusiveScan ||
4963 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004964 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004965 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004966 else {
4967 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004968 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004969 else
Rex Xu51596642016-09-21 18:56:12 +08004970 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004971 }
Rex Xu430ef402016-10-14 17:22:23 +08004972 } else if (op == glslang::EOpMaxInvocations ||
4973 op == glslang::EOpMaxInvocationsInclusiveScan ||
4974 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004975 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004976 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004977 else {
4978 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004979 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004980 else
Rex Xu51596642016-09-21 18:56:12 +08004981 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004982 }
4983 } else {
4984 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004985 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004986 else
Rex Xu51596642016-09-21 18:56:12 +08004987 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004988 }
4989
Rex Xu2bbbe062016-08-23 15:41:05 +08004990 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004991 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004992
4993 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004994 case glslang::EOpMinInvocationsNonUniform:
4995 case glslang::EOpMaxInvocationsNonUniform:
4996 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004997 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4998 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4999 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5000 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5001 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5002 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5003 if (op == glslang::EOpMinInvocationsNonUniform ||
5004 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5005 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005006 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005007 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005008 else {
5009 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005010 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005011 else
Rex Xu51596642016-09-21 18:56:12 +08005012 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005013 }
5014 }
Rex Xu430ef402016-10-14 17:22:23 +08005015 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5016 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5017 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005018 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005019 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005020 else {
5021 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005022 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005023 else
Rex Xu51596642016-09-21 18:56:12 +08005024 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005025 }
5026 }
5027 else {
5028 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005029 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005030 else
Rex Xu51596642016-09-21 18:56:12 +08005031 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005032 }
5033
Rex Xu2bbbe062016-08-23 15:41:05 +08005034 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005035 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005036
5037 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005038#endif
John Kessenich91cef522016-05-05 16:45:40 -06005039 default:
5040 logger->missingFunctionality("invocation operation");
5041 return spv::NoResult;
5042 }
Rex Xu51596642016-09-21 18:56:12 +08005043
5044 assert(opCode != spv::OpNop);
5045 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005046}
5047
Rex Xu2bbbe062016-08-23 15:41:05 +08005048// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005049spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005050{
Rex Xub7072052016-09-26 15:53:40 +08005051#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005052 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5053 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005054 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005055 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005056 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5057 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5058 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005059#else
5060 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5061 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005062 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5063 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005064#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005065
5066 // Handle group invocation operations scalar by scalar.
5067 // The result type is the same type as the original type.
5068 // The algorithm is to:
5069 // - break the vector into scalars
5070 // - apply the operation to each scalar
5071 // - make a vector out the scalar results
5072
5073 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005074 int numComponents = builder.getNumComponents(operands[0]);
5075 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005076 std::vector<spv::Id> results;
5077
5078 // do each scalar op
5079 for (int comp = 0; comp < numComponents; ++comp) {
5080 std::vector<unsigned int> indexes;
5081 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005082 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005083 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005084 if (op == spv::OpSubgroupReadInvocationKHR) {
5085 spvGroupOperands.push_back(scalar);
5086 spvGroupOperands.push_back(operands[1]);
5087 } else if (op == spv::OpGroupBroadcast) {
5088 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005089 spvGroupOperands.push_back(scalar);
5090 spvGroupOperands.push_back(operands[1]);
5091 } else {
chaocf200da82016-12-20 12:44:35 -08005092 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005093 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005094 spvGroupOperands.push_back(scalar);
5095 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005096
Rex Xub7072052016-09-26 15:53:40 +08005097 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005098 }
5099
5100 // put the pieces together
5101 return builder.createCompositeConstruct(typeId, results);
5102}
Rex Xu2bbbe062016-08-23 15:41:05 +08005103
John Kessenich5e4b1242015-08-06 22:53:06 -06005104spv::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 -06005105{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005106#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005107 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005108 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5109#else
Rex Xucabbb782017-03-24 13:41:14 +08005110 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005111 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005112#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005113
John Kessenich140f3df2015-06-26 16:58:36 -06005114 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005115 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005116 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005117 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005118 spv::Id typeId0 = 0;
5119 if (consumedOperands > 0)
5120 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005121 spv::Id typeId1 = 0;
5122 if (consumedOperands > 1)
5123 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005124 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005125
5126 switch (op) {
5127 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005128 if (isFloat)
5129 libCall = spv::GLSLstd450FMin;
5130 else if (isUnsigned)
5131 libCall = spv::GLSLstd450UMin;
5132 else
5133 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005134 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005135 break;
5136 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005137 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005138 break;
5139 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005140 if (isFloat)
5141 libCall = spv::GLSLstd450FMax;
5142 else if (isUnsigned)
5143 libCall = spv::GLSLstd450UMax;
5144 else
5145 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005146 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005147 break;
5148 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005149 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005150 break;
5151 case glslang::EOpDot:
5152 opCode = spv::OpDot;
5153 break;
5154 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005155 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005156 break;
5157
5158 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005159 if (isFloat)
5160 libCall = spv::GLSLstd450FClamp;
5161 else if (isUnsigned)
5162 libCall = spv::GLSLstd450UClamp;
5163 else
5164 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005165 builder.promoteScalar(precision, operands.front(), operands[1]);
5166 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005167 break;
5168 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005169 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5170 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005171 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005172 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005173 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005174 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005175 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005176 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005177 break;
5178 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005179 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005180 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005181 break;
5182 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005183 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005184 builder.promoteScalar(precision, operands[0], operands[2]);
5185 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005186 break;
5187
5188 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005189 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005190 break;
5191 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005192 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005193 break;
5194 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005195 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005196 break;
5197 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005198 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005199 break;
5200 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005201 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005202 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005203 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005204 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005205 libCall = spv::GLSLstd450InterpolateAtSample;
5206 break;
5207 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005208 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005209 libCall = spv::GLSLstd450InterpolateAtOffset;
5210 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005211 case glslang::EOpAddCarry:
5212 opCode = spv::OpIAddCarry;
5213 typeId = builder.makeStructResultType(typeId0, typeId0);
5214 consumedOperands = 2;
5215 break;
5216 case glslang::EOpSubBorrow:
5217 opCode = spv::OpISubBorrow;
5218 typeId = builder.makeStructResultType(typeId0, typeId0);
5219 consumedOperands = 2;
5220 break;
5221 case glslang::EOpUMulExtended:
5222 opCode = spv::OpUMulExtended;
5223 typeId = builder.makeStructResultType(typeId0, typeId0);
5224 consumedOperands = 2;
5225 break;
5226 case glslang::EOpIMulExtended:
5227 opCode = spv::OpSMulExtended;
5228 typeId = builder.makeStructResultType(typeId0, typeId0);
5229 consumedOperands = 2;
5230 break;
5231 case glslang::EOpBitfieldExtract:
5232 if (isUnsigned)
5233 opCode = spv::OpBitFieldUExtract;
5234 else
5235 opCode = spv::OpBitFieldSExtract;
5236 break;
5237 case glslang::EOpBitfieldInsert:
5238 opCode = spv::OpBitFieldInsert;
5239 break;
5240
5241 case glslang::EOpFma:
5242 libCall = spv::GLSLstd450Fma;
5243 break;
5244 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005245 {
5246 libCall = spv::GLSLstd450FrexpStruct;
5247 assert(builder.isPointerType(typeId1));
5248 typeId1 = builder.getContainedTypeId(typeId1);
5249#ifdef AMD_EXTENSIONS
5250 int width = builder.getScalarTypeWidth(typeId1);
5251#else
5252 int width = 32;
5253#endif
5254 if (builder.getNumComponents(operands[0]) == 1)
5255 frexpIntType = builder.makeIntegerType(width, true);
5256 else
5257 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5258 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5259 consumedOperands = 1;
5260 }
John Kessenich55e7d112015-11-15 21:33:39 -07005261 break;
5262 case glslang::EOpLdexp:
5263 libCall = spv::GLSLstd450Ldexp;
5264 break;
5265
Rex Xu574ab042016-04-14 16:53:07 +08005266 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005267 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005268
Rex Xu9d93a232016-05-05 12:30:44 +08005269#ifdef AMD_EXTENSIONS
5270 case glslang::EOpSwizzleInvocations:
5271 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5272 libCall = spv::SwizzleInvocationsAMD;
5273 break;
5274 case glslang::EOpSwizzleInvocationsMasked:
5275 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5276 libCall = spv::SwizzleInvocationsMaskedAMD;
5277 break;
5278 case glslang::EOpWriteInvocation:
5279 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5280 libCall = spv::WriteInvocationAMD;
5281 break;
5282
5283 case glslang::EOpMin3:
5284 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5285 if (isFloat)
5286 libCall = spv::FMin3AMD;
5287 else {
5288 if (isUnsigned)
5289 libCall = spv::UMin3AMD;
5290 else
5291 libCall = spv::SMin3AMD;
5292 }
5293 break;
5294 case glslang::EOpMax3:
5295 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5296 if (isFloat)
5297 libCall = spv::FMax3AMD;
5298 else {
5299 if (isUnsigned)
5300 libCall = spv::UMax3AMD;
5301 else
5302 libCall = spv::SMax3AMD;
5303 }
5304 break;
5305 case glslang::EOpMid3:
5306 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5307 if (isFloat)
5308 libCall = spv::FMid3AMD;
5309 else {
5310 if (isUnsigned)
5311 libCall = spv::UMid3AMD;
5312 else
5313 libCall = spv::SMid3AMD;
5314 }
5315 break;
5316
5317 case glslang::EOpInterpolateAtVertex:
5318 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5319 libCall = spv::InterpolateAtVertexAMD;
5320 break;
5321#endif
5322
John Kessenich140f3df2015-06-26 16:58:36 -06005323 default:
5324 return 0;
5325 }
5326
5327 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005328 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005329 // Use an extended instruction from the standard library.
5330 // Construct the call arguments, without modifying the original operands vector.
5331 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5332 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005333 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005334 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005335 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005336 case 0:
5337 // should all be handled by visitAggregate and createNoArgOperation
5338 assert(0);
5339 return 0;
5340 case 1:
5341 // should all be handled by createUnaryOperation
5342 assert(0);
5343 return 0;
5344 case 2:
5345 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5346 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005347 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005348 // anything 3 or over doesn't have l-value operands, so all should be consumed
5349 assert(consumedOperands == operands.size());
5350 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005351 break;
5352 }
5353 }
5354
John Kessenich55e7d112015-11-15 21:33:39 -07005355 // Decode the return types that were structures
5356 switch (op) {
5357 case glslang::EOpAddCarry:
5358 case glslang::EOpSubBorrow:
5359 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5360 id = builder.createCompositeExtract(id, typeId0, 0);
5361 break;
5362 case glslang::EOpUMulExtended:
5363 case glslang::EOpIMulExtended:
5364 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5365 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5366 break;
5367 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005368 {
5369 assert(operands.size() == 2);
5370 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5371 // "exp" is floating-point type (from HLSL intrinsic)
5372 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5373 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5374 builder.createStore(member1, operands[1]);
5375 } else
5376 // "exp" is integer type (from GLSL built-in function)
5377 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5378 id = builder.createCompositeExtract(id, typeId0, 0);
5379 }
John Kessenich55e7d112015-11-15 21:33:39 -07005380 break;
5381 default:
5382 break;
5383 }
5384
John Kessenich32cfd492016-02-02 12:37:46 -07005385 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005386}
5387
Rex Xu9d93a232016-05-05 12:30:44 +08005388// Intrinsics with no arguments (or no return value, and no precision).
5389spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005390{
5391 // TODO: get the barrier operands correct
5392
5393 switch (op) {
5394 case glslang::EOpEmitVertex:
5395 builder.createNoResultOp(spv::OpEmitVertex);
5396 return 0;
5397 case glslang::EOpEndPrimitive:
5398 builder.createNoResultOp(spv::OpEndPrimitive);
5399 return 0;
5400 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005401 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005402 return 0;
5403 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005404 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005405 return 0;
5406 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005407 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005408 return 0;
5409 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005410 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005411 return 0;
5412 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005413 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005414 return 0;
5415 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005416 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005417 return 0;
5418 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005419 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005420 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005421 case glslang::EOpAllMemoryBarrierWithGroupSync:
5422 // Control barrier with non-"None" semantic is also a memory barrier.
5423 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5424 return 0;
5425 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5426 // Control barrier with non-"None" semantic is also a memory barrier.
5427 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5428 return 0;
5429 case glslang::EOpWorkgroupMemoryBarrier:
5430 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5431 return 0;
5432 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5433 // Control barrier with non-"None" semantic is also a memory barrier.
5434 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5435 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005436#ifdef AMD_EXTENSIONS
5437 case glslang::EOpTime:
5438 {
5439 std::vector<spv::Id> args; // Dummy arguments
5440 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5441 return builder.setPrecision(id, precision);
5442 }
5443#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005444 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005445 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005446 return 0;
5447 }
5448}
5449
5450spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5451{
John Kessenich2f273362015-07-18 22:34:27 -06005452 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005453 spv::Id id;
5454 if (symbolValues.end() != iter) {
5455 id = iter->second;
5456 return id;
5457 }
5458
5459 // it was not found, create it
5460 id = createSpvVariable(symbol);
5461 symbolValues[symbol->getId()] = id;
5462
Rex Xuc884b4a2016-06-29 15:03:44 +08005463 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005464 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005465 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005466 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005467 if (symbol->getType().getQualifier().hasSpecConstantId())
5468 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005469 if (symbol->getQualifier().hasIndex())
5470 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5471 if (symbol->getQualifier().hasComponent())
5472 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5473 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005474 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005475 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005476 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005477 if (symbol->getQualifier().hasXfbBuffer())
5478 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5479 if (symbol->getQualifier().hasXfbOffset())
5480 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5481 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005482 // atomic counters use this:
5483 if (symbol->getQualifier().hasOffset())
5484 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005485 }
5486
scygan2c864272016-05-18 18:09:17 +02005487 if (symbol->getQualifier().hasLocation())
5488 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005489 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005490 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005491 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005492 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005493 }
John Kessenich140f3df2015-06-26 16:58:36 -06005494 if (symbol->getQualifier().hasSet())
5495 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005496 else if (IsDescriptorResource(symbol->getType())) {
5497 // default to 0
5498 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5499 }
John Kessenich140f3df2015-06-26 16:58:36 -06005500 if (symbol->getQualifier().hasBinding())
5501 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005502 if (symbol->getQualifier().hasAttachment())
5503 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005504 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005505 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005506 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005507 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005508 if (symbol->getQualifier().hasXfbBuffer())
5509 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5510 }
5511
Rex Xu1da878f2016-02-21 20:59:01 +08005512 if (symbol->getType().isImage()) {
5513 std::vector<spv::Decoration> memory;
5514 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5515 for (unsigned int i = 0; i < memory.size(); ++i)
5516 addDecoration(id, memory[i]);
5517 }
5518
John Kessenich140f3df2015-06-26 16:58:36 -06005519 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005520 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005521 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005522 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005523
John Kessenichecba76f2017-01-06 00:34:48 -07005524#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005525 if (builtIn == spv::BuiltInSampleMask) {
5526 spv::Decoration decoration;
5527 // GL_NV_sample_mask_override_coverage extension
5528 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005529 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005530 else
5531 decoration = (spv::Decoration)spv::DecorationMax;
5532 addDecoration(id, decoration);
5533 if (decoration != spv::DecorationMax) {
5534 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5535 }
5536 }
chaoc771d89f2017-01-13 01:10:53 -08005537 else if (builtIn == spv::BuiltInLayer) {
5538 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06005539 if (symbol->getQualifier().layoutViewportRelative) {
chaoc771d89f2017-01-13 01:10:53 -08005540 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5541 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5542 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5543 }
John Kessenichb41bff62017-08-11 13:07:17 -06005544 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
chaoc771d89f2017-01-13 01:10:53 -08005545 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5546 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5547 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5548 }
5549 }
5550
chaoc6e5acae2016-12-20 13:28:52 -08005551 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005552 addDecoration(id, spv::DecorationPassthroughNV);
5553 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005554 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5555 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005556#endif
5557
John Kessenich140f3df2015-06-26 16:58:36 -06005558 return id;
5559}
5560
John Kessenich55e7d112015-11-15 21:33:39 -07005561// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005562void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5563{
John Kessenich4016e382016-07-15 11:53:56 -06005564 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005565 builder.addDecoration(id, dec);
5566}
5567
John Kessenich55e7d112015-11-15 21:33:39 -07005568// If 'dec' is valid, add a one-operand decoration to an object
5569void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5570{
John Kessenich4016e382016-07-15 11:53:56 -06005571 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005572 builder.addDecoration(id, dec, value);
5573}
5574
5575// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005576void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5577{
John Kessenich4016e382016-07-15 11:53:56 -06005578 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005579 builder.addMemberDecoration(id, (unsigned)member, dec);
5580}
5581
John Kessenich92187592016-02-01 13:45:25 -07005582// If 'dec' is valid, add a one-operand decoration to a struct member
5583void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5584{
John Kessenich4016e382016-07-15 11:53:56 -06005585 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005586 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5587}
5588
John Kessenich55e7d112015-11-15 21:33:39 -07005589// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005590// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005591//
5592// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5593//
5594// Recursively walk the nodes. The nodes form a tree whose leaves are
5595// regular constants, which themselves are trees that createSpvConstant()
5596// recursively walks. So, this function walks the "top" of the tree:
5597// - emit specialization constant-building instructions for specConstant
5598// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005599spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005600{
John Kessenich7cc0e282016-03-20 00:46:02 -06005601 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005602
qining4f4bb812016-04-03 23:55:17 -04005603 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005604 if (! node.getQualifier().specConstant) {
5605 // hand off to the non-spec-constant path
5606 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5607 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005608 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005609 nextConst, false);
5610 }
5611
5612 // We now know we have a specialization constant to build
5613
John Kessenichd94c0032016-05-30 19:29:40 -06005614 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005615 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5616 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5617 std::vector<spv::Id> dimConstId;
5618 for (int dim = 0; dim < 3; ++dim) {
5619 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5620 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5621 if (specConst)
5622 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5623 }
5624 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5625 }
5626
5627 // An AST node labelled as specialization constant should be a symbol node.
5628 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5629 if (auto* sn = node.getAsSymbolNode()) {
5630 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005631 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5632 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5633 // will set the builder into spec constant op instruction generating mode.
5634 sub_tree->traverse(this);
5635 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005636 } else if (auto* const_union_array = &sn->getConstArray()){
5637 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005638 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5639 builder.addName(id, sn->getName().c_str());
5640 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005641 }
5642 }
qining4f4bb812016-04-03 23:55:17 -04005643
5644 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5645 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005646 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005647 exit(1);
5648 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005649}
5650
John Kessenich140f3df2015-06-26 16:58:36 -06005651// Use 'consts' as the flattened glslang source of scalar constants to recursively
5652// build the aggregate SPIR-V constant.
5653//
5654// If there are not enough elements present in 'consts', 0 will be substituted;
5655// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5656//
qining08408382016-03-21 09:51:37 -04005657spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005658{
5659 // vector of constants for SPIR-V
5660 std::vector<spv::Id> spvConsts;
5661
5662 // Type is used for struct and array constants
5663 spv::Id typeId = convertGlslangToSpvType(glslangType);
5664
5665 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005666 glslang::TType elementType(glslangType, 0);
5667 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005668 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005669 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005670 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005671 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005672 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005673 } else if (glslangType.getStruct()) {
5674 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5675 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005676 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005677 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005678 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5679 bool zero = nextConst >= consts.size();
5680 switch (glslangType.getBasicType()) {
5681 case glslang::EbtInt:
5682 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5683 break;
5684 case glslang::EbtUint:
5685 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5686 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005687 case glslang::EbtInt64:
5688 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5689 break;
5690 case glslang::EbtUint64:
5691 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5692 break;
Rex Xucabbb782017-03-24 13:41:14 +08005693#ifdef AMD_EXTENSIONS
5694 case glslang::EbtInt16:
5695 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5696 break;
5697 case glslang::EbtUint16:
5698 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5699 break;
5700#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005701 case glslang::EbtFloat:
5702 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5703 break;
5704 case glslang::EbtDouble:
5705 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5706 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005707#ifdef AMD_EXTENSIONS
5708 case glslang::EbtFloat16:
5709 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5710 break;
5711#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005712 case glslang::EbtBool:
5713 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5714 break;
5715 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005716 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005717 break;
5718 }
5719 ++nextConst;
5720 }
5721 } else {
5722 // we have a non-aggregate (scalar) constant
5723 bool zero = nextConst >= consts.size();
5724 spv::Id scalar = 0;
5725 switch (glslangType.getBasicType()) {
5726 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005727 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005728 break;
5729 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005730 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005731 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005732 case glslang::EbtInt64:
5733 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5734 break;
5735 case glslang::EbtUint64:
5736 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5737 break;
Rex Xucabbb782017-03-24 13:41:14 +08005738#ifdef AMD_EXTENSIONS
5739 case glslang::EbtInt16:
5740 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5741 break;
5742 case glslang::EbtUint16:
5743 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5744 break;
5745#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005746 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005747 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005748 break;
5749 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005750 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005751 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005752#ifdef AMD_EXTENSIONS
5753 case glslang::EbtFloat16:
5754 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5755 break;
5756#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005757 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005758 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005759 break;
5760 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005761 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005762 break;
5763 }
5764 ++nextConst;
5765 return scalar;
5766 }
5767
5768 return builder.makeCompositeConstant(typeId, spvConsts);
5769}
5770
John Kessenich7c1aa102015-10-15 13:29:11 -06005771// Return true if the node is a constant or symbol whose reading has no
5772// non-trivial observable cost or effect.
5773bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5774{
5775 // don't know what this is
5776 if (node == nullptr)
5777 return false;
5778
5779 // a constant is safe
5780 if (node->getAsConstantUnion() != nullptr)
5781 return true;
5782
5783 // not a symbol means non-trivial
5784 if (node->getAsSymbolNode() == nullptr)
5785 return false;
5786
5787 // a symbol, depends on what's being read
5788 switch (node->getType().getQualifier().storage) {
5789 case glslang::EvqTemporary:
5790 case glslang::EvqGlobal:
5791 case glslang::EvqIn:
5792 case glslang::EvqInOut:
5793 case glslang::EvqConst:
5794 case glslang::EvqConstReadOnly:
5795 case glslang::EvqUniform:
5796 return true;
5797 default:
5798 return false;
5799 }
qining25262b32016-05-06 17:25:16 -04005800}
John Kessenich7c1aa102015-10-15 13:29:11 -06005801
5802// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005803// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005804// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005805// Return true if trivial.
5806bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5807{
5808 if (node == nullptr)
5809 return false;
5810
John Kessenich84cc15f2017-05-24 16:44:47 -06005811 // count non scalars as trivial, as well as anything coming from HLSL
5812 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005813 return true;
5814
John Kessenich7c1aa102015-10-15 13:29:11 -06005815 // symbols and constants are trivial
5816 if (isTrivialLeaf(node))
5817 return true;
5818
5819 // otherwise, it needs to be a simple operation or one or two leaf nodes
5820
5821 // not a simple operation
5822 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5823 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5824 if (binaryNode == nullptr && unaryNode == nullptr)
5825 return false;
5826
5827 // not on leaf nodes
5828 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5829 return false;
5830
5831 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5832 return false;
5833 }
5834
5835 switch (node->getAsOperator()->getOp()) {
5836 case glslang::EOpLogicalNot:
5837 case glslang::EOpConvIntToBool:
5838 case glslang::EOpConvUintToBool:
5839 case glslang::EOpConvFloatToBool:
5840 case glslang::EOpConvDoubleToBool:
5841 case glslang::EOpEqual:
5842 case glslang::EOpNotEqual:
5843 case glslang::EOpLessThan:
5844 case glslang::EOpGreaterThan:
5845 case glslang::EOpLessThanEqual:
5846 case glslang::EOpGreaterThanEqual:
5847 case glslang::EOpIndexDirect:
5848 case glslang::EOpIndexDirectStruct:
5849 case glslang::EOpLogicalXor:
5850 case glslang::EOpAny:
5851 case glslang::EOpAll:
5852 return true;
5853 default:
5854 return false;
5855 }
5856}
5857
5858// Emit short-circuiting code, where 'right' is never evaluated unless
5859// the left side is true (for &&) or false (for ||).
5860spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5861{
5862 spv::Id boolTypeId = builder.makeBoolType();
5863
5864 // emit left operand
5865 builder.clearAccessChain();
5866 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005867 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005868
5869 // Operands to accumulate OpPhi operands
5870 std::vector<spv::Id> phiOperands;
5871 // accumulate left operand's phi information
5872 phiOperands.push_back(leftId);
5873 phiOperands.push_back(builder.getBuildPoint()->getId());
5874
5875 // Make the two kinds of operation symmetric with a "!"
5876 // || => emit "if (! left) result = right"
5877 // && => emit "if ( left) result = right"
5878 //
5879 // TODO: this runtime "not" for || could be avoided by adding functionality
5880 // to 'builder' to have an "else" without an "then"
5881 if (op == glslang::EOpLogicalOr)
5882 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5883
5884 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005885 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005886
5887 // emit right operand as the "then" part of the "if"
5888 builder.clearAccessChain();
5889 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005890 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005891
5892 // accumulate left operand's phi information
5893 phiOperands.push_back(rightId);
5894 phiOperands.push_back(builder.getBuildPoint()->getId());
5895
5896 // finish the "if"
5897 ifBuilder.makeEndIf();
5898
5899 // phi together the two results
5900 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5901}
5902
Rex Xu9d93a232016-05-05 12:30:44 +08005903// Return type Id of the imported set of extended instructions corresponds to the name.
5904// Import this set if it has not been imported yet.
5905spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5906{
5907 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5908 return extBuiltinMap[name];
5909 else {
Rex Xu51596642016-09-21 18:56:12 +08005910 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005911 spv::Id extBuiltins = builder.import(name);
5912 extBuiltinMap[name] = extBuiltins;
5913 return extBuiltins;
5914 }
5915}
5916
John Kessenich140f3df2015-06-26 16:58:36 -06005917}; // end anonymous namespace
5918
5919namespace glslang {
5920
John Kessenich68d78fd2015-07-12 19:28:10 -06005921void GetSpirvVersion(std::string& version)
5922{
John Kessenich9e55f632015-07-15 10:03:39 -06005923 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005924 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005925 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005926 version = buf;
5927}
5928
John Kessenich140f3df2015-06-26 16:58:36 -06005929// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005930void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005931{
5932 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005933 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005934 if (out.fail())
5935 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005936 for (int i = 0; i < (int)spirv.size(); ++i) {
5937 unsigned int word = spirv[i];
5938 out.write((const char*)&word, 4);
5939 }
5940 out.close();
5941}
5942
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005943// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005944void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005945{
5946 std::ofstream out;
5947 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005948 if (out.fail())
5949 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005950 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005951 if (varName != nullptr) {
5952 out << "\t #pragma once" << std::endl;
5953 out << "const uint32_t " << varName << "[] = {" << std::endl;
5954 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005955 const int WORDS_PER_LINE = 8;
5956 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5957 out << "\t";
5958 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5959 const unsigned int word = spirv[i + j];
5960 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5961 if (i + j + 1 < (int)spirv.size()) {
5962 out << ",";
5963 }
5964 }
5965 out << std::endl;
5966 }
Flavio15017db2017-02-15 14:29:33 -08005967 if (varName != nullptr) {
5968 out << "};";
5969 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005970 out.close();
5971}
5972
GregFcd1f1692017-09-21 18:40:22 -06005973#ifdef ENABLE_OPT
5974void errHandler(const std::string& str) {
5975 std::cerr << str << std::endl;
5976}
5977#endif
5978
John Kessenich140f3df2015-06-26 16:58:36 -06005979//
5980// Set up the glslang traversal
5981//
John Kessenich121853f2017-05-31 17:11:16 -06005982void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06005983{
Lei Zhang17535f72016-05-04 15:55:59 -04005984 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06005985 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04005986}
5987
John Kessenich121853f2017-05-31 17:11:16 -06005988void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
5989 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04005990{
John Kessenich140f3df2015-06-26 16:58:36 -06005991 TIntermNode* root = intermediate.getTreeRoot();
5992
5993 if (root == 0)
5994 return;
5995
John Kessenich121853f2017-05-31 17:11:16 -06005996 glslang::SpvOptions defaultOptions;
5997 if (options == nullptr)
5998 options = &defaultOptions;
5999
John Kessenich140f3df2015-06-26 16:58:36 -06006000 glslang::GetThreadPoolAllocator().push();
6001
John Kessenich121853f2017-05-31 17:11:16 -06006002 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006003 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006004 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006005 it.dumpSpv(spirv);
6006
GregFcd1f1692017-09-21 18:40:22 -06006007#ifdef ENABLE_OPT
6008 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6009 // eg. forward and remove memory writes of opaque types.
6010 if ((intermediate.getSource() == EShSourceHlsl ||
6011 options->optimizeSize) &&
6012 !options->disableOptimizer) {
6013 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6014
6015 spvtools::Optimizer optimizer(target_env);
6016 optimizer.SetMessageConsumer([](spv_message_level_t level,
6017 const char* source,
6018 const spv_position_t& position,
6019 const char* message) {
6020 std::cerr << StringifyMessage(level, source, position, message)
6021 << std::endl;
6022 });
6023
6024 optimizer.RegisterPass(CreateInlineExhaustivePass());
6025 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
6026 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
6027 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
6028 optimizer.RegisterPass(CreateInsertExtractElimPass());
6029 optimizer.RegisterPass(CreateAggressiveDCEPass());
6030 optimizer.RegisterPass(CreateDeadBranchElimPass());
6031 optimizer.RegisterPass(CreateBlockMergePass());
6032 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
6033 optimizer.RegisterPass(CreateInsertExtractElimPass());
6034 optimizer.RegisterPass(CreateAggressiveDCEPass());
6035 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
6036 // if (options->optimizeSize)
6037 // optimizer.RegisterPass(CreateCommonUniformElimPass());
6038
6039 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
6040 return;
6041
6042 // Remove dead module-level objects: functions, types, vars
6043 // TODO(greg-lunarg): Switch to spirv-opt versions when available
6044 spv::spirvbin_t Remapper(0);
6045 Remapper.registerErrorHandler(errHandler);
6046 Remapper.remap(spirv, spv::spirvbin_t::DCE_ALL);
6047 }
6048#endif
6049
John Kessenich140f3df2015-06-26 16:58:36 -06006050 glslang::GetThreadPoolAllocator().pop();
6051}
6052
6053}; // end namespace glslang