blob: 745021f2650858aef6c17adb9486973f9f743377 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
John Kessenich927608b2017-01-06 12:34:14 -070023// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060035
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Piers Daniell1c5443c2017-12-13 13:07:22 -070047 #include "GLSL.ext.EXT.h"
Rex Xu9d93a232016-05-05 12:30:44 +080048#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080049 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080050#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080051#ifdef NV_EXTENSIONS
52 #include "GLSL.ext.NV.h"
53#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060054}
John Kessenich140f3df2015-06-26 16:58:36 -060055
GregFcd1f1692017-09-21 18:40:22 -060056#ifdef ENABLE_OPT
57 #include "spirv-tools/optimizer.hpp"
58 #include "message.h"
59 #include "SPVRemapper.h"
60#endif
61
62#ifdef ENABLE_OPT
63using namespace spvtools;
64#endif
65
John Kessenich140f3df2015-06-26 16:58:36 -060066// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020067#include "../glslang/MachineIndependent/localintermediate.h"
68#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060069#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050070#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060071
John Kessenich140f3df2015-06-26 16:58:36 -060072#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050073#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040074#include <list>
75#include <map>
76#include <stack>
77#include <string>
78#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060079
80namespace {
81
qining4c912612016-04-01 10:35:16 -040082namespace {
83class SpecConstantOpModeGuard {
84public:
85 SpecConstantOpModeGuard(spv::Builder* builder)
86 : builder_(builder) {
87 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040088 }
89 ~SpecConstantOpModeGuard() {
90 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
91 : builder_->setToNormalCodeGenMode();
92 }
qining40887662016-04-03 22:20:42 -040093 void turnOnSpecConstantOpMode() {
94 builder_->setToSpecConstCodeGenMode();
95 }
qining4c912612016-04-01 10:35:16 -040096
97private:
98 spv::Builder* builder_;
99 bool previous_flag_;
100};
101}
102
John Kessenich140f3df2015-06-26 16:58:36 -0600103//
104// The main holder of information for translating glslang to SPIR-V.
105//
106// Derives from the AST walking base class.
107//
108class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
109public:
John Kessenich121853f2017-05-31 17:11:16 -0600110 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger, glslang::SpvOptions& options);
John Kessenichfca82622016-11-26 13:23:20 -0700111 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600112
113 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
114 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
115 void visitConstantUnion(glslang::TIntermConstantUnion*);
116 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
117 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
118 void visitSymbol(glslang::TIntermSymbol* symbol);
119 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
120 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
121 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
122
John Kessenichfca82622016-11-26 13:23:20 -0700123 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700124 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600125
126protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800127 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800128 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100129 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700130 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
Rex Xu57e65922017-07-04 23:23:40 +0800131 spv::SelectionControlMask TranslateSelectionControl(glslang::TSelectionControl) const;
steve-lunargf1709e72017-05-02 20:14:50 -0600132 spv::LoopControlMask TranslateLoopControl(glslang::TLoopControl) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600133 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600134 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
135 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600136 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
137 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
138 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600139 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700140 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600141 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600142 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
143 glslang::TLayoutPacking, const glslang::TQualifier&);
144 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
145 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700146 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700147 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800148 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600149 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700150 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700151 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
152 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
153 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100154 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600155
John Kessenich6fccb3c2016-09-19 16:01:41 -0600156 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenichd41993d2017-09-10 15:21:05 -0600157 bool writableParam(glslang::TStorageQualifier);
158 bool originalParam(glslang::TStorageQualifier, const glslang::TType&, bool implicitThisParam);
John Kessenich140f3df2015-06-26 16:58:36 -0600159 void makeFunctions(const glslang::TIntermSequence&);
160 void makeGlobalInitializers(const glslang::TIntermSequence&);
161 void visitFunctions(const glslang::TIntermSequence&);
162 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800163 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600164 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
165 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600166 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
167
qining25262b32016-05-06 17:25:16 -0400168 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
169 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
170 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800171 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800172 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600173 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800174 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800175 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800176 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600177 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800178 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600179 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
180 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700181 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600182 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700183 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400184 spv::Id createSpvConstant(const glslang::TIntermTyped&);
185 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600186 bool isTrivialLeaf(const glslang::TIntermTyped* node);
187 bool isTrivial(const glslang::TIntermTyped* node);
188 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800189 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600190
John Kessenich121853f2017-05-31 17:11:16 -0600191 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600192 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600193 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700194 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600195 int sequenceDepth;
196
Lei Zhang17535f72016-05-04 15:55:59 -0400197 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400198
John Kessenich140f3df2015-06-26 16:58:36 -0600199 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
200 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700201 bool inEntryPoint;
202 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700203 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700204 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600205 const glslang::TIntermediate* glslangIntermediate;
206 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800207 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600208
John Kessenich2f273362015-07-18 22:34:27 -0600209 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600210 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600211 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700212 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600213 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600214 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600215};
216
217//
218// Helper functions for translating glslang representations to SPIR-V enumerants.
219//
220
221// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700222spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600223{
John Kessenich66e2faf2016-03-12 18:34:36 -0700224 switch (source) {
225 case glslang::EShSourceGlsl:
226 switch (profile) {
227 case ENoProfile:
228 case ECoreProfile:
229 case ECompatibilityProfile:
230 return spv::SourceLanguageGLSL;
231 case EEsProfile:
232 return spv::SourceLanguageESSL;
233 default:
234 return spv::SourceLanguageUnknown;
235 }
236 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600237 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600238 default:
239 return spv::SourceLanguageUnknown;
240 }
241}
242
243// Translate glslang language (stage) to SPIR-V execution model.
244spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
245{
246 switch (stage) {
247 case EShLangVertex: return spv::ExecutionModelVertex;
248 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
249 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
250 case EShLangGeometry: return spv::ExecutionModelGeometry;
251 case EShLangFragment: return spv::ExecutionModelFragment;
252 case EShLangCompute: return spv::ExecutionModelGLCompute;
253 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700254 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600255 return spv::ExecutionModelFragment;
256 }
257}
258
John Kessenich140f3df2015-06-26 16:58:36 -0600259// Translate glslang sampler type to SPIR-V dimensionality.
260spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
261{
262 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700263 case glslang::Esd1D: return spv::Dim1D;
264 case glslang::Esd2D: return spv::Dim2D;
265 case glslang::Esd3D: return spv::Dim3D;
266 case glslang::EsdCube: return spv::DimCube;
267 case glslang::EsdRect: return spv::DimRect;
268 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700269 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600270 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700271 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600272 return spv::Dim2D;
273 }
274}
275
John Kessenichf6640762016-08-01 19:44:00 -0600276// Translate glslang precision to SPIR-V precision decorations.
277spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600278{
John Kessenichf6640762016-08-01 19:44:00 -0600279 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700280 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600281 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600282 default:
283 return spv::NoPrecision;
284 }
285}
286
John Kessenichf6640762016-08-01 19:44:00 -0600287// Translate glslang type to SPIR-V precision decorations.
288spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
289{
290 return TranslatePrecisionDecoration(type.getQualifier().precision);
291}
292
John Kessenich140f3df2015-06-26 16:58:36 -0600293// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600294spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600295{
296 if (type.getBasicType() == glslang::EbtBlock) {
297 switch (type.getQualifier().storage) {
298 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600299 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600300 case glslang::EvqVaryingIn: return spv::DecorationBlock;
301 case glslang::EvqVaryingOut: return spv::DecorationBlock;
302 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700303 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600304 break;
305 }
306 }
307
John Kessenich4016e382016-07-15 11:53:56 -0600308 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600309}
310
Rex Xu1da878f2016-02-21 20:59:01 +0800311// Translate glslang type to SPIR-V memory decorations.
312void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
313{
314 if (qualifier.coherent)
315 memory.push_back(spv::DecorationCoherent);
316 if (qualifier.volatil)
317 memory.push_back(spv::DecorationVolatile);
318 if (qualifier.restrict)
319 memory.push_back(spv::DecorationRestrict);
320 if (qualifier.readonly)
321 memory.push_back(spv::DecorationNonWritable);
322 if (qualifier.writeonly)
323 memory.push_back(spv::DecorationNonReadable);
324}
325
John Kessenich140f3df2015-06-26 16:58:36 -0600326// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700327spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600328{
329 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700330 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600331 case glslang::ElmRowMajor:
332 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700333 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600334 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700335 default:
336 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600337 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600338 }
339 } else {
340 switch (type.getBasicType()) {
341 default:
John Kessenich4016e382016-07-15 11:53:56 -0600342 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600343 break;
344 case glslang::EbtBlock:
345 switch (type.getQualifier().storage) {
346 case glslang::EvqUniform:
347 case glslang::EvqBuffer:
348 switch (type.getQualifier().layoutPacking) {
349 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600350 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
351 default:
John Kessenich4016e382016-07-15 11:53:56 -0600352 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600353 }
354 case glslang::EvqVaryingIn:
355 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700356 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600357 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600358 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700359 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600360 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600361 }
362 }
363 }
364}
365
366// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600367// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700368// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800369spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600370{
Rex Xubbceed72016-05-21 09:40:44 +0800371 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700372 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600373 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800374 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700375 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700376 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600377 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800378#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800379 else if (qualifier.explicitInterp) {
380 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800381 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800382 }
Rex Xu9d93a232016-05-05 12:30:44 +0800383#endif
Rex Xubbceed72016-05-21 09:40:44 +0800384 else
John Kessenich4016e382016-07-15 11:53:56 -0600385 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800386}
387
388// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600389// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800390// should be applied.
391spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
392{
393 if (qualifier.patch)
394 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700395 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600396 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700397 else if (qualifier.sample) {
398 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600399 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700400 } else
John Kessenich4016e382016-07-15 11:53:56 -0600401 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600402}
403
John Kessenich92187592016-02-01 13:45:25 -0700404// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700405spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600406{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700407 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600408 return spv::DecorationInvariant;
409 else
John Kessenich4016e382016-07-15 11:53:56 -0600410 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600411}
412
qining9220dbb2016-05-04 17:34:38 -0400413// If glslang type is noContraction, return SPIR-V NoContraction decoration.
414spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
415{
416 if (qualifier.noContraction)
417 return spv::DecorationNoContraction;
418 else
John Kessenich4016e382016-07-15 11:53:56 -0600419 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400420}
421
David Netoa901ffe2016-06-08 14:11:40 +0100422// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
423// associated capabilities when required. For some built-in variables, a capability
424// is generated only when using the variable in an executable instruction, but not when
425// just declaring a struct member variable with it. This is true for PointSize,
426// ClipDistance, and CullDistance.
427spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600428{
429 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700430 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600431 // Defer adding the capability until the built-in is actually used.
432 if (! memberDeclaration) {
433 switch (glslangIntermediate->getStage()) {
434 case EShLangGeometry:
435 builder.addCapability(spv::CapabilityGeometryPointSize);
436 break;
437 case EShLangTessControl:
438 case EShLangTessEvaluation:
439 builder.addCapability(spv::CapabilityTessellationPointSize);
440 break;
441 default:
442 break;
443 }
John Kessenich92187592016-02-01 13:45:25 -0700444 }
445 return spv::BuiltInPointSize;
446
John Kessenichebb50532016-05-16 19:22:05 -0600447 // These *Distance capabilities logically belong here, but if the member is declared and
448 // then never used, consumers of SPIR-V prefer the capability not be declared.
449 // They are now generated when used, rather than here when declared.
450 // Potentially, the specification should be more clear what the minimum
451 // use needed is to trigger the capability.
452 //
John Kessenich92187592016-02-01 13:45:25 -0700453 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100454 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800455 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700456 return spv::BuiltInClipDistance;
457
458 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100459 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800460 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700461 return spv::BuiltInCullDistance;
462
463 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600464 builder.addCapability(spv::CapabilityMultiViewport);
465 if (glslangIntermediate->getStage() == EShLangVertex ||
466 glslangIntermediate->getStage() == EShLangTessControl ||
467 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800468
John Kessenichba6a3c22017-09-13 13:22:50 -0600469 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
470 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800471 }
John Kessenich92187592016-02-01 13:45:25 -0700472 return spv::BuiltInViewportIndex;
473
John Kessenich5e801132016-02-15 11:09:46 -0700474 case glslang::EbvSampleId:
475 builder.addCapability(spv::CapabilitySampleRateShading);
476 return spv::BuiltInSampleId;
477
478 case glslang::EbvSamplePosition:
479 builder.addCapability(spv::CapabilitySampleRateShading);
480 return spv::BuiltInSamplePosition;
481
482 case glslang::EbvSampleMask:
John Kessenich5e801132016-02-15 11:09:46 -0700483 return spv::BuiltInSampleMask;
484
John Kessenich78a45572016-07-08 14:05:15 -0600485 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600486 builder.addCapability(spv::CapabilityGeometry);
487 if (glslangIntermediate->getStage() == EShLangVertex ||
488 glslangIntermediate->getStage() == EShLangTessControl ||
489 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800490
John Kessenichba6a3c22017-09-13 13:22:50 -0600491 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
492 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800493 }
John Kessenich78a45572016-07-08 14:05:15 -0600494 return spv::BuiltInLayer;
495
John Kessenich140f3df2015-06-26 16:58:36 -0600496 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600497 case glslang::EbvVertexId: return spv::BuiltInVertexId;
498 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700499 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
500 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800501
John Kessenichda581a22015-10-14 14:10:30 -0600502 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800503 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
504 builder.addCapability(spv::CapabilityDrawParameters);
505 return spv::BuiltInBaseVertex;
506
John Kessenichda581a22015-10-14 14:10:30 -0600507 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800508 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
509 builder.addCapability(spv::CapabilityDrawParameters);
510 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200511
John Kessenichda581a22015-10-14 14:10:30 -0600512 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800513 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
514 builder.addCapability(spv::CapabilityDrawParameters);
515 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200516
517 case glslang::EbvPrimitiveId:
518 if (glslangIntermediate->getStage() == EShLangFragment)
519 builder.addCapability(spv::CapabilityGeometry);
520 return spv::BuiltInPrimitiveId;
521
Rex Xu37cdcee2017-06-29 17:46:34 +0800522 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800523 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
524 builder.addCapability(spv::CapabilityStencilExportEXT);
525 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800526
John Kessenich140f3df2015-06-26 16:58:36 -0600527 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600528 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
529 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
530 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
531 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
532 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
533 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
534 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600535 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
536 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
537 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
538 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
539 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
540 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
541 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
542 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800543
Rex Xu574ab042016-04-14 16:53:07 +0800544 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800545 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800546 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
547 return spv::BuiltInSubgroupSize;
548
Rex Xu574ab042016-04-14 16:53:07 +0800549 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800550 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800551 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
552 return spv::BuiltInSubgroupLocalInvocationId;
553
Rex Xu574ab042016-04-14 16:53:07 +0800554 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800555 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
556 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
557 return spv::BuiltInSubgroupEqMaskKHR;
558
Rex Xu574ab042016-04-14 16:53:07 +0800559 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800560 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
561 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
562 return spv::BuiltInSubgroupGeMaskKHR;
563
Rex Xu574ab042016-04-14 16:53:07 +0800564 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800565 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
566 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
567 return spv::BuiltInSubgroupGtMaskKHR;
568
Rex Xu574ab042016-04-14 16:53:07 +0800569 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800570 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
571 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
572 return spv::BuiltInSubgroupLeMaskKHR;
573
Rex Xu574ab042016-04-14 16:53:07 +0800574 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800575 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
576 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
577 return spv::BuiltInSubgroupLtMaskKHR;
578
Rex Xu9d93a232016-05-05 12:30:44 +0800579#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800580 case glslang::EbvBaryCoordNoPersp:
581 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
582 return spv::BuiltInBaryCoordNoPerspAMD;
583
584 case glslang::EbvBaryCoordNoPerspCentroid:
585 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
586 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
587
588 case glslang::EbvBaryCoordNoPerspSample:
589 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
590 return spv::BuiltInBaryCoordNoPerspSampleAMD;
591
592 case glslang::EbvBaryCoordSmooth:
593 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
594 return spv::BuiltInBaryCoordSmoothAMD;
595
596 case glslang::EbvBaryCoordSmoothCentroid:
597 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
598 return spv::BuiltInBaryCoordSmoothCentroidAMD;
599
600 case glslang::EbvBaryCoordSmoothSample:
601 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
602 return spv::BuiltInBaryCoordSmoothSampleAMD;
603
604 case glslang::EbvBaryCoordPullModel:
605 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
606 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800607#endif
chaoc771d89f2017-01-13 01:10:53 -0800608
John Kessenich6c8aaac2017-02-27 01:20:51 -0700609 case glslang::EbvDeviceIndex:
610 builder.addExtension(spv::E_SPV_KHR_device_group);
611 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700612 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700613
614 case glslang::EbvViewIndex:
615 builder.addExtension(spv::E_SPV_KHR_multiview);
616 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700617 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700618
chaoc771d89f2017-01-13 01:10:53 -0800619#ifdef NV_EXTENSIONS
620 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800621 if (!memberDeclaration) {
622 builder.addExtension(spv::E_SPV_NV_viewport_array2);
623 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
624 }
chaoc771d89f2017-01-13 01:10:53 -0800625 return spv::BuiltInViewportMaskNV;
626 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800627 if (!memberDeclaration) {
628 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
629 builder.addCapability(spv::CapabilityShaderStereoViewNV);
630 }
chaoc771d89f2017-01-13 01:10:53 -0800631 return spv::BuiltInSecondaryPositionNV;
632 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800633 if (!memberDeclaration) {
634 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
635 builder.addCapability(spv::CapabilityShaderStereoViewNV);
636 }
chaoc771d89f2017-01-13 01:10:53 -0800637 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800638 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800639 if (!memberDeclaration) {
640 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
641 builder.addCapability(spv::CapabilityPerViewAttributesNV);
642 }
chaocdf3956c2017-02-14 14:52:34 -0800643 return spv::BuiltInPositionPerViewNV;
644 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800645 if (!memberDeclaration) {
646 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
647 builder.addCapability(spv::CapabilityPerViewAttributesNV);
648 }
chaocdf3956c2017-02-14 14:52:34 -0800649 return spv::BuiltInViewportMaskPerViewNV;
Piers Daniell1c5443c2017-12-13 13:07:22 -0700650 case glslang::EbvFragFullyCoveredNV:
651 builder.addExtension(spv::E_SPV_EXT_fragment_fully_covered);
652 builder.addCapability(spv::CapabilityFragmentFullyCoveredEXT);
653 return spv::BuiltInFullyCoveredEXT;
chaoc771d89f2017-01-13 01:10:53 -0800654#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800655 default:
656 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600657 }
658}
659
Rex Xufc618912015-09-09 16:42:49 +0800660// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700661spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800662{
663 assert(type.getBasicType() == glslang::EbtSampler);
664
John Kessenich5d0fa972016-02-15 11:57:00 -0700665 // Check for capabilities
666 switch (type.getQualifier().layoutFormat) {
667 case glslang::ElfRg32f:
668 case glslang::ElfRg16f:
669 case glslang::ElfR11fG11fB10f:
670 case glslang::ElfR16f:
671 case glslang::ElfRgba16:
672 case glslang::ElfRgb10A2:
673 case glslang::ElfRg16:
674 case glslang::ElfRg8:
675 case glslang::ElfR16:
676 case glslang::ElfR8:
677 case glslang::ElfRgba16Snorm:
678 case glslang::ElfRg16Snorm:
679 case glslang::ElfRg8Snorm:
680 case glslang::ElfR16Snorm:
681 case glslang::ElfR8Snorm:
682
683 case glslang::ElfRg32i:
684 case glslang::ElfRg16i:
685 case glslang::ElfRg8i:
686 case glslang::ElfR16i:
687 case glslang::ElfR8i:
688
689 case glslang::ElfRgb10a2ui:
690 case glslang::ElfRg32ui:
691 case glslang::ElfRg16ui:
692 case glslang::ElfRg8ui:
693 case glslang::ElfR16ui:
694 case glslang::ElfR8ui:
695 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
696 break;
697
698 default:
699 break;
700 }
701
702 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800703 switch (type.getQualifier().layoutFormat) {
704 case glslang::ElfNone: return spv::ImageFormatUnknown;
705 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
706 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
707 case glslang::ElfR32f: return spv::ImageFormatR32f;
708 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
709 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
710 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
711 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
712 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
713 case glslang::ElfR16f: return spv::ImageFormatR16f;
714 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
715 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
716 case glslang::ElfRg16: return spv::ImageFormatRg16;
717 case glslang::ElfRg8: return spv::ImageFormatRg8;
718 case glslang::ElfR16: return spv::ImageFormatR16;
719 case glslang::ElfR8: return spv::ImageFormatR8;
720 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
721 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
722 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
723 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
724 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
725 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
726 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
727 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
728 case glslang::ElfR32i: return spv::ImageFormatR32i;
729 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
730 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
731 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
732 case glslang::ElfR16i: return spv::ImageFormatR16i;
733 case glslang::ElfR8i: return spv::ImageFormatR8i;
734 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
735 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
736 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
737 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
738 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
739 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
740 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
741 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
742 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
743 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600744 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800745 }
746}
747
Rex Xu57e65922017-07-04 23:23:40 +0800748spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(glslang::TSelectionControl selectionControl) const
749{
750 switch (selectionControl) {
751 case glslang::ESelectionControlNone: return spv::SelectionControlMaskNone;
752 case glslang::ESelectionControlFlatten: return spv::SelectionControlFlattenMask;
753 case glslang::ESelectionControlDontFlatten: return spv::SelectionControlDontFlattenMask;
754 default: return spv::SelectionControlMaskNone;
755 }
756}
757
steve-lunargf1709e72017-05-02 20:14:50 -0600758spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
759{
760 switch (loopControl) {
761 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
762 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
763 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
764 // TODO: DependencyInfinite
765 // TODO: DependencyLength
766 default: return spv::LoopControlMaskNone;
767 }
768}
769
John Kessenicha5c5fb62017-05-05 05:09:58 -0600770// Translate glslang type to SPIR-V storage class.
771spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
772{
773 if (type.getQualifier().isPipeInput())
774 return spv::StorageClassInput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600775 if (type.getQualifier().isPipeOutput())
John Kessenicha5c5fb62017-05-05 05:09:58 -0600776 return spv::StorageClassOutput;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600777
778 if (glslangIntermediate->getSource() != glslang::EShSourceHlsl ||
779 type.getQualifier().storage == glslang::EvqUniform) {
780 if (type.getBasicType() == glslang::EbtAtomicUint)
781 return spv::StorageClassAtomicCounter;
782 if (type.containsOpaque())
783 return spv::StorageClassUniformConstant;
784 }
785
786 if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600787 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
788 return spv::StorageClassStorageBuffer;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600789 }
790
791 if (type.getQualifier().isUniformOrBuffer()) {
John Kessenicha5c5fb62017-05-05 05:09:58 -0600792 if (type.getQualifier().layoutPushConstant)
793 return spv::StorageClassPushConstant;
794 if (type.getBasicType() == glslang::EbtBlock)
795 return spv::StorageClassUniform;
John Kessenichbed4e4f2017-09-08 02:38:07 -0600796 return spv::StorageClassUniformConstant;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600797 }
John Kessenichbed4e4f2017-09-08 02:38:07 -0600798
799 switch (type.getQualifier().storage) {
800 case glslang::EvqShared: return spv::StorageClassWorkgroup;
801 case glslang::EvqGlobal: return spv::StorageClassPrivate;
802 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
803 case glslang::EvqTemporary: return spv::StorageClassFunction;
804 default:
805 assert(0);
806 break;
807 }
808
809 return spv::StorageClassFunction;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600810}
811
qining25262b32016-05-06 17:25:16 -0400812// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700813// descriptor set.
814bool IsDescriptorResource(const glslang::TType& type)
815{
John Kessenichf7497e22016-03-08 21:36:22 -0700816 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700817 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700818 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700819
820 // non block...
821 // basically samplerXXX/subpass/sampler/texture are all included
822 // if they are the global-scope-class, not the function parameter
823 // (or local, if they ever exist) class.
824 if (type.getBasicType() == glslang::EbtSampler)
825 return type.getQualifier().isUniformOrBuffer();
826
827 // None of the above.
828 return false;
829}
830
John Kesseniche0b6cad2015-12-24 10:30:13 -0700831void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
832{
833 if (child.layoutMatrix == glslang::ElmNone)
834 child.layoutMatrix = parent.layoutMatrix;
835
836 if (parent.invariant)
837 child.invariant = true;
838 if (parent.nopersp)
839 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800840#ifdef AMD_EXTENSIONS
841 if (parent.explicitInterp)
842 child.explicitInterp = true;
843#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700844 if (parent.flat)
845 child.flat = true;
846 if (parent.centroid)
847 child.centroid = true;
848 if (parent.patch)
849 child.patch = true;
850 if (parent.sample)
851 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800852 if (parent.coherent)
853 child.coherent = true;
854 if (parent.volatil)
855 child.volatil = true;
856 if (parent.restrict)
857 child.restrict = true;
858 if (parent.readonly)
859 child.readonly = true;
860 if (parent.writeonly)
861 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700862}
863
John Kessenichf2b7f332016-09-01 17:05:23 -0600864bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700865{
John Kessenich7b9fa252016-01-21 18:56:57 -0700866 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600867 // - struct members might inherit from a struct declaration
868 // (note that non-block structs don't explicitly inherit,
869 // only implicitly, meaning no decoration involved)
870 // - affect decorations on the struct members
871 // (note smooth does not, and expecting something like volatile
872 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700873 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600874 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700875}
876
John Kessenich140f3df2015-06-26 16:58:36 -0600877//
878// Implement the TGlslangToSpvTraverser class.
879//
880
John Kessenich121853f2017-05-31 17:11:16 -0600881TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate,
882 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
883 : TIntermTraverser(true, false, true),
884 options(options),
885 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600886 sequenceDepth(0), logger(buildLogger),
John Kessenicha372a3e2017-11-02 22:32:14 -0600887 builder((glslang::GetKhronosToolId() << 16) | glslang::GetSpirvGeneratorVersion(), logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700888 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600889 glslangIntermediate(glslangIntermediate)
890{
891 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
892
893 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600894 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
895 glslangIntermediate->getVersion());
896
John Kessenich121853f2017-05-31 17:11:16 -0600897 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600898 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600899 builder.setSourceFile(glslangIntermediate->getSourceFile());
900
901 // Set the source shader's text. If for SPV version 1.0, include
902 // a preamble in comments stating the OpModuleProcessed instructions.
903 // Otherwise, emit those as actual instructions.
904 std::string text;
905 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
906 for (int p = 0; p < (int)processes.size(); ++p) {
907 if (glslangIntermediate->getSpv().spv < 0x00010100) {
908 text.append("// OpModuleProcessed ");
909 text.append(processes[p]);
910 text.append("\n");
911 } else
912 builder.addModuleProcessed(processes[p]);
913 }
914 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
915 text.append("#line 1\n");
916 text.append(glslangIntermediate->getSourceText());
917 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600918 }
John Kessenich140f3df2015-06-26 16:58:36 -0600919 stdBuiltins = builder.import("GLSL.std.450");
920 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600921 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
922 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600923
924 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600925 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
926 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600927 builder.addSourceExtension(it->c_str());
928
929 // Add the top-level modes for this shader.
930
John Kessenich92187592016-02-01 13:45:25 -0700931 if (glslangIntermediate->getXfbMode()) {
932 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600933 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700934 }
John Kessenich140f3df2015-06-26 16:58:36 -0600935
936 unsigned int mode;
937 switch (glslangIntermediate->getStage()) {
938 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600939 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600940 break;
941
steve-lunarge7412492017-03-23 11:56:07 -0600942 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600943 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600944 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600945
steve-lunarge7412492017-03-23 11:56:07 -0600946 glslang::TLayoutGeometry primitive;
947
948 if (glslangIntermediate->getStage() == EShLangTessControl) {
949 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
950 primitive = glslangIntermediate->getOutputPrimitive();
951 } else {
952 primitive = glslangIntermediate->getInputPrimitive();
953 }
954
955 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700956 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
957 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
958 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600959 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600960 }
John Kessenich4016e382016-07-15 11:53:56 -0600961 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600962 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
963
John Kesseniche6903322015-10-13 16:29:02 -0600964 switch (glslangIntermediate->getVertexSpacing()) {
965 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
966 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
967 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600968 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600969 }
John Kessenich4016e382016-07-15 11:53:56 -0600970 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600971 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
972
973 switch (glslangIntermediate->getVertexOrder()) {
974 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
975 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600976 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600977 }
John Kessenich4016e382016-07-15 11:53:56 -0600978 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600979 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
980
981 if (glslangIntermediate->getPointMode())
982 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600983 break;
984
985 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600986 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600987 switch (glslangIntermediate->getInputPrimitive()) {
988 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
989 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
990 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700991 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600992 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600993 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600994 }
John Kessenich4016e382016-07-15 11:53:56 -0600995 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600996 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600997
John Kessenich140f3df2015-06-26 16:58:36 -0600998 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
999
1000 switch (glslangIntermediate->getOutputPrimitive()) {
1001 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
1002 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
1003 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -06001004 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -06001005 }
John Kessenich4016e382016-07-15 11:53:56 -06001006 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -06001007 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1008 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
1009 break;
1010
1011 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -06001012 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -06001013 if (glslangIntermediate->getPixelCenterInteger())
1014 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -06001015
John Kessenich140f3df2015-06-26 16:58:36 -06001016 if (glslangIntermediate->getOriginUpperLeft())
1017 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -06001018 else
1019 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001020
1021 if (glslangIntermediate->getEarlyFragmentTests())
1022 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1023
chaocc1204522017-06-30 17:14:30 -07001024 if (glslangIntermediate->getPostDepthCoverage()) {
1025 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1026 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1027 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1028 }
1029
John Kesseniche6903322015-10-13 16:29:02 -06001030 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001031 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1032 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001033 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001034 }
John Kessenich4016e382016-07-15 11:53:56 -06001035 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001036 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1037
1038 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1039 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001040 break;
1041
1042 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001043 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001044 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1045 glslangIntermediate->getLocalSize(1),
1046 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001047 break;
1048
1049 default:
1050 break;
1051 }
John Kessenich140f3df2015-06-26 16:58:36 -06001052}
1053
John Kessenichfca82622016-11-26 13:23:20 -07001054// Finish creating SPV, after the traversal is complete.
1055void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001056{
John Kessenich517fe7a2016-11-26 13:31:47 -07001057 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001058 builder.setBuildPoint(shaderEntry->getLastBlock());
1059 builder.leaveFunction();
1060 }
1061
John Kessenich7ba63412015-12-20 17:37:07 -07001062 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001063 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1064 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001065
qiningda397332016-03-09 19:54:03 -05001066 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001067}
1068
John Kessenichfca82622016-11-26 13:23:20 -07001069// Write the SPV into 'out'.
1070void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001071{
John Kessenichfca82622016-11-26 13:23:20 -07001072 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001073}
1074
1075//
1076// Implement the traversal functions.
1077//
1078// Return true from interior nodes to have the external traversal
1079// continue on to children. Return false if children were
1080// already processed.
1081//
1082
1083//
qining25262b32016-05-06 17:25:16 -04001084// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001085// - uniform/input reads
1086// - output writes
1087// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1088// - something simple that degenerates into the last bullet
1089//
1090void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1091{
qining75d1d802016-04-06 14:42:01 -04001092 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1093 if (symbol->getType().getQualifier().isSpecConstant())
1094 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1095
John Kessenich140f3df2015-06-26 16:58:36 -06001096 // getSymbolId() will set up all the IO decorations on the first call.
1097 // Formal function parameters were mapped during makeFunctions().
1098 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001099
1100 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1101 if (builder.isPointer(id)) {
1102 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001103 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1104 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1105 iOSet.insert(id);
1106 }
John Kessenich7ba63412015-12-20 17:37:07 -07001107 }
1108
1109 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001110 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001111 // Prepare to generate code for the access
1112
1113 // L-value chains will be computed left to right. We're on the symbol now,
1114 // which is the left-most part of the access chain, so now is "clear" time,
1115 // followed by setting the base.
1116 builder.clearAccessChain();
1117
1118 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001119 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001120 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001121 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001122 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001123 // These are also pure R-values.
1124 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001125 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001126 builder.setAccessChainRValue(id);
1127 else
1128 builder.setAccessChainLValue(id);
1129 }
1130}
1131
1132bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1133{
John Kesseniche485c7a2017-05-31 18:50:53 -06001134 builder.setLine(node->getLoc().line);
1135
qining40887662016-04-03 22:20:42 -04001136 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1137 if (node->getType().getQualifier().isSpecConstant())
1138 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1139
John Kessenich140f3df2015-06-26 16:58:36 -06001140 // First, handle special cases
1141 switch (node->getOp()) {
1142 case glslang::EOpAssign:
1143 case glslang::EOpAddAssign:
1144 case glslang::EOpSubAssign:
1145 case glslang::EOpMulAssign:
1146 case glslang::EOpVectorTimesMatrixAssign:
1147 case glslang::EOpVectorTimesScalarAssign:
1148 case glslang::EOpMatrixTimesScalarAssign:
1149 case glslang::EOpMatrixTimesMatrixAssign:
1150 case glslang::EOpDivAssign:
1151 case glslang::EOpModAssign:
1152 case glslang::EOpAndAssign:
1153 case glslang::EOpInclusiveOrAssign:
1154 case glslang::EOpExclusiveOrAssign:
1155 case glslang::EOpLeftShiftAssign:
1156 case glslang::EOpRightShiftAssign:
1157 // A bin-op assign "a += b" means the same thing as "a = a + b"
1158 // where a is evaluated before b. For a simple assignment, GLSL
1159 // says to evaluate the left before the right. So, always, left
1160 // node then right node.
1161 {
1162 // get the left l-value, save it away
1163 builder.clearAccessChain();
1164 node->getLeft()->traverse(this);
1165 spv::Builder::AccessChain lValue = builder.getAccessChain();
1166
1167 // evaluate the right
1168 builder.clearAccessChain();
1169 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001170 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001171
1172 if (node->getOp() != glslang::EOpAssign) {
1173 // the left is also an r-value
1174 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001175 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001176
1177 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001178 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001179 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001180 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1181 node->getType().getBasicType());
1182
1183 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001184 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001185 }
1186
1187 // store the result
1188 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001189 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001190
1191 // assignments are expressions having an rValue after they are evaluated...
1192 builder.clearAccessChain();
1193 builder.setAccessChainRValue(rValue);
1194 }
1195 return false;
1196 case glslang::EOpIndexDirect:
1197 case glslang::EOpIndexDirectStruct:
1198 {
1199 // Get the left part of the access chain.
1200 node->getLeft()->traverse(this);
1201
1202 // Add the next element in the chain
1203
David Netoa901ffe2016-06-08 14:11:40 +01001204 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001205 if (! node->getLeft()->getType().isArray() &&
1206 node->getLeft()->getType().isVector() &&
1207 node->getOp() == glslang::EOpIndexDirect) {
1208 // This is essentially a hard-coded vector swizzle of size 1,
1209 // so short circuit the access-chain stuff with a swizzle.
1210 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001211 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001212 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001213 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001214 int spvIndex = glslangIndex;
1215 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1216 node->getOp() == glslang::EOpIndexDirectStruct)
1217 {
1218 // This may be, e.g., an anonymous block-member selection, which generally need
1219 // index remapping due to hidden members in anonymous blocks.
1220 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1221 assert(remapper.size() > 0);
1222 spvIndex = remapper[glslangIndex];
1223 }
John Kessenichebb50532016-05-16 19:22:05 -06001224
David Netoa901ffe2016-06-08 14:11:40 +01001225 // normal case for indexing array or structure or block
1226 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1227
1228 // Add capabilities here for accessing PointSize and clip/cull distance.
1229 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001230 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001231 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001232 }
1233 }
1234 return false;
1235 case glslang::EOpIndexIndirect:
1236 {
1237 // Structure or array or vector indirection.
1238 // Will use native SPIR-V access-chain for struct and array indirection;
1239 // matrices are arrays of vectors, so will also work for a matrix.
1240 // Will use the access chain's 'component' for variable index into a vector.
1241
1242 // This adapter is building access chains left to right.
1243 // Set up the access chain to the left.
1244 node->getLeft()->traverse(this);
1245
1246 // save it so that computing the right side doesn't trash it
1247 spv::Builder::AccessChain partial = builder.getAccessChain();
1248
1249 // compute the next index in the chain
1250 builder.clearAccessChain();
1251 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001252 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001253
1254 // restore the saved access chain
1255 builder.setAccessChain(partial);
1256
1257 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001258 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001259 else
John Kessenichfa668da2015-09-13 14:46:30 -06001260 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001261 }
1262 return false;
1263 case glslang::EOpVectorSwizzle:
1264 {
1265 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001266 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001267 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001268 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001269 }
1270 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001271 case glslang::EOpMatrixSwizzle:
1272 logger->missingFunctionality("matrix swizzle");
1273 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001274 case glslang::EOpLogicalOr:
1275 case glslang::EOpLogicalAnd:
1276 {
1277
1278 // These may require short circuiting, but can sometimes be done as straight
1279 // binary operations. The right operand must be short circuited if it has
1280 // side effects, and should probably be if it is complex.
1281 if (isTrivial(node->getRight()->getAsTyped()))
1282 break; // handle below as a normal binary operation
1283 // otherwise, we need to do dynamic short circuiting on the right operand
1284 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1285 builder.clearAccessChain();
1286 builder.setAccessChainRValue(result);
1287 }
1288 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001289 default:
1290 break;
1291 }
1292
1293 // Assume generic binary op...
1294
John Kessenich32cfd492016-02-02 12:37:46 -07001295 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001296 builder.clearAccessChain();
1297 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001298 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001299
John Kessenich32cfd492016-02-02 12:37:46 -07001300 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001301 builder.clearAccessChain();
1302 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001303 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001304
John Kessenich32cfd492016-02-02 12:37:46 -07001305 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001306 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001307 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001308 convertGlslangToSpvType(node->getType()), left, right,
1309 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001310
John Kessenich50e57562015-12-21 21:21:11 -07001311 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001312 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001313 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001314 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001315 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001316 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001317 return false;
1318 }
John Kessenich140f3df2015-06-26 16:58:36 -06001319}
1320
1321bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1322{
John Kesseniche485c7a2017-05-31 18:50:53 -06001323 builder.setLine(node->getLoc().line);
1324
qining40887662016-04-03 22:20:42 -04001325 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1326 if (node->getType().getQualifier().isSpecConstant())
1327 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1328
John Kessenichfc51d282015-08-19 13:34:18 -06001329 spv::Id result = spv::NoResult;
1330
1331 // try texturing first
1332 result = createImageTextureFunctionCall(node);
1333 if (result != spv::NoResult) {
1334 builder.clearAccessChain();
1335 builder.setAccessChainRValue(result);
1336
1337 return false; // done with this node
1338 }
1339
1340 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001341
1342 if (node->getOp() == glslang::EOpArrayLength) {
1343 // Quite special; won't want to evaluate the operand.
1344
1345 // Normal .length() would have been constant folded by the front-end.
1346 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001347 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001348 assert(node->getOperand()->getType().isRuntimeSizedArray());
1349 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1350 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001351 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1352 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001353
1354 builder.clearAccessChain();
1355 builder.setAccessChainRValue(length);
1356
1357 return false;
1358 }
1359
John Kessenichfc51d282015-08-19 13:34:18 -06001360 // Start by evaluating the operand
1361
John Kessenich8c8505c2016-07-26 12:50:38 -06001362 // Does it need a swizzle inversion? If so, evaluation is inverted;
1363 // operate first on the swizzle base, then apply the swizzle.
1364 spv::Id invertedType = spv::NoType;
1365 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1366 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1367 invertedType = getInvertedSwizzleType(*node->getOperand());
1368
John Kessenich140f3df2015-06-26 16:58:36 -06001369 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001370 if (invertedType != spv::NoType)
1371 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1372 else
1373 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001374
Rex Xufc618912015-09-09 16:42:49 +08001375 spv::Id operand = spv::NoResult;
1376
1377 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1378 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001379 node->getOp() == glslang::EOpAtomicCounter ||
1380 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001381 operand = builder.accessChainGetLValue(); // Special case l-value operands
1382 else
John Kessenich32cfd492016-02-02 12:37:46 -07001383 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001384
John Kessenichf6640762016-08-01 19:44:00 -06001385 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001386 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001387
1388 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001389 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001390 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001391
1392 // if not, then possibly an operation
1393 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001394 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001395
1396 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001397 if (invertedType)
1398 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1399
John Kessenich140f3df2015-06-26 16:58:36 -06001400 builder.clearAccessChain();
1401 builder.setAccessChainRValue(result);
1402
1403 return false; // done with this node
1404 }
1405
1406 // it must be a special case, check...
1407 switch (node->getOp()) {
1408 case glslang::EOpPostIncrement:
1409 case glslang::EOpPostDecrement:
1410 case glslang::EOpPreIncrement:
1411 case glslang::EOpPreDecrement:
1412 {
1413 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001414 spv::Id one = 0;
1415 if (node->getBasicType() == glslang::EbtFloat)
1416 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001417 else if (node->getBasicType() == glslang::EbtDouble)
1418 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001419#ifdef AMD_EXTENSIONS
1420 else if (node->getBasicType() == glslang::EbtFloat16)
1421 one = builder.makeFloat16Constant(1.0F);
1422#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001423 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1424 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001425#ifdef AMD_EXTENSIONS
1426 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1427 one = builder.makeInt16Constant(1);
1428#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001429 else
1430 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001431 glslang::TOperator op;
1432 if (node->getOp() == glslang::EOpPreIncrement ||
1433 node->getOp() == glslang::EOpPostIncrement)
1434 op = glslang::EOpAdd;
1435 else
1436 op = glslang::EOpSub;
1437
John Kessenichf6640762016-08-01 19:44:00 -06001438 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001439 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001440 convertGlslangToSpvType(node->getType()), operand, one,
1441 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001442 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001443
1444 // The result of operation is always stored, but conditionally the
1445 // consumed result. The consumed result is always an r-value.
1446 builder.accessChainStore(result);
1447 builder.clearAccessChain();
1448 if (node->getOp() == glslang::EOpPreIncrement ||
1449 node->getOp() == glslang::EOpPreDecrement)
1450 builder.setAccessChainRValue(result);
1451 else
1452 builder.setAccessChainRValue(operand);
1453 }
1454
1455 return false;
1456
1457 case glslang::EOpEmitStreamVertex:
1458 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1459 return false;
1460 case glslang::EOpEndStreamPrimitive:
1461 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1462 return false;
1463
1464 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001465 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001466 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001467 }
John Kessenich140f3df2015-06-26 16:58:36 -06001468}
1469
1470bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1471{
qining27e04a02016-04-14 16:40:20 -04001472 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1473 if (node->getType().getQualifier().isSpecConstant())
1474 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1475
John Kessenichfc51d282015-08-19 13:34:18 -06001476 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001477 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1478 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001479
1480 // try texturing
1481 result = createImageTextureFunctionCall(node);
1482 if (result != spv::NoResult) {
1483 builder.clearAccessChain();
1484 builder.setAccessChainRValue(result);
1485
1486 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001487#ifdef AMD_EXTENSIONS
1488 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1489#else
John Kessenich56bab042015-09-16 10:54:31 -06001490 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001491#endif
Rex Xufc618912015-09-09 16:42:49 +08001492 // "imageStore" is a special case, which has no result
1493 return false;
1494 }
John Kessenichfc51d282015-08-19 13:34:18 -06001495
John Kessenich140f3df2015-06-26 16:58:36 -06001496 glslang::TOperator binOp = glslang::EOpNull;
1497 bool reduceComparison = true;
1498 bool isMatrix = false;
1499 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001500 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001501
1502 assert(node->getOp());
1503
John Kessenichf6640762016-08-01 19:44:00 -06001504 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001505
1506 switch (node->getOp()) {
1507 case glslang::EOpSequence:
1508 {
1509 if (preVisit)
1510 ++sequenceDepth;
1511 else
1512 --sequenceDepth;
1513
1514 if (sequenceDepth == 1) {
1515 // If this is the parent node of all the functions, we want to see them
1516 // early, so all call points have actual SPIR-V functions to reference.
1517 // In all cases, still let the traverser visit the children for us.
1518 makeFunctions(node->getAsAggregate()->getSequence());
1519
John Kessenich6fccb3c2016-09-19 16:01:41 -06001520 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001521 // anything else gets there, so visit out of order, doing them all now.
1522 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1523
John Kessenich6a60c2f2016-12-08 21:01:59 -07001524 // Initializers are done, don't want to visit again, but functions and link objects need to be processed,
John Kessenich140f3df2015-06-26 16:58:36 -06001525 // so do them manually.
1526 visitFunctions(node->getAsAggregate()->getSequence());
1527
1528 return false;
1529 }
1530
1531 return true;
1532 }
1533 case glslang::EOpLinkerObjects:
1534 {
1535 if (visit == glslang::EvPreVisit)
1536 linkageOnly = true;
1537 else
1538 linkageOnly = false;
1539
1540 return true;
1541 }
1542 case glslang::EOpComma:
1543 {
1544 // processing from left to right naturally leaves the right-most
1545 // lying around in the access chain
1546 glslang::TIntermSequence& glslangOperands = node->getSequence();
1547 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1548 glslangOperands[i]->traverse(this);
1549
1550 return false;
1551 }
1552 case glslang::EOpFunction:
1553 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001554 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001555 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001556 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001557 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001558 } else {
1559 handleFunctionEntry(node);
1560 }
1561 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001562 if (inEntryPoint)
1563 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001564 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001565 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001566 }
1567
1568 return true;
1569 case glslang::EOpParameters:
1570 // Parameters will have been consumed by EOpFunction processing, but not
1571 // the body, so we still visited the function node's children, making this
1572 // child redundant.
1573 return false;
1574 case glslang::EOpFunctionCall:
1575 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001576 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001577 if (node->isUserDefined())
1578 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001579 // assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
John Kessenich6c292d32016-02-15 20:58:50 -07001580 if (result) {
1581 builder.clearAccessChain();
1582 builder.setAccessChainRValue(result);
1583 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001584 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001585
1586 return false;
1587 }
1588 case glslang::EOpConstructMat2x2:
1589 case glslang::EOpConstructMat2x3:
1590 case glslang::EOpConstructMat2x4:
1591 case glslang::EOpConstructMat3x2:
1592 case glslang::EOpConstructMat3x3:
1593 case glslang::EOpConstructMat3x4:
1594 case glslang::EOpConstructMat4x2:
1595 case glslang::EOpConstructMat4x3:
1596 case glslang::EOpConstructMat4x4:
1597 case glslang::EOpConstructDMat2x2:
1598 case glslang::EOpConstructDMat2x3:
1599 case glslang::EOpConstructDMat2x4:
1600 case glslang::EOpConstructDMat3x2:
1601 case glslang::EOpConstructDMat3x3:
1602 case glslang::EOpConstructDMat3x4:
1603 case glslang::EOpConstructDMat4x2:
1604 case glslang::EOpConstructDMat4x3:
1605 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001606 case glslang::EOpConstructIMat2x2:
1607 case glslang::EOpConstructIMat2x3:
1608 case glslang::EOpConstructIMat2x4:
1609 case glslang::EOpConstructIMat3x2:
1610 case glslang::EOpConstructIMat3x3:
1611 case glslang::EOpConstructIMat3x4:
1612 case glslang::EOpConstructIMat4x2:
1613 case glslang::EOpConstructIMat4x3:
1614 case glslang::EOpConstructIMat4x4:
1615 case glslang::EOpConstructUMat2x2:
1616 case glslang::EOpConstructUMat2x3:
1617 case glslang::EOpConstructUMat2x4:
1618 case glslang::EOpConstructUMat3x2:
1619 case glslang::EOpConstructUMat3x3:
1620 case glslang::EOpConstructUMat3x4:
1621 case glslang::EOpConstructUMat4x2:
1622 case glslang::EOpConstructUMat4x3:
1623 case glslang::EOpConstructUMat4x4:
1624 case glslang::EOpConstructBMat2x2:
1625 case glslang::EOpConstructBMat2x3:
1626 case glslang::EOpConstructBMat2x4:
1627 case glslang::EOpConstructBMat3x2:
1628 case glslang::EOpConstructBMat3x3:
1629 case glslang::EOpConstructBMat3x4:
1630 case glslang::EOpConstructBMat4x2:
1631 case glslang::EOpConstructBMat4x3:
1632 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001633#ifdef AMD_EXTENSIONS
1634 case glslang::EOpConstructF16Mat2x2:
1635 case glslang::EOpConstructF16Mat2x3:
1636 case glslang::EOpConstructF16Mat2x4:
1637 case glslang::EOpConstructF16Mat3x2:
1638 case glslang::EOpConstructF16Mat3x3:
1639 case glslang::EOpConstructF16Mat3x4:
1640 case glslang::EOpConstructF16Mat4x2:
1641 case glslang::EOpConstructF16Mat4x3:
1642 case glslang::EOpConstructF16Mat4x4:
1643#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001644 isMatrix = true;
1645 // fall through
1646 case glslang::EOpConstructFloat:
1647 case glslang::EOpConstructVec2:
1648 case glslang::EOpConstructVec3:
1649 case glslang::EOpConstructVec4:
1650 case glslang::EOpConstructDouble:
1651 case glslang::EOpConstructDVec2:
1652 case glslang::EOpConstructDVec3:
1653 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001654#ifdef AMD_EXTENSIONS
1655 case glslang::EOpConstructFloat16:
1656 case glslang::EOpConstructF16Vec2:
1657 case glslang::EOpConstructF16Vec3:
1658 case glslang::EOpConstructF16Vec4:
1659#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001660 case glslang::EOpConstructBool:
1661 case glslang::EOpConstructBVec2:
1662 case glslang::EOpConstructBVec3:
1663 case glslang::EOpConstructBVec4:
1664 case glslang::EOpConstructInt:
1665 case glslang::EOpConstructIVec2:
1666 case glslang::EOpConstructIVec3:
1667 case glslang::EOpConstructIVec4:
1668 case glslang::EOpConstructUint:
1669 case glslang::EOpConstructUVec2:
1670 case glslang::EOpConstructUVec3:
1671 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001672 case glslang::EOpConstructInt64:
1673 case glslang::EOpConstructI64Vec2:
1674 case glslang::EOpConstructI64Vec3:
1675 case glslang::EOpConstructI64Vec4:
1676 case glslang::EOpConstructUint64:
1677 case glslang::EOpConstructU64Vec2:
1678 case glslang::EOpConstructU64Vec3:
1679 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001680#ifdef AMD_EXTENSIONS
1681 case glslang::EOpConstructInt16:
1682 case glslang::EOpConstructI16Vec2:
1683 case glslang::EOpConstructI16Vec3:
1684 case glslang::EOpConstructI16Vec4:
1685 case glslang::EOpConstructUint16:
1686 case glslang::EOpConstructU16Vec2:
1687 case glslang::EOpConstructU16Vec3:
1688 case glslang::EOpConstructU16Vec4:
1689#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001690 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001691 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001692 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001693 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001694 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001695 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001696 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001697 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001698 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001699 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001700 std::vector<spv::Id> constituents;
1701 for (int c = 0; c < (int)arguments.size(); ++c)
1702 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001703 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001704 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001705 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001706 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001707 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001708
1709 builder.clearAccessChain();
1710 builder.setAccessChainRValue(constructed);
1711
1712 return false;
1713 }
1714
1715 // These six are component-wise compares with component-wise results.
1716 // Forward on to createBinaryOperation(), requesting a vector result.
1717 case glslang::EOpLessThan:
1718 case glslang::EOpGreaterThan:
1719 case glslang::EOpLessThanEqual:
1720 case glslang::EOpGreaterThanEqual:
1721 case glslang::EOpVectorEqual:
1722 case glslang::EOpVectorNotEqual:
1723 {
1724 // Map the operation to a binary
1725 binOp = node->getOp();
1726 reduceComparison = false;
1727 switch (node->getOp()) {
1728 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1729 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1730 default: binOp = node->getOp(); break;
1731 }
1732
1733 break;
1734 }
1735 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001736 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001737 binOp = glslang::EOpMul;
1738 break;
1739 case glslang::EOpOuterProduct:
1740 // two vectors multiplied to make a matrix
1741 binOp = glslang::EOpOuterProduct;
1742 break;
1743 case glslang::EOpDot:
1744 {
qining25262b32016-05-06 17:25:16 -04001745 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001746 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001747 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001748 binOp = glslang::EOpMul;
1749 break;
1750 }
1751 case glslang::EOpMod:
1752 // when an aggregate, this is the floating-point mod built-in function,
1753 // which can be emitted by the one in createBinaryOperation()
1754 binOp = glslang::EOpMod;
1755 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001756 case glslang::EOpEmitVertex:
1757 case glslang::EOpEndPrimitive:
1758 case glslang::EOpBarrier:
1759 case glslang::EOpMemoryBarrier:
1760 case glslang::EOpMemoryBarrierAtomicCounter:
1761 case glslang::EOpMemoryBarrierBuffer:
1762 case glslang::EOpMemoryBarrierImage:
1763 case glslang::EOpMemoryBarrierShared:
1764 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001765 case glslang::EOpAllMemoryBarrierWithGroupSync:
1766 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1767 case glslang::EOpWorkgroupMemoryBarrier:
1768 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001769 noReturnValue = true;
1770 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1771 break;
1772
John Kessenich426394d2015-07-23 10:22:48 -06001773 case glslang::EOpAtomicAdd:
1774 case glslang::EOpAtomicMin:
1775 case glslang::EOpAtomicMax:
1776 case glslang::EOpAtomicAnd:
1777 case glslang::EOpAtomicOr:
1778 case glslang::EOpAtomicXor:
1779 case glslang::EOpAtomicExchange:
1780 case glslang::EOpAtomicCompSwap:
1781 atomic = true;
1782 break;
1783
John Kessenich0d0c6d32017-07-23 16:08:26 -06001784 case glslang::EOpAtomicCounterAdd:
1785 case glslang::EOpAtomicCounterSubtract:
1786 case glslang::EOpAtomicCounterMin:
1787 case glslang::EOpAtomicCounterMax:
1788 case glslang::EOpAtomicCounterAnd:
1789 case glslang::EOpAtomicCounterOr:
1790 case glslang::EOpAtomicCounterXor:
1791 case glslang::EOpAtomicCounterExchange:
1792 case glslang::EOpAtomicCounterCompSwap:
1793 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1794 builder.addCapability(spv::CapabilityAtomicStorageOps);
1795 atomic = true;
1796 break;
1797
John Kessenich140f3df2015-06-26 16:58:36 -06001798 default:
1799 break;
1800 }
1801
1802 //
1803 // See if it maps to a regular operation.
1804 //
John Kessenich140f3df2015-06-26 16:58:36 -06001805 if (binOp != glslang::EOpNull) {
1806 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1807 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1808 assert(left && right);
1809
1810 builder.clearAccessChain();
1811 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001812 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001813
1814 builder.clearAccessChain();
1815 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001816 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001817
John Kesseniche485c7a2017-05-31 18:50:53 -06001818 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001819 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001820 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001821 left->getType().getBasicType(), reduceComparison);
1822
1823 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001824 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001825 builder.clearAccessChain();
1826 builder.setAccessChainRValue(result);
1827
1828 return false;
1829 }
1830
John Kessenich426394d2015-07-23 10:22:48 -06001831 //
1832 // Create the list of operands.
1833 //
John Kessenich140f3df2015-06-26 16:58:36 -06001834 glslang::TIntermSequence& glslangOperands = node->getSequence();
1835 std::vector<spv::Id> operands;
1836 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001837 // special case l-value operands; there are just a few
1838 bool lvalue = false;
1839 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001840 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001841 case glslang::EOpModf:
1842 if (arg == 1)
1843 lvalue = true;
1844 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001845 case glslang::EOpInterpolateAtSample:
1846 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001847#ifdef AMD_EXTENSIONS
1848 case glslang::EOpInterpolateAtVertex:
1849#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001850 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001851 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001852
1853 // Does it need a swizzle inversion? If so, evaluation is inverted;
1854 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001855 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001856 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1857 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1858 }
Rex Xu7a26c172015-12-08 17:12:09 +08001859 break;
Rex Xud4782c12015-09-06 16:30:11 +08001860 case glslang::EOpAtomicAdd:
1861 case glslang::EOpAtomicMin:
1862 case glslang::EOpAtomicMax:
1863 case glslang::EOpAtomicAnd:
1864 case glslang::EOpAtomicOr:
1865 case glslang::EOpAtomicXor:
1866 case glslang::EOpAtomicExchange:
1867 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001868 case glslang::EOpAtomicCounterAdd:
1869 case glslang::EOpAtomicCounterSubtract:
1870 case glslang::EOpAtomicCounterMin:
1871 case glslang::EOpAtomicCounterMax:
1872 case glslang::EOpAtomicCounterAnd:
1873 case glslang::EOpAtomicCounterOr:
1874 case glslang::EOpAtomicCounterXor:
1875 case glslang::EOpAtomicCounterExchange:
1876 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001877 if (arg == 0)
1878 lvalue = true;
1879 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001880 case glslang::EOpAddCarry:
1881 case glslang::EOpSubBorrow:
1882 if (arg == 2)
1883 lvalue = true;
1884 break;
1885 case glslang::EOpUMulExtended:
1886 case glslang::EOpIMulExtended:
1887 if (arg >= 2)
1888 lvalue = true;
1889 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001890 default:
1891 break;
1892 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001893 builder.clearAccessChain();
1894 if (invertedType != spv::NoType && arg == 0)
1895 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1896 else
1897 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001898 if (lvalue)
1899 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001900 else {
1901 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001902 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001903 }
John Kessenich140f3df2015-06-26 16:58:36 -06001904 }
John Kessenich426394d2015-07-23 10:22:48 -06001905
John Kesseniche485c7a2017-05-31 18:50:53 -06001906 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001907 if (atomic) {
1908 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001909 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001910 } else {
1911 // Pass through to generic operations.
1912 switch (glslangOperands.size()) {
1913 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001914 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001915 break;
1916 case 1:
qining25262b32016-05-06 17:25:16 -04001917 result = createUnaryOperation(
1918 node->getOp(), precision,
1919 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001920 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001921 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001922 break;
1923 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001924 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001925 break;
1926 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001927 if (invertedType)
1928 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001929 }
1930
1931 if (noReturnValue)
1932 return false;
1933
1934 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001935 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001936 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001937 } else {
1938 builder.clearAccessChain();
1939 builder.setAccessChainRValue(result);
1940 return false;
1941 }
1942}
1943
John Kessenich433e9ff2017-01-26 20:31:11 -07001944// This path handles both if-then-else and ?:
1945// The if-then-else has a node type of void, while
1946// ?: has either a void or a non-void node type
1947//
1948// Leaving the result, when not void:
1949// GLSL only has r-values as the result of a :?, but
1950// if we have an l-value, that can be more efficient if it will
1951// become the base of a complex r-value expression, because the
1952// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001953bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1954{
John Kessenich433e9ff2017-01-26 20:31:11 -07001955 // See if it simple and safe to generate OpSelect instead of using control flow.
1956 // Crucially, side effects must be avoided, and there are performance trade-offs.
1957 // Return true if good idea (and safe) for OpSelect, false otherwise.
1958 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001959 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1960 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001961 return false;
1962
1963 if (node->getTrueBlock() == nullptr ||
1964 node->getFalseBlock() == nullptr)
1965 return false;
1966
1967 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1968 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1969
1970 // return true if a single operand to ? : is okay for OpSelect
1971 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001972 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001973 };
1974
1975 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1976 operandOkay(node->getFalseBlock()->getAsTyped());
1977 };
1978
1979 // Emit OpSelect for this selection.
1980 const auto handleAsOpSelect = [&]() {
1981 node->getCondition()->traverse(this);
1982 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1983 node->getTrueBlock()->traverse(this);
1984 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1985 node->getFalseBlock()->traverse(this);
1986 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1987
John Kesseniche485c7a2017-05-31 18:50:53 -06001988 builder.setLine(node->getLoc().line);
1989
John Kesseniche434ad92017-03-30 10:09:28 -06001990 // smear condition to vector, if necessary (AST is always scalar)
1991 if (builder.isVector(trueValue))
1992 condition = builder.smearScalar(spv::NoPrecision, condition,
1993 builder.makeVectorType(builder.makeBoolType(),
1994 builder.getNumComponents(trueValue)));
1995
1996 spv::Id select = builder.createTriOp(spv::OpSelect,
1997 convertGlslangToSpvType(node->getType()), condition,
1998 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001999 builder.clearAccessChain();
2000 builder.setAccessChainRValue(select);
2001 };
2002
2003 // Try for OpSelect
2004
2005 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07002006 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
2007 if (node->getType().getQualifier().isSpecConstant())
2008 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
2009
John Kessenich433e9ff2017-01-26 20:31:11 -07002010 handleAsOpSelect();
2011 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06002012 }
2013
Rex Xu57e65922017-07-04 23:23:40 +08002014 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07002015 // Don't handle results as temporaries, because there will be two names
2016 // and better to leave SSA to later passes.
2017 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
2018 ? spv::NoResult
2019 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2020
John Kessenich140f3df2015-06-26 16:58:36 -06002021 // emit the condition before doing anything with selection
2022 node->getCondition()->traverse(this);
2023
Rex Xu57e65922017-07-04 23:23:40 +08002024 // Selection control:
2025 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2026
John Kessenich140f3df2015-06-26 16:58:36 -06002027 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08002028 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06002029
John Kessenich433e9ff2017-01-26 20:31:11 -07002030 // emit the "then" statement
2031 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002032 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002033 if (result != spv::NoResult)
2034 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002035 }
2036
John Kessenich433e9ff2017-01-26 20:31:11 -07002037 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002038 ifBuilder.makeBeginElse();
2039 // emit the "else" statement
2040 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002041 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07002042 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002043 }
2044
John Kessenich433e9ff2017-01-26 20:31:11 -07002045 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06002046 ifBuilder.makeEndIf();
2047
John Kessenich433e9ff2017-01-26 20:31:11 -07002048 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06002049 // GLSL only has r-values as the result of a :?, but
2050 // if we have an l-value, that can be more efficient if it will
2051 // become the base of a complex r-value expression, because the
2052 // next layer copies r-values into memory to use the access-chain mechanism
2053 builder.clearAccessChain();
2054 builder.setAccessChainLValue(result);
2055 }
2056
2057 return false;
2058}
2059
2060bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2061{
2062 // emit and get the condition before doing anything with switch
2063 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002064 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002065
Rex Xu57e65922017-07-04 23:23:40 +08002066 // Selection control:
2067 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2068
John Kessenich140f3df2015-06-26 16:58:36 -06002069 // browse the children to sort out code segments
2070 int defaultSegment = -1;
2071 std::vector<TIntermNode*> codeSegments;
2072 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2073 std::vector<int> caseValues;
2074 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2075 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2076 TIntermNode* child = *c;
2077 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002078 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002079 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002080 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002081 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2082 } else
2083 codeSegments.push_back(child);
2084 }
2085
qining25262b32016-05-06 17:25:16 -04002086 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002087 // statements between the last case and the end of the switch statement
2088 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2089 (int)codeSegments.size() == defaultSegment)
2090 codeSegments.push_back(nullptr);
2091
2092 // make the switch statement
2093 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002094 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002095
2096 // emit all the code in the segments
2097 breakForLoop.push(false);
2098 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2099 builder.nextSwitchSegment(segmentBlocks, s);
2100 if (codeSegments[s])
2101 codeSegments[s]->traverse(this);
2102 else
2103 builder.addSwitchBreak();
2104 }
2105 breakForLoop.pop();
2106
2107 builder.endSwitch(segmentBlocks);
2108
2109 return false;
2110}
2111
2112void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2113{
2114 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002115 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002116
2117 builder.clearAccessChain();
2118 builder.setAccessChainRValue(constant);
2119}
2120
2121bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2122{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002123 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002124 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002125
2126 // Loop control:
2127 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2128
2129 // TODO: dependency length
2130
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002131 // Spec requires back edges to target header blocks, and every header block
2132 // must dominate its merge block. Make a header block first to ensure these
2133 // conditions are met. By definition, it will contain OpLoopMerge, followed
2134 // by a block-ending branch. But we don't want to put any other body/test
2135 // instructions in it, since the body/test may have arbitrary instructions,
2136 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002137 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002138 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002139 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002140 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002141 spv::Block& test = builder.makeNewBlock();
2142 builder.createBranch(&test);
2143
2144 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002145 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002146 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002147 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2148
2149 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002150 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002151 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002152 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002153 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002154 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002155
2156 builder.setBuildPoint(&blocks.continue_target);
2157 if (node->getTerminal())
2158 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002159 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002160 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002161 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002162 builder.createBranch(&blocks.body);
2163
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002164 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002165 builder.setBuildPoint(&blocks.body);
2166 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002167 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002168 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002169 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002170
2171 builder.setBuildPoint(&blocks.continue_target);
2172 if (node->getTerminal())
2173 node->getTerminal()->traverse(this);
2174 if (node->getTest()) {
2175 node->getTest()->traverse(this);
2176 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002177 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002178 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002179 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002180 // TODO: unless there was a break/return/discard instruction
2181 // somewhere in the body, this is an infinite loop, so we should
2182 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002183 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002184 }
John Kessenich140f3df2015-06-26 16:58:36 -06002185 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002186 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002187 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002188 return false;
2189}
2190
2191bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2192{
2193 if (node->getExpression())
2194 node->getExpression()->traverse(this);
2195
John Kesseniche485c7a2017-05-31 18:50:53 -06002196 builder.setLine(node->getLoc().line);
2197
John Kessenich140f3df2015-06-26 16:58:36 -06002198 switch (node->getFlowOp()) {
2199 case glslang::EOpKill:
2200 builder.makeDiscard();
2201 break;
2202 case glslang::EOpBreak:
2203 if (breakForLoop.top())
2204 builder.createLoopExit();
2205 else
2206 builder.addSwitchBreak();
2207 break;
2208 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002209 builder.createLoopContinue();
2210 break;
2211 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002212 if (node->getExpression()) {
2213 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2214 spv::Id returnId = accessChainLoad(glslangReturnType);
2215 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2216 builder.clearAccessChain();
2217 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2218 builder.setAccessChainLValue(copyId);
2219 multiTypeStore(glslangReturnType, returnId);
2220 returnId = builder.createLoad(copyId);
2221 }
2222 builder.makeReturn(false, returnId);
2223 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002224 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002225
2226 builder.clearAccessChain();
2227 break;
2228
2229 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002230 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002231 break;
2232 }
2233
2234 return false;
2235}
2236
2237spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2238{
qining25262b32016-05-06 17:25:16 -04002239 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002240 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002241 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002242 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002243 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002244 }
2245
2246 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002247 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002248 spv::Id spvType = convertGlslangToSpvType(node->getType());
2249
Rex Xuf89ad982017-04-07 23:22:33 +08002250#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002251 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2252 node->getType().containsBasicType(glslang::EbtInt16) ||
2253 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002254 if (contains16BitType) {
2255 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2256 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2257 builder.addCapability(spv::CapabilityStorageInputOutput16);
2258 } else if (storageClass == spv::StorageClassPushConstant) {
2259 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2260 builder.addCapability(spv::CapabilityStoragePushConstant16);
2261 } else if (storageClass == spv::StorageClassUniform) {
2262 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2263 builder.addCapability(spv::CapabilityStorageUniform16);
2264 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2265 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2266 }
2267 }
2268#endif
2269
John Kessenich140f3df2015-06-26 16:58:36 -06002270 const char* name = node->getName().c_str();
2271 if (glslang::IsAnonymous(name))
2272 name = "";
2273
2274 return builder.createVariable(storageClass, spvType, name);
2275}
2276
2277// Return type Id of the sampled type.
2278spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2279{
2280 switch (sampler.type) {
2281 case glslang::EbtFloat: return builder.makeFloatType(32);
2282 case glslang::EbtInt: return builder.makeIntType(32);
2283 case glslang::EbtUint: return builder.makeUintType(32);
2284 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002285 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002286 return builder.makeFloatType(32);
2287 }
2288}
2289
John Kessenich8c8505c2016-07-26 12:50:38 -06002290// If node is a swizzle operation, return the type that should be used if
2291// the swizzle base is first consumed by another operation, before the swizzle
2292// is applied.
2293spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2294{
John Kessenichecba76f2017-01-06 00:34:48 -07002295 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002296 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2297 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2298 else
2299 return spv::NoType;
2300}
2301
2302// When inverting a swizzle with a parent op, this function
2303// will apply the swizzle operation to a completed parent operation.
2304spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2305{
2306 std::vector<unsigned> swizzle;
2307 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2308 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2309}
2310
John Kessenich8c8505c2016-07-26 12:50:38 -06002311// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2312void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2313{
2314 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2315 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2316 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2317}
2318
John Kessenich3ac051e2015-12-20 11:29:16 -07002319// Convert from a glslang type to an SPV type, by calling into a
2320// recursive version of this function. This establishes the inherited
2321// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002322spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2323{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002324 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002325}
2326
2327// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002328// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002329// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002330spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002331{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002332 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002333
2334 switch (type.getBasicType()) {
2335 case glslang::EbtVoid:
2336 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002337 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002338 break;
2339 case glslang::EbtFloat:
2340 spvType = builder.makeFloatType(32);
2341 break;
2342 case glslang::EbtDouble:
2343 spvType = builder.makeFloatType(64);
2344 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002345#ifdef AMD_EXTENSIONS
2346 case glslang::EbtFloat16:
2347 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002348 spvType = builder.makeFloatType(16);
2349 break;
2350#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002351 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002352 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2353 // a 32-bit int where non-0 means true.
2354 if (explicitLayout != glslang::ElpNone)
2355 spvType = builder.makeUintType(32);
2356 else
2357 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002358 break;
2359 case glslang::EbtInt:
2360 spvType = builder.makeIntType(32);
2361 break;
2362 case glslang::EbtUint:
2363 spvType = builder.makeUintType(32);
2364 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002365 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002366 spvType = builder.makeIntType(64);
2367 break;
2368 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002369 spvType = builder.makeUintType(64);
2370 break;
Rex Xucabbb782017-03-24 13:41:14 +08002371#ifdef AMD_EXTENSIONS
2372 case glslang::EbtInt16:
2373 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2374 spvType = builder.makeIntType(16);
2375 break;
2376 case glslang::EbtUint16:
2377 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2378 spvType = builder.makeUintType(16);
2379 break;
2380#endif
John Kessenich426394d2015-07-23 10:22:48 -06002381 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002382 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002383 spvType = builder.makeUintType(32);
2384 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002385 case glslang::EbtSampler:
2386 {
2387 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002388 if (sampler.sampler) {
2389 // pure sampler
2390 spvType = builder.makeSamplerType();
2391 } else {
2392 // an image is present, make its type
2393 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2394 sampler.image ? 2 : 1, TranslateImageFormat(type));
2395 if (sampler.combined) {
2396 // already has both image and sampler, make the combined type
2397 spvType = builder.makeSampledImageType(spvType);
2398 }
John Kessenich55e7d112015-11-15 21:33:39 -07002399 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002400 }
John Kessenich140f3df2015-06-26 16:58:36 -06002401 break;
2402 case glslang::EbtStruct:
2403 case glslang::EbtBlock:
2404 {
2405 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002406 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002407
2408 // Try to share structs for different layouts, but not yet for other
2409 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002410 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002411 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002412 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002413 break;
2414
2415 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002416 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002417 memberRemapper[glslangMembers].resize(glslangMembers->size());
2418 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002419 }
2420 break;
2421 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002422 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002423 break;
2424 }
2425
2426 if (type.isMatrix())
2427 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2428 else {
2429 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2430 if (type.getVectorSize() > 1)
2431 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2432 }
2433
2434 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002435 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2436
John Kessenichc9a80832015-09-12 12:17:44 -06002437 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002438 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002439 // We need to decorate array strides for types needing explicit layout, except blocks.
2440 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002441 // Use a dummy glslang type for querying internal strides of
2442 // arrays of arrays, but using just a one-dimensional array.
2443 glslang::TType simpleArrayType(type, 0); // deference type of the array
2444 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2445 simpleArrayType.getArraySizes().dereference();
2446
2447 // Will compute the higher-order strides here, rather than making a whole
2448 // pile of types and doing repetitive recursion on their contents.
2449 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2450 }
John Kessenichf8842e52016-01-04 19:22:56 -07002451
2452 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002453 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002454 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002455 if (stride > 0)
2456 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002457 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002458 }
2459 } else {
2460 // single-dimensional array, and don't yet have stride
2461
John Kessenichf8842e52016-01-04 19:22:56 -07002462 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002463 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2464 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002465 }
John Kessenich31ed4832015-09-09 17:51:38 -06002466
John Kessenichc9a80832015-09-12 12:17:44 -06002467 // Do the outer dimension, which might not be known for a runtime-sized array
2468 if (type.isRuntimeSizedArray()) {
2469 spvType = builder.makeRuntimeArray(spvType);
2470 } else {
2471 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002472 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002473 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002474 if (stride > 0)
2475 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002476 }
2477
2478 return spvType;
2479}
2480
John Kessenich0e737842017-03-24 18:38:16 -06002481// TODO: this functionality should exist at a higher level, in creating the AST
2482//
2483// Identify interface members that don't have their required extension turned on.
2484//
2485bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2486{
2487 auto& extensions = glslangIntermediate->getRequestedExtensions();
2488
Rex Xubcf291a2017-03-29 23:01:36 +08002489 if (member.getFieldName() == "gl_ViewportMask" &&
2490 extensions.find("GL_NV_viewport_array2") == extensions.end())
2491 return true;
2492 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2493 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2494 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002495 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2496 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2497 return true;
2498 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2499 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2500 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002501 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2502 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2503 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002504
2505 return false;
2506};
2507
John Kessenich6090df02016-06-30 21:18:02 -06002508// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2509// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2510// Mutually recursive with convertGlslangToSpvType().
2511spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2512 const glslang::TTypeList* glslangMembers,
2513 glslang::TLayoutPacking explicitLayout,
2514 const glslang::TQualifier& qualifier)
2515{
2516 // Create a vector of struct types for SPIR-V to consume
2517 std::vector<spv::Id> spvMembers;
2518 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 -06002519 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2520 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2521 if (glslangMember.hiddenMember()) {
2522 ++memberDelta;
2523 if (type.getBasicType() == glslang::EbtBlock)
2524 memberRemapper[glslangMembers][i] = -1;
2525 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002526 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002527 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002528 if (filterMember(glslangMember))
2529 continue;
2530 }
John Kessenich6090df02016-06-30 21:18:02 -06002531 // modify just this child's view of the qualifier
2532 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2533 InheritQualifiers(memberQualifier, qualifier);
2534
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002535 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002536 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002537 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002538
2539 // recurse
2540 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2541 }
2542 }
2543
2544 // Make the SPIR-V type
2545 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002546 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002547 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2548
2549 // Decorate it
2550 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2551
2552 return spvType;
2553}
2554
2555void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2556 const glslang::TTypeList* glslangMembers,
2557 glslang::TLayoutPacking explicitLayout,
2558 const glslang::TQualifier& qualifier,
2559 spv::Id spvType)
2560{
2561 // Name and decorate the non-hidden members
2562 int offset = -1;
2563 int locationOffset = 0; // for use within the members of this struct
2564 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2565 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2566 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002567 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002568 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002569 if (filterMember(glslangMember))
2570 continue;
2571 }
John Kessenich6090df02016-06-30 21:18:02 -06002572
2573 // modify just this child's view of the qualifier
2574 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2575 InheritQualifiers(memberQualifier, qualifier);
2576
2577 // using -1 above to indicate a hidden member
2578 if (member >= 0) {
2579 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2580 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2581 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2582 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002583 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2584 type.getQualifier().storage == glslang::EvqVaryingOut) {
2585 if (type.getBasicType() == glslang::EbtBlock ||
2586 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002587 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2588 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2589 }
2590 }
2591 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2592
Rex Xu286ca432017-07-27 14:33:16 +08002593 if (type.getBasicType() == glslang::EbtBlock &&
2594 qualifier.storage == glslang::EvqBuffer) {
2595 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002596 std::vector<spv::Decoration> memory;
2597 TranslateMemoryDecoration(memberQualifier, memory);
2598 for (unsigned int i = 0; i < memory.size(); ++i)
2599 addMemberDecoration(spvType, member, memory[i]);
2600 }
2601
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002602 // Location assignment was already completed correctly by the front end,
2603 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002604 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002605 // ill-specified and decisions have been made to not allow this.
2606 if (! type.isArray() && memberQualifier.hasLocation())
2607 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002608
John Kessenich2f47bc92016-06-30 21:47:35 -06002609 if (qualifier.hasLocation()) // track for upcoming inheritance
2610 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2611
John Kessenich6090df02016-06-30 21:18:02 -06002612 // component, XFB, others
2613 if (glslangMember.getQualifier().hasComponent())
2614 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2615 if (glslangMember.getQualifier().hasXfbOffset())
2616 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2617 else if (explicitLayout != glslang::ElpNone) {
2618 // figure out what to do with offset, which is accumulating
2619 int nextOffset;
2620 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2621 if (offset >= 0)
2622 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2623 offset = nextOffset;
2624 }
2625
2626 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2627 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2628
2629 // built-in variable decorations
2630 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002631 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002632 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002633
2634#ifdef NV_EXTENSIONS
2635 if (builtIn == spv::BuiltInLayer) {
2636 // SPV_NV_viewport_array2 extension
2637 if (glslangMember.getQualifier().layoutViewportRelative){
2638 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2639 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2640 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2641 }
2642 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2643 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2644 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2645 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2646 }
2647 }
chaocdf3956c2017-02-14 14:52:34 -08002648 if (glslangMember.getQualifier().layoutPassthrough) {
2649 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2650 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2651 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2652 }
chaoc771d89f2017-01-13 01:10:53 -08002653#endif
John Kessenich6090df02016-06-30 21:18:02 -06002654 }
2655 }
2656
2657 // Decorate the structure
2658 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002659 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002660 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2661 builder.addCapability(spv::CapabilityGeometryStreams);
2662 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2663 }
John Kessenich6090df02016-06-30 21:18:02 -06002664}
2665
John Kessenich6c292d32016-02-15 20:58:50 -07002666// Turn the expression forming the array size into an id.
2667// This is not quite trivial, because of specialization constants.
2668// Sometimes, a raw constant is turned into an Id, and sometimes
2669// a specialization constant expression is.
2670spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2671{
2672 // First, see if this is sized with a node, meaning a specialization constant:
2673 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2674 if (specNode != nullptr) {
2675 builder.clearAccessChain();
2676 specNode->traverse(this);
2677 return accessChainLoad(specNode->getAsTyped()->getType());
2678 }
qining25262b32016-05-06 17:25:16 -04002679
John Kessenich6c292d32016-02-15 20:58:50 -07002680 // Otherwise, need a compile-time (front end) size, get it:
2681 int size = arraySizes.getDimSize(dim);
2682 assert(size > 0);
2683 return builder.makeUintConstant(size);
2684}
2685
John Kessenich103bef92016-02-08 21:38:15 -07002686// Wrap the builder's accessChainLoad to:
2687// - localize handling of RelaxedPrecision
2688// - use the SPIR-V inferred type instead of another conversion of the glslang type
2689// (avoids unnecessary work and possible type punning for structures)
2690// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002691spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2692{
John Kessenich103bef92016-02-08 21:38:15 -07002693 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2694 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2695
2696 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002697 if (type.getBasicType() == glslang::EbtBool) {
2698 if (builder.isScalarType(nominalTypeId)) {
2699 // Conversion for bool
2700 spv::Id boolType = builder.makeBoolType();
2701 if (nominalTypeId != boolType)
2702 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2703 } else if (builder.isVectorType(nominalTypeId)) {
2704 // Conversion for bvec
2705 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2706 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2707 if (nominalTypeId != bvecType)
2708 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2709 }
2710 }
John Kessenich103bef92016-02-08 21:38:15 -07002711
2712 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002713}
2714
Rex Xu27253232016-02-23 17:51:09 +08002715// Wrap the builder's accessChainStore to:
2716// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002717//
2718// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002719void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2720{
2721 // Need to convert to abstract types when necessary
2722 if (type.getBasicType() == glslang::EbtBool) {
2723 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2724
2725 if (builder.isScalarType(nominalTypeId)) {
2726 // Conversion for bool
2727 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002728 if (nominalTypeId != boolType) {
2729 // keep these outside arguments, for determinant order-of-evaluation
2730 spv::Id one = builder.makeUintConstant(1);
2731 spv::Id zero = builder.makeUintConstant(0);
2732 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2733 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002734 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002735 } else if (builder.isVectorType(nominalTypeId)) {
2736 // Conversion for bvec
2737 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2738 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002739 if (nominalTypeId != bvecType) {
2740 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002741 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2742 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2743 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002744 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002745 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2746 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002747 }
2748 }
2749
2750 builder.accessChainStore(rvalue);
2751}
2752
John Kessenich4bf71552016-09-02 11:20:21 -06002753// For storing when types match at the glslang level, but not might match at the
2754// SPIR-V level.
2755//
2756// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002757// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002758// as in a member-decorated way.
2759//
2760// NOTE: This function can handle any store request; if it's not special it
2761// simplifies to a simple OpStore.
2762//
2763// Implicitly uses the existing builder.accessChain as the storage target.
2764void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2765{
John Kessenichb3e24e42016-09-11 12:33:43 -06002766 // we only do the complex path here if it's an aggregate
2767 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002768 accessChainStore(type, rValue);
2769 return;
2770 }
2771
John Kessenichb3e24e42016-09-11 12:33:43 -06002772 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002773 spv::Id rType = builder.getTypeId(rValue);
2774 spv::Id lValue = builder.accessChainGetLValue();
2775 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2776 if (lType == rType) {
2777 accessChainStore(type, rValue);
2778 return;
2779 }
2780
John Kessenichb3e24e42016-09-11 12:33:43 -06002781 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002782 // where the two types were the same type in GLSL. This requires member
2783 // by member copy, recursively.
2784
John Kessenichb3e24e42016-09-11 12:33:43 -06002785 // If an array, copy element by element.
2786 if (type.isArray()) {
2787 glslang::TType glslangElementType(type, 0);
2788 spv::Id elementRType = builder.getContainedTypeId(rType);
2789 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2790 // get the source member
2791 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002792
John Kessenichb3e24e42016-09-11 12:33:43 -06002793 // set up the target storage
2794 builder.clearAccessChain();
2795 builder.setAccessChainLValue(lValue);
2796 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002797
John Kessenichb3e24e42016-09-11 12:33:43 -06002798 // store the member
2799 multiTypeStore(glslangElementType, elementRValue);
2800 }
2801 } else {
2802 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002803
John Kessenichb3e24e42016-09-11 12:33:43 -06002804 // loop over structure members
2805 const glslang::TTypeList& members = *type.getStruct();
2806 for (int m = 0; m < (int)members.size(); ++m) {
2807 const glslang::TType& glslangMemberType = *members[m].type;
2808
2809 // get the source member
2810 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2811 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2812
2813 // set up the target storage
2814 builder.clearAccessChain();
2815 builder.setAccessChainLValue(lValue);
2816 builder.accessChainPush(builder.makeIntConstant(m));
2817
2818 // store the member
2819 multiTypeStore(glslangMemberType, memberRValue);
2820 }
John Kessenich4bf71552016-09-02 11:20:21 -06002821 }
2822}
2823
John Kessenichf85e8062015-12-19 13:57:10 -07002824// Decide whether or not this type should be
2825// decorated with offsets and strides, and if so
2826// whether std140 or std430 rules should be applied.
2827glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002828{
John Kessenichf85e8062015-12-19 13:57:10 -07002829 // has to be a block
2830 if (type.getBasicType() != glslang::EbtBlock)
2831 return glslang::ElpNone;
2832
2833 // has to be a uniform or buffer block
2834 if (type.getQualifier().storage != glslang::EvqUniform &&
2835 type.getQualifier().storage != glslang::EvqBuffer)
2836 return glslang::ElpNone;
2837
2838 // return the layout to use
2839 switch (type.getQualifier().layoutPacking) {
2840 case glslang::ElpStd140:
2841 case glslang::ElpStd430:
2842 return type.getQualifier().layoutPacking;
2843 default:
2844 return glslang::ElpNone;
2845 }
John Kessenich31ed4832015-09-09 17:51:38 -06002846}
2847
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002848// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002849int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002850{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002851 int size;
John Kessenich49987892015-12-29 17:11:44 -07002852 int stride;
2853 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002854
2855 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002856}
2857
John Kessenich49987892015-12-29 17:11:44 -07002858// 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 -07002859// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002860int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002861{
John Kessenich49987892015-12-29 17:11:44 -07002862 glslang::TType elementType;
2863 elementType.shallowCopy(matrixType);
2864 elementType.clearArraySizes();
2865
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002866 int size;
John Kessenich49987892015-12-29 17:11:44 -07002867 int stride;
2868 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2869
2870 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002871}
2872
John Kessenich5e4b1242015-08-06 22:53:06 -06002873// Given a member type of a struct, realign the current offset for it, and compute
2874// the next (not yet aligned) offset for the next member, which will get aligned
2875// on the next call.
2876// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2877// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2878// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002879void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002880 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002881{
2882 // this will get a positive value when deemed necessary
2883 nextOffset = -1;
2884
John Kessenich5e4b1242015-08-06 22:53:06 -06002885 // override anything in currentOffset with user-set offset
2886 if (memberType.getQualifier().hasOffset())
2887 currentOffset = memberType.getQualifier().layoutOffset;
2888
2889 // It could be that current linker usage in glslang updated all the layoutOffset,
2890 // in which case the following code does not matter. But, that's not quite right
2891 // once cross-compilation unit GLSL validation is done, as the original user
2892 // settings are needed in layoutOffset, and then the following will come into play.
2893
John Kessenichf85e8062015-12-19 13:57:10 -07002894 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002895 if (! memberType.getQualifier().hasOffset())
2896 currentOffset = -1;
2897
2898 return;
2899 }
2900
John Kessenichf85e8062015-12-19 13:57:10 -07002901 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002902 if (currentOffset < 0)
2903 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002904
John Kessenich5e4b1242015-08-06 22:53:06 -06002905 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2906 // but possibly not yet correctly aligned.
2907
2908 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002909 int dummyStride;
2910 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002911
2912 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002913 // TODO: make this consistent in early phases of code:
2914 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2915 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2916 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002917 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002918 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002919 int dummySize;
2920 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2921 if (componentAlignment <= 4)
2922 memberAlignment = componentAlignment;
2923 }
2924
2925 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002926 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002927
2928 // Bump up to vec4 if there is a bad straddle
2929 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2930 glslang::RoundToPow2(currentOffset, 16);
2931
John Kessenich5e4b1242015-08-06 22:53:06 -06002932 nextOffset = currentOffset + memberSize;
2933}
2934
David Netoa901ffe2016-06-08 14:11:40 +01002935void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002936{
David Netoa901ffe2016-06-08 14:11:40 +01002937 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2938 switch (glslangBuiltIn)
2939 {
2940 case glslang::EbvClipDistance:
2941 case glslang::EbvCullDistance:
2942 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002943#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08002944 case glslang::EbvViewportMaskNV:
2945 case glslang::EbvSecondaryPositionNV:
2946 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002947 case glslang::EbvPositionPerViewNV:
2948 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002949#endif
David Netoa901ffe2016-06-08 14:11:40 +01002950 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2951 // Alternately, we could just call this for any glslang built-in, since the
2952 // capability already guards against duplicates.
2953 TranslateBuiltInDecoration(glslangBuiltIn, false);
2954 break;
2955 default:
2956 // Capabilities were already generated when the struct was declared.
2957 break;
2958 }
John Kessenichebb50532016-05-16 19:22:05 -06002959}
2960
John Kessenich6fccb3c2016-09-19 16:01:41 -06002961bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002962{
John Kessenicheee9d532016-09-19 18:09:30 -06002963 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002964}
2965
John Kessenichd41993d2017-09-10 15:21:05 -06002966// Does parameter need a place to keep writes, separate from the original?
John Kessenich6a14f782017-12-04 02:48:10 -07002967// Assumes called after originalParam(), which filters out block/buffer/opaque-based
2968// qualifiers such that we should have only in/out/inout/constreadonly here.
John Kessenichd41993d2017-09-10 15:21:05 -06002969bool TGlslangToSpvTraverser::writableParam(glslang::TStorageQualifier qualifier)
2970{
John Kessenich6a14f782017-12-04 02:48:10 -07002971 assert(qualifier == glslang::EvqIn ||
2972 qualifier == glslang::EvqOut ||
2973 qualifier == glslang::EvqInOut ||
2974 qualifier == glslang::EvqConstReadOnly);
John Kessenichd41993d2017-09-10 15:21:05 -06002975 return qualifier != glslang::EvqConstReadOnly;
2976}
2977
2978// Is parameter pass-by-original?
2979bool TGlslangToSpvTraverser::originalParam(glslang::TStorageQualifier qualifier, const glslang::TType& paramType,
2980 bool implicitThisParam)
2981{
2982 if (implicitThisParam) // implicit this
2983 return true;
2984 if (glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich6a14f782017-12-04 02:48:10 -07002985 return paramType.getBasicType() == glslang::EbtBlock;
John Kessenichd41993d2017-09-10 15:21:05 -06002986 return paramType.containsOpaque() || // sampler, etc.
2987 (paramType.getBasicType() == glslang::EbtBlock && qualifier == glslang::EvqBuffer); // SSBO
2988}
2989
John Kessenich140f3df2015-06-26 16:58:36 -06002990// Make all the functions, skeletally, without actually visiting their bodies.
2991void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2992{
John Kessenichfad62972017-07-18 02:35:46 -06002993 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
2994 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
2995 if (paramPrecision != spv::NoPrecision)
2996 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06002997 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06002998 };
2999
John Kessenich140f3df2015-06-26 16:58:36 -06003000 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3001 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06003002 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06003003 continue;
3004
3005 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06003006 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06003007 //
qining25262b32016-05-06 17:25:16 -04003008 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06003009 // function. What it is an address of varies:
3010 //
John Kessenich4bf71552016-09-02 11:20:21 -06003011 // - "in" parameters not marked as "const" can be written to without modifying the calling
3012 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06003013 //
3014 // - "const in" parameters can just be the r-value, as no writes need occur.
3015 //
John Kessenich4bf71552016-09-02 11:20:21 -06003016 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
3017 // 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 -06003018
3019 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06003020 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06003021 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
3022
John Kessenichfad62972017-07-18 02:35:46 -06003023 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
3024 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06003025
John Kessenichfad62972017-07-18 02:35:46 -06003026 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06003027 for (int p = 0; p < (int)parameters.size(); ++p) {
3028 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
3029 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003030 if (originalParam(paramType.getQualifier().storage, paramType, implicitThis && p == 0))
John Kessenicha5c5fb62017-05-05 05:09:58 -06003031 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
John Kessenichd41993d2017-09-10 15:21:05 -06003032 else if (writableParam(paramType.getQualifier().storage))
John Kessenich140f3df2015-06-26 16:58:36 -06003033 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3034 else
John Kessenich4bf71552016-09-02 11:20:21 -06003035 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003036 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003037 paramTypes.push_back(typeId);
3038 }
3039
3040 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003041 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3042 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003043 glslFunction->getName().c_str(), paramTypes,
3044 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003045 if (implicitThis)
3046 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003047
3048 // Track function to emit/call later
3049 functionMap[glslFunction->getName().c_str()] = function;
3050
3051 // Set the parameter id's
3052 for (int p = 0; p < (int)parameters.size(); ++p) {
3053 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3054 // give a name too
3055 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3056 }
3057 }
3058}
3059
3060// Process all the initializers, while skipping the functions and link objects
3061void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3062{
3063 builder.setBuildPoint(shaderEntry->getLastBlock());
3064 for (int i = 0; i < (int)initializers.size(); ++i) {
3065 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3066 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3067
3068 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003069 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003070 initializer->traverse(this);
3071 }
3072 }
3073}
3074
3075// Process all the functions, while skipping initializers.
3076void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3077{
3078 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3079 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003080 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003081 node->traverse(this);
3082 }
3083}
3084
3085void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3086{
qining25262b32016-05-06 17:25:16 -04003087 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003088 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003089 currentFunction = functionMap[node->getName().c_str()];
3090 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003091 builder.setBuildPoint(functionBlock);
3092}
3093
Rex Xu04db3f52015-09-16 11:44:02 +08003094void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003095{
Rex Xufc618912015-09-09 16:42:49 +08003096 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003097
3098 glslang::TSampler sampler = {};
3099 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003100 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003101 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3102 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3103 }
3104
John Kessenich140f3df2015-06-26 16:58:36 -06003105 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3106 builder.clearAccessChain();
3107 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003108
3109 // Special case l-value operands
3110 bool lvalue = false;
3111 switch (node.getOp()) {
3112 case glslang::EOpImageAtomicAdd:
3113 case glslang::EOpImageAtomicMin:
3114 case glslang::EOpImageAtomicMax:
3115 case glslang::EOpImageAtomicAnd:
3116 case glslang::EOpImageAtomicOr:
3117 case glslang::EOpImageAtomicXor:
3118 case glslang::EOpImageAtomicExchange:
3119 case glslang::EOpImageAtomicCompSwap:
3120 if (i == 0)
3121 lvalue = true;
3122 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003123 case glslang::EOpSparseImageLoad:
3124 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3125 lvalue = true;
3126 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003127 case glslang::EOpSparseTexture:
3128 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3129 lvalue = true;
3130 break;
3131 case glslang::EOpSparseTextureClamp:
3132 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3133 lvalue = true;
3134 break;
3135 case glslang::EOpSparseTextureLod:
3136 case glslang::EOpSparseTextureOffset:
3137 if (i == 3)
3138 lvalue = true;
3139 break;
3140 case glslang::EOpSparseTextureFetch:
3141 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3142 lvalue = true;
3143 break;
3144 case glslang::EOpSparseTextureFetchOffset:
3145 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3146 lvalue = true;
3147 break;
3148 case glslang::EOpSparseTextureLodOffset:
3149 case glslang::EOpSparseTextureGrad:
3150 case glslang::EOpSparseTextureOffsetClamp:
3151 if (i == 4)
3152 lvalue = true;
3153 break;
3154 case glslang::EOpSparseTextureGradOffset:
3155 case glslang::EOpSparseTextureGradClamp:
3156 if (i == 5)
3157 lvalue = true;
3158 break;
3159 case glslang::EOpSparseTextureGradOffsetClamp:
3160 if (i == 6)
3161 lvalue = true;
3162 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003163 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003164 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3165 lvalue = true;
3166 break;
3167 case glslang::EOpSparseTextureGatherOffset:
3168 case glslang::EOpSparseTextureGatherOffsets:
3169 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3170 lvalue = true;
3171 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003172#ifdef AMD_EXTENSIONS
3173 case glslang::EOpSparseTextureGatherLod:
3174 if (i == 3)
3175 lvalue = true;
3176 break;
3177 case glslang::EOpSparseTextureGatherLodOffset:
3178 case glslang::EOpSparseTextureGatherLodOffsets:
3179 if (i == 4)
3180 lvalue = true;
3181 break;
Rex Xu129799a2017-07-05 17:23:28 +08003182 case glslang::EOpSparseImageLoadLod:
3183 if (i == 3)
3184 lvalue = true;
3185 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003186#endif
Rex Xufc618912015-09-09 16:42:49 +08003187 default:
3188 break;
3189 }
3190
Rex Xu6b86d492015-09-16 17:48:22 +08003191 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003192 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003193 else
John Kessenich32cfd492016-02-02 12:37:46 -07003194 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003195 }
3196}
3197
John Kessenichfc51d282015-08-19 13:34:18 -06003198void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003199{
John Kessenichfc51d282015-08-19 13:34:18 -06003200 builder.clearAccessChain();
3201 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003202 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003203}
John Kessenich140f3df2015-06-26 16:58:36 -06003204
John Kessenichfc51d282015-08-19 13:34:18 -06003205spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3206{
John Kesseniche485c7a2017-05-31 18:50:53 -06003207 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003208 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003209
3210 builder.setLine(node->getLoc().line);
3211
John Kessenich8c8505c2016-07-26 12:50:38 -06003212 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003213
John Kessenichfc51d282015-08-19 13:34:18 -06003214 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003215 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3216 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3217 std::vector<spv::Id> arguments;
3218 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003219 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003220 else
3221 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003222 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003223
3224 spv::Builder::TextureParameters params = { };
3225 params.sampler = arguments[0];
3226
Rex Xu04db3f52015-09-16 11:44:02 +08003227 glslang::TCrackedTextureOp cracked;
3228 node->crackTexture(sampler, cracked);
3229
amhagan05506bb2017-06-13 16:53:02 -04003230 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003231
John Kessenichfc51d282015-08-19 13:34:18 -06003232 // Check for queries
3233 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003234 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3235 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003236 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003237
John Kessenichfc51d282015-08-19 13:34:18 -06003238 switch (node->getOp()) {
3239 case glslang::EOpImageQuerySize:
3240 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003241 if (arguments.size() > 1) {
3242 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003243 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003244 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003245 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003246 case glslang::EOpImageQuerySamples:
3247 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003248 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003249 case glslang::EOpTextureQueryLod:
3250 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003251 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003252 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003253 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003254 case glslang::EOpSparseTexelsResident:
3255 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003256 default:
3257 assert(0);
3258 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003259 }
John Kessenich140f3df2015-06-26 16:58:36 -06003260 }
3261
Rex Xufc618912015-09-09 16:42:49 +08003262 // Check for image functions other than queries
3263 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003264 std::vector<spv::Id> operands;
3265 auto opIt = arguments.begin();
3266 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003267
3268 // Handle subpass operations
3269 // TODO: GLSL should change to have the "MS" only on the type rather than the
3270 // built-in function.
3271 if (cracked.subpass) {
3272 // add on the (0,0) coordinate
3273 spv::Id zero = builder.makeIntConstant(0);
3274 std::vector<spv::Id> comps;
3275 comps.push_back(zero);
3276 comps.push_back(zero);
3277 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3278 if (sampler.ms) {
3279 operands.push_back(spv::ImageOperandsSampleMask);
3280 operands.push_back(*(opIt++));
3281 }
John Kessenichfe4e5722017-10-19 02:07:30 -06003282 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3283 builder.setPrecision(result, precision);
3284 return result;
John Kessenich6c292d32016-02-15 20:58:50 -07003285 }
3286
John Kessenich56bab042015-09-16 10:54:31 -06003287 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003288#ifdef AMD_EXTENSIONS
3289 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3290#else
John Kessenich56bab042015-09-16 10:54:31 -06003291 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003292#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003293 if (sampler.ms) {
3294 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003295 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003296#ifdef AMD_EXTENSIONS
3297 } else if (cracked.lod) {
3298 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3299 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3300
3301 operands.push_back(spv::ImageOperandsLodMask);
3302 operands.push_back(*opIt);
3303#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003304 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003305 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3306 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenichfe4e5722017-10-19 02:07:30 -06003307
3308 spv::Id result = builder.createOp(spv::OpImageRead, resultType(), operands);
3309 builder.setPrecision(result, precision);
3310 return result;
Rex Xu129799a2017-07-05 17:23:28 +08003311#ifdef AMD_EXTENSIONS
3312 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3313#else
John Kessenich56bab042015-09-16 10:54:31 -06003314 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003315#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003316 if (sampler.ms) {
3317 operands.push_back(*(opIt + 1));
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(*(opIt + 1));
3326 operands.push_back(spv::ImageOperandsLodMask);
3327 operands.push_back(*opIt);
3328#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003329 } else
3330 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003331 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003332 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3333 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003334 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003335#ifdef AMD_EXTENSIONS
3336 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3337#else
Rex Xu5eafa472016-02-19 22:24:03 +08003338 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003339#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003340 builder.addCapability(spv::CapabilitySparseResidency);
3341 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3342 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3343
3344 if (sampler.ms) {
3345 operands.push_back(spv::ImageOperandsSampleMask);
3346 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003347#ifdef AMD_EXTENSIONS
3348 } else if (cracked.lod) {
3349 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3350 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3351
3352 operands.push_back(spv::ImageOperandsLodMask);
3353 operands.push_back(*opIt++);
3354#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003355 }
3356
3357 // Create the return type that was a special structure
3358 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003359 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003360 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3361 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3362
3363 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3364
3365 // Decode the return type
3366 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3367 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003368 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003369 // Process image atomic operations
3370
3371 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3372 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003373 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003374
John Kessenich8c8505c2016-07-26 12:50:38 -06003375 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003376 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003377
3378 std::vector<spv::Id> operands;
3379 operands.push_back(pointer);
3380 for (; opIt != arguments.end(); ++opIt)
3381 operands.push_back(*opIt);
3382
John Kessenich8c8505c2016-07-26 12:50:38 -06003383 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003384 }
3385 }
3386
amhagan05506bb2017-06-13 16:53:02 -04003387#ifdef AMD_EXTENSIONS
3388 // Check for fragment mask functions other than queries
3389 if (cracked.fragMask) {
3390 assert(sampler.ms);
3391
3392 auto opIt = arguments.begin();
3393 std::vector<spv::Id> operands;
3394
3395 // Extract the image if necessary
3396 if (builder.isSampledImage(params.sampler))
3397 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3398
3399 operands.push_back(params.sampler);
3400 ++opIt;
3401
3402 if (sampler.isSubpass()) {
3403 // add on the (0,0) coordinate
3404 spv::Id zero = builder.makeIntConstant(0);
3405 std::vector<spv::Id> comps;
3406 comps.push_back(zero);
3407 comps.push_back(zero);
3408 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3409 }
3410
3411 for (; opIt != arguments.end(); ++opIt)
3412 operands.push_back(*opIt);
3413
3414 spv::Op fragMaskOp = spv::OpNop;
3415 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3416 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3417 else if (node->getOp() == glslang::EOpFragmentFetch)
3418 fragMaskOp = spv::OpFragmentFetchAMD;
3419
3420 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3421 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3422 return builder.createOp(fragMaskOp, resultType(), operands);
3423 }
3424#endif
3425
Rex Xufc618912015-09-09 16:42:49 +08003426 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003427 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003428 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3429
John Kessenichfc51d282015-08-19 13:34:18 -06003430 // check for bias argument
3431 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003432#ifdef AMD_EXTENSIONS
3433 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3434#else
Rex Xu71519fe2015-11-11 15:35:47 +08003435 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003436#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003437 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003438#ifdef AMD_EXTENSIONS
3439 if (cracked.gather)
3440 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3441#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003442 if (cracked.offset)
3443 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003444#ifdef AMD_EXTENSIONS
3445 else if (cracked.offsets)
3446 ++nonBiasArgCount;
3447#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003448 if (cracked.grad)
3449 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003450 if (cracked.lodClamp)
3451 ++nonBiasArgCount;
3452 if (sparse)
3453 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003454
3455 if ((int)arguments.size() > nonBiasArgCount)
3456 bias = true;
3457 }
3458
John Kessenicha5c33d62016-06-02 23:45:21 -06003459 // See if the sampler param should really be just the SPV image part
3460 if (cracked.fetch) {
3461 // a fetch needs to have the image extracted first
3462 if (builder.isSampledImage(params.sampler))
3463 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3464 }
3465
Rex Xu225e0fc2016-11-17 17:47:59 +08003466#ifdef AMD_EXTENSIONS
3467 if (cracked.gather) {
3468 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3469 if (bias || cracked.lod ||
3470 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3471 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003472 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003473 }
3474 }
3475#endif
3476
John Kessenichfc51d282015-08-19 13:34:18 -06003477 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003478
John Kessenichfc51d282015-08-19 13:34:18 -06003479 params.coords = arguments[1];
3480 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003481 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003482
3483 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003484 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003485 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003486 ++extraArgs;
3487 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003488 params.Dref = arguments[2];
3489 ++extraArgs;
3490 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003491 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003492 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003493 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003494 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003495 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003496 dRefComp = builder.getNumComponents(params.coords) - 1;
3497 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003498 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3499 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003500
3501 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003502 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003503 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003504 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003505 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3506 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3507 noImplicitLod = true;
3508 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003509
3510 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003511 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003512 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003513 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003514 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003515
3516 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003517 if (cracked.grad) {
3518 params.gradX = arguments[2 + extraArgs];
3519 params.gradY = arguments[3 + extraArgs];
3520 extraArgs += 2;
3521 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003522
3523 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003524 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003525 params.offset = arguments[2 + extraArgs];
3526 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003527 } else if (cracked.offsets) {
3528 params.offsets = arguments[2 + extraArgs];
3529 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003530 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003531
3532 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003533 if (cracked.lodClamp) {
3534 params.lodClamp = arguments[2 + extraArgs];
3535 ++extraArgs;
3536 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003537
3538 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003539 if (sparse) {
3540 params.texelOut = arguments[2 + extraArgs];
3541 ++extraArgs;
3542 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003543
John Kessenich76d4dfc2016-06-16 12:43:23 -06003544 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003545 if (cracked.gather && ! sampler.shadow) {
3546 // default component is 0, if missing, otherwise an argument
3547 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003548 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003549 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003550 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003551 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003552 }
3553
3554 // bias
3555 if (bias) {
3556 params.bias = arguments[2 + extraArgs];
3557 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003558 }
John Kessenichfc51d282015-08-19 13:34:18 -06003559
John Kessenich65336482016-06-16 14:06:26 -06003560 // projective component (might not to move)
3561 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3562 // are divided by the last component of P."
3563 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3564 // unused components will appear after all used components."
3565 if (cracked.proj) {
3566 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3567 int projTargetComp;
3568 switch (sampler.dim) {
3569 case glslang::Esd1D: projTargetComp = 1; break;
3570 case glslang::Esd2D: projTargetComp = 2; break;
3571 case glslang::EsdRect: projTargetComp = 2; break;
3572 default: projTargetComp = projSourceComp; break;
3573 }
3574 // copy the projective coordinate if we have to
3575 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003576 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003577 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3578 projSourceComp);
3579 params.coords = builder.createCompositeInsert(projComp, params.coords,
3580 builder.getTypeId(params.coords), projTargetComp);
3581 }
3582 }
3583
John Kessenich8c8505c2016-07-26 12:50:38 -06003584 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003585}
3586
3587spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3588{
3589 // Grab the function's pointer from the previously created function
3590 spv::Function* function = functionMap[node->getName().c_str()];
3591 if (! function)
3592 return 0;
3593
3594 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3595 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3596
3597 // See comments in makeFunctions() for details about the semantics for parameter passing.
3598 //
3599 // These imply we need a four step process:
3600 // 1. Evaluate the arguments
3601 // 2. Allocate and make copies of in, out, and inout arguments
3602 // 3. Make the call
3603 // 4. Copy back the results
3604
3605 // 1. Evaluate the arguments
3606 std::vector<spv::Builder::AccessChain> lValues;
3607 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003608 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003609 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003610 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003611 // build l-value
3612 builder.clearAccessChain();
3613 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003614 argTypes.push_back(&paramType);
John Kessenichd41993d2017-09-10 15:21:05 -06003615 // keep outputs and pass-by-originals as l-values, evaluate others as r-values
John Kessenich6a14f782017-12-04 02:48:10 -07003616 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0) ||
3617 writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003618 // save l-value
3619 lValues.push_back(builder.getAccessChain());
3620 } else {
3621 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003622 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003623 }
3624 }
3625
3626 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3627 // copy the original into that space.
3628 //
3629 // Also, build up the list of actual arguments to pass in for the call
3630 int lValueCount = 0;
3631 int rValueCount = 0;
3632 std::vector<spv::Id> spvArgs;
3633 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003634 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003635 spv::Id arg;
John Kessenichd41993d2017-09-10 15:21:05 -06003636 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0)) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003637 builder.setAccessChain(lValues[lValueCount]);
3638 arg = builder.accessChainGetLValue();
3639 ++lValueCount;
John Kessenichd41993d2017-09-10 15:21:05 -06003640 } else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003641 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003642 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3643 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3644 // need to copy the input into output space
3645 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003646 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003647 builder.clearAccessChain();
3648 builder.setAccessChainLValue(arg);
3649 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003650 }
3651 ++lValueCount;
3652 } else {
3653 arg = rValues[rValueCount];
3654 ++rValueCount;
3655 }
3656 spvArgs.push_back(arg);
3657 }
3658
3659 // 3. Make the call.
3660 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003661 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003662
3663 // 4. Copy back out an "out" arguments.
3664 lValueCount = 0;
3665 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003666 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenichd41993d2017-09-10 15:21:05 -06003667 if (originalParam(qualifiers[a], paramType, function->hasImplicitThis() && a == 0))
3668 ++lValueCount;
3669 else if (writableParam(qualifiers[a])) {
John Kessenich140f3df2015-06-26 16:58:36 -06003670 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3671 spv::Id copy = builder.createLoad(spvArgs[a]);
3672 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003673 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003674 }
3675 ++lValueCount;
3676 }
3677 }
3678
3679 return result;
3680}
3681
3682// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003683spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3684 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003685 spv::Id typeId, spv::Id left, spv::Id right,
3686 glslang::TBasicType typeProxy, bool reduceComparison)
3687{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003688#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003689 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003690 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3691#else
Rex Xucabbb782017-03-24 13:41:14 +08003692 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003693 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003694#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003695 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003696
3697 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003698 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003699 bool comparison = false;
3700
3701 switch (op) {
3702 case glslang::EOpAdd:
3703 case glslang::EOpAddAssign:
3704 if (isFloat)
3705 binOp = spv::OpFAdd;
3706 else
3707 binOp = spv::OpIAdd;
3708 break;
3709 case glslang::EOpSub:
3710 case glslang::EOpSubAssign:
3711 if (isFloat)
3712 binOp = spv::OpFSub;
3713 else
3714 binOp = spv::OpISub;
3715 break;
3716 case glslang::EOpMul:
3717 case glslang::EOpMulAssign:
3718 if (isFloat)
3719 binOp = spv::OpFMul;
3720 else
3721 binOp = spv::OpIMul;
3722 break;
3723 case glslang::EOpVectorTimesScalar:
3724 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003725 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003726 if (builder.isVector(right))
3727 std::swap(left, right);
3728 assert(builder.isScalar(right));
3729 needMatchingVectors = false;
3730 binOp = spv::OpVectorTimesScalar;
3731 } else
3732 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003733 break;
3734 case glslang::EOpVectorTimesMatrix:
3735 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003736 binOp = spv::OpVectorTimesMatrix;
3737 break;
3738 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003739 binOp = spv::OpMatrixTimesVector;
3740 break;
3741 case glslang::EOpMatrixTimesScalar:
3742 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003743 binOp = spv::OpMatrixTimesScalar;
3744 break;
3745 case glslang::EOpMatrixTimesMatrix:
3746 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003747 binOp = spv::OpMatrixTimesMatrix;
3748 break;
3749 case glslang::EOpOuterProduct:
3750 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003751 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003752 break;
3753
3754 case glslang::EOpDiv:
3755 case glslang::EOpDivAssign:
3756 if (isFloat)
3757 binOp = spv::OpFDiv;
3758 else if (isUnsigned)
3759 binOp = spv::OpUDiv;
3760 else
3761 binOp = spv::OpSDiv;
3762 break;
3763 case glslang::EOpMod:
3764 case glslang::EOpModAssign:
3765 if (isFloat)
3766 binOp = spv::OpFMod;
3767 else if (isUnsigned)
3768 binOp = spv::OpUMod;
3769 else
3770 binOp = spv::OpSMod;
3771 break;
3772 case glslang::EOpRightShift:
3773 case glslang::EOpRightShiftAssign:
3774 if (isUnsigned)
3775 binOp = spv::OpShiftRightLogical;
3776 else
3777 binOp = spv::OpShiftRightArithmetic;
3778 break;
3779 case glslang::EOpLeftShift:
3780 case glslang::EOpLeftShiftAssign:
3781 binOp = spv::OpShiftLeftLogical;
3782 break;
3783 case glslang::EOpAnd:
3784 case glslang::EOpAndAssign:
3785 binOp = spv::OpBitwiseAnd;
3786 break;
3787 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003788 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003789 binOp = spv::OpLogicalAnd;
3790 break;
3791 case glslang::EOpInclusiveOr:
3792 case glslang::EOpInclusiveOrAssign:
3793 binOp = spv::OpBitwiseOr;
3794 break;
3795 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003796 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003797 binOp = spv::OpLogicalOr;
3798 break;
3799 case glslang::EOpExclusiveOr:
3800 case glslang::EOpExclusiveOrAssign:
3801 binOp = spv::OpBitwiseXor;
3802 break;
3803 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003804 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003805 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003806 break;
3807
3808 case glslang::EOpLessThan:
3809 case glslang::EOpGreaterThan:
3810 case glslang::EOpLessThanEqual:
3811 case glslang::EOpGreaterThanEqual:
3812 case glslang::EOpEqual:
3813 case glslang::EOpNotEqual:
3814 case glslang::EOpVectorEqual:
3815 case glslang::EOpVectorNotEqual:
3816 comparison = true;
3817 break;
3818 default:
3819 break;
3820 }
3821
John Kessenich7c1aa102015-10-15 13:29:11 -06003822 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003823 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003824 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003825 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003826 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003827
3828 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003829 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003830 builder.promoteScalar(precision, left, right);
3831
qining25262b32016-05-06 17:25:16 -04003832 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3833 addDecoration(result, noContraction);
3834 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003835 }
3836
3837 if (! comparison)
3838 return 0;
3839
John Kessenich7c1aa102015-10-15 13:29:11 -06003840 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003841
John Kessenich4583b612016-08-07 19:14:22 -06003842 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3843 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003844 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003845
3846 switch (op) {
3847 case glslang::EOpLessThan:
3848 if (isFloat)
3849 binOp = spv::OpFOrdLessThan;
3850 else if (isUnsigned)
3851 binOp = spv::OpULessThan;
3852 else
3853 binOp = spv::OpSLessThan;
3854 break;
3855 case glslang::EOpGreaterThan:
3856 if (isFloat)
3857 binOp = spv::OpFOrdGreaterThan;
3858 else if (isUnsigned)
3859 binOp = spv::OpUGreaterThan;
3860 else
3861 binOp = spv::OpSGreaterThan;
3862 break;
3863 case glslang::EOpLessThanEqual:
3864 if (isFloat)
3865 binOp = spv::OpFOrdLessThanEqual;
3866 else if (isUnsigned)
3867 binOp = spv::OpULessThanEqual;
3868 else
3869 binOp = spv::OpSLessThanEqual;
3870 break;
3871 case glslang::EOpGreaterThanEqual:
3872 if (isFloat)
3873 binOp = spv::OpFOrdGreaterThanEqual;
3874 else if (isUnsigned)
3875 binOp = spv::OpUGreaterThanEqual;
3876 else
3877 binOp = spv::OpSGreaterThanEqual;
3878 break;
3879 case glslang::EOpEqual:
3880 case glslang::EOpVectorEqual:
3881 if (isFloat)
3882 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003883 else if (isBool)
3884 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003885 else
3886 binOp = spv::OpIEqual;
3887 break;
3888 case glslang::EOpNotEqual:
3889 case glslang::EOpVectorNotEqual:
3890 if (isFloat)
3891 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003892 else if (isBool)
3893 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003894 else
3895 binOp = spv::OpINotEqual;
3896 break;
3897 default:
3898 break;
3899 }
3900
qining25262b32016-05-06 17:25:16 -04003901 if (binOp != spv::OpNop) {
3902 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3903 addDecoration(result, noContraction);
3904 return builder.setPrecision(result, precision);
3905 }
John Kessenich140f3df2015-06-26 16:58:36 -06003906
3907 return 0;
3908}
3909
John Kessenich04bb8a02015-12-12 12:28:14 -07003910//
3911// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3912// These can be any of:
3913//
3914// matrix * scalar
3915// scalar * matrix
3916// matrix * matrix linear algebraic
3917// matrix * vector
3918// vector * matrix
3919// matrix * matrix componentwise
3920// matrix op matrix op in {+, -, /}
3921// matrix op scalar op in {+, -, /}
3922// scalar op matrix op in {+, -, /}
3923//
qining25262b32016-05-06 17:25:16 -04003924spv::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 -07003925{
3926 bool firstClass = true;
3927
3928 // First, handle first-class matrix operations (* and matrix/scalar)
3929 switch (op) {
3930 case spv::OpFDiv:
3931 if (builder.isMatrix(left) && builder.isScalar(right)) {
3932 // turn matrix / scalar into a multiply...
3933 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3934 op = spv::OpMatrixTimesScalar;
3935 } else
3936 firstClass = false;
3937 break;
3938 case spv::OpMatrixTimesScalar:
3939 if (builder.isMatrix(right))
3940 std::swap(left, right);
3941 assert(builder.isScalar(right));
3942 break;
3943 case spv::OpVectorTimesMatrix:
3944 assert(builder.isVector(left));
3945 assert(builder.isMatrix(right));
3946 break;
3947 case spv::OpMatrixTimesVector:
3948 assert(builder.isMatrix(left));
3949 assert(builder.isVector(right));
3950 break;
3951 case spv::OpMatrixTimesMatrix:
3952 assert(builder.isMatrix(left));
3953 assert(builder.isMatrix(right));
3954 break;
3955 default:
3956 firstClass = false;
3957 break;
3958 }
3959
qining25262b32016-05-06 17:25:16 -04003960 if (firstClass) {
3961 spv::Id result = builder.createBinOp(op, typeId, left, right);
3962 addDecoration(result, noContraction);
3963 return builder.setPrecision(result, precision);
3964 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003965
LoopDawg592860c2016-06-09 08:57:35 -06003966 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003967 // The result type of all of them is the same type as the (a) matrix operand.
3968 // The algorithm is to:
3969 // - break the matrix(es) into vectors
3970 // - smear any scalar to a vector
3971 // - do vector operations
3972 // - make a matrix out the vector results
3973 switch (op) {
3974 case spv::OpFAdd:
3975 case spv::OpFSub:
3976 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003977 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003978 case spv::OpFMul:
3979 {
3980 // one time set up...
3981 bool leftMat = builder.isMatrix(left);
3982 bool rightMat = builder.isMatrix(right);
3983 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3984 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3985 spv::Id scalarType = builder.getScalarTypeId(typeId);
3986 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3987 std::vector<spv::Id> results;
3988 spv::Id smearVec = spv::NoResult;
3989 if (builder.isScalar(left))
3990 smearVec = builder.smearScalar(precision, left, vecType);
3991 else if (builder.isScalar(right))
3992 smearVec = builder.smearScalar(precision, right, vecType);
3993
3994 // do each vector op
3995 for (unsigned int c = 0; c < numCols; ++c) {
3996 std::vector<unsigned int> indexes;
3997 indexes.push_back(c);
3998 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3999 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04004000 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
4001 addDecoration(result, noContraction);
4002 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07004003 }
4004
4005 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004006 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07004007 }
4008 default:
4009 assert(0);
4010 return spv::NoResult;
4011 }
4012}
4013
qining25262b32016-05-06 17:25:16 -04004014spv::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 -06004015{
4016 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004017 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004018 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004019#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004020 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004021 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4022#else
Rex Xucabbb782017-03-24 13:41:14 +08004023 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08004024 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004025#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004026
4027 switch (op) {
4028 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07004029 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06004030 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07004031 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04004032 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004033 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004034 unaryOp = spv::OpSNegate;
4035 break;
4036
4037 case glslang::EOpLogicalNot:
4038 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004039 unaryOp = spv::OpLogicalNot;
4040 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004041 case glslang::EOpBitwiseNot:
4042 unaryOp = spv::OpNot;
4043 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004044
John Kessenich140f3df2015-06-26 16:58:36 -06004045 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004046 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004047 break;
4048 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004049 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004050 break;
4051 case glslang::EOpTranspose:
4052 unaryOp = spv::OpTranspose;
4053 break;
4054
4055 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004056 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004057 break;
4058 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004059 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004060 break;
4061 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004062 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004063 break;
4064 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004065 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004066 break;
4067 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004068 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004069 break;
4070 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004071 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004072 break;
4073 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004074 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004075 break;
4076 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004077 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004078 break;
4079
4080 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004081 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004082 break;
4083 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004084 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004085 break;
4086 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004087 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004088 break;
4089 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004090 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004091 break;
4092 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004093 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004094 break;
4095 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004096 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004097 break;
4098
4099 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004100 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004101 break;
4102 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004103 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004104 break;
4105
4106 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004107 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004108 break;
4109 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004110 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004111 break;
4112 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004113 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004114 break;
4115 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004116 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004117 break;
4118 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004119 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004120 break;
4121 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004122 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004123 break;
4124
4125 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004126 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004127 break;
4128 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004129 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004130 break;
4131 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004132 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004133 break;
4134 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004135 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004136 break;
4137 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004138 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004139 break;
4140 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004141 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004142 break;
4143
4144 case glslang::EOpIsNan:
4145 unaryOp = spv::OpIsNan;
4146 break;
4147 case glslang::EOpIsInf:
4148 unaryOp = spv::OpIsInf;
4149 break;
LoopDawg592860c2016-06-09 08:57:35 -06004150 case glslang::EOpIsFinite:
4151 unaryOp = spv::OpIsFinite;
4152 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004153
Rex Xucbc426e2015-12-15 16:03:10 +08004154 case glslang::EOpFloatBitsToInt:
4155 case glslang::EOpFloatBitsToUint:
4156 case glslang::EOpIntBitsToFloat:
4157 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004158 case glslang::EOpDoubleBitsToInt64:
4159 case glslang::EOpDoubleBitsToUint64:
4160 case glslang::EOpInt64BitsToDouble:
4161 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004162#ifdef AMD_EXTENSIONS
4163 case glslang::EOpFloat16BitsToInt16:
4164 case glslang::EOpFloat16BitsToUint16:
4165 case glslang::EOpInt16BitsToFloat16:
4166 case glslang::EOpUint16BitsToFloat16:
4167#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004168 unaryOp = spv::OpBitcast;
4169 break;
4170
John Kessenich140f3df2015-06-26 16:58:36 -06004171 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004172 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004173 break;
4174 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004175 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004176 break;
4177 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004178 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004179 break;
4180 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004181 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004182 break;
4183 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004184 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004185 break;
4186 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004187 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004188 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004189 case glslang::EOpPackSnorm4x8:
4190 libCall = spv::GLSLstd450PackSnorm4x8;
4191 break;
4192 case glslang::EOpUnpackSnorm4x8:
4193 libCall = spv::GLSLstd450UnpackSnorm4x8;
4194 break;
4195 case glslang::EOpPackUnorm4x8:
4196 libCall = spv::GLSLstd450PackUnorm4x8;
4197 break;
4198 case glslang::EOpUnpackUnorm4x8:
4199 libCall = spv::GLSLstd450UnpackUnorm4x8;
4200 break;
4201 case glslang::EOpPackDouble2x32:
4202 libCall = spv::GLSLstd450PackDouble2x32;
4203 break;
4204 case glslang::EOpUnpackDouble2x32:
4205 libCall = spv::GLSLstd450UnpackDouble2x32;
4206 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004207
Rex Xu8ff43de2016-04-22 16:51:45 +08004208 case glslang::EOpPackInt2x32:
4209 case glslang::EOpUnpackInt2x32:
4210 case glslang::EOpPackUint2x32:
4211 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004212 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004213 break;
4214
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004215#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004216 case glslang::EOpPackInt2x16:
4217 case glslang::EOpUnpackInt2x16:
4218 case glslang::EOpPackUint2x16:
4219 case glslang::EOpUnpackUint2x16:
4220 case glslang::EOpPackInt4x16:
4221 case glslang::EOpUnpackInt4x16:
4222 case glslang::EOpPackUint4x16:
4223 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004224 case glslang::EOpPackFloat2x16:
4225 case glslang::EOpUnpackFloat2x16:
4226 unaryOp = spv::OpBitcast;
4227 break;
4228#endif
4229
John Kessenich140f3df2015-06-26 16:58:36 -06004230 case glslang::EOpDPdx:
4231 unaryOp = spv::OpDPdx;
4232 break;
4233 case glslang::EOpDPdy:
4234 unaryOp = spv::OpDPdy;
4235 break;
4236 case glslang::EOpFwidth:
4237 unaryOp = spv::OpFwidth;
4238 break;
4239 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004240 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004241 unaryOp = spv::OpDPdxFine;
4242 break;
4243 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004244 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004245 unaryOp = spv::OpDPdyFine;
4246 break;
4247 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004248 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004249 unaryOp = spv::OpFwidthFine;
4250 break;
4251 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004252 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004253 unaryOp = spv::OpDPdxCoarse;
4254 break;
4255 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004256 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004257 unaryOp = spv::OpDPdyCoarse;
4258 break;
4259 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004260 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004261 unaryOp = spv::OpFwidthCoarse;
4262 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004263 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004264 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004265 libCall = spv::GLSLstd450InterpolateAtCentroid;
4266 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004267 case glslang::EOpAny:
4268 unaryOp = spv::OpAny;
4269 break;
4270 case glslang::EOpAll:
4271 unaryOp = spv::OpAll;
4272 break;
4273
4274 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004275 if (isFloat)
4276 libCall = spv::GLSLstd450FAbs;
4277 else
4278 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004279 break;
4280 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004281 if (isFloat)
4282 libCall = spv::GLSLstd450FSign;
4283 else
4284 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004285 break;
4286
John Kessenichfc51d282015-08-19 13:34:18 -06004287 case glslang::EOpAtomicCounterIncrement:
4288 case glslang::EOpAtomicCounterDecrement:
4289 case glslang::EOpAtomicCounter:
4290 {
4291 // Handle all of the atomics in one place, in createAtomicOperation()
4292 std::vector<spv::Id> operands;
4293 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004294 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004295 }
4296
John Kessenichfc51d282015-08-19 13:34:18 -06004297 case glslang::EOpBitFieldReverse:
4298 unaryOp = spv::OpBitReverse;
4299 break;
4300 case glslang::EOpBitCount:
4301 unaryOp = spv::OpBitCount;
4302 break;
4303 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004304 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004305 break;
4306 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004307 if (isUnsigned)
4308 libCall = spv::GLSLstd450FindUMsb;
4309 else
4310 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004311 break;
4312
Rex Xu574ab042016-04-14 16:53:07 +08004313 case glslang::EOpBallot:
4314 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004315 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004316 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004317 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004318#ifdef AMD_EXTENSIONS
4319 case glslang::EOpMinInvocations:
4320 case glslang::EOpMaxInvocations:
4321 case glslang::EOpAddInvocations:
4322 case glslang::EOpMinInvocationsNonUniform:
4323 case glslang::EOpMaxInvocationsNonUniform:
4324 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004325 case glslang::EOpMinInvocationsInclusiveScan:
4326 case glslang::EOpMaxInvocationsInclusiveScan:
4327 case glslang::EOpAddInvocationsInclusiveScan:
4328 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4329 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4330 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4331 case glslang::EOpMinInvocationsExclusiveScan:
4332 case glslang::EOpMaxInvocationsExclusiveScan:
4333 case glslang::EOpAddInvocationsExclusiveScan:
4334 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4335 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4336 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004337#endif
Rex Xu51596642016-09-21 18:56:12 +08004338 {
4339 std::vector<spv::Id> operands;
4340 operands.push_back(operand);
4341 return createInvocationsOperation(op, typeId, operands, typeProxy);
4342 }
Rex Xu9d93a232016-05-05 12:30:44 +08004343
4344#ifdef AMD_EXTENSIONS
4345 case glslang::EOpMbcnt:
4346 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4347 libCall = spv::MbcntAMD;
4348 break;
4349
4350 case glslang::EOpCubeFaceIndex:
4351 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4352 libCall = spv::CubeFaceIndexAMD;
4353 break;
4354
4355 case glslang::EOpCubeFaceCoord:
4356 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4357 libCall = spv::CubeFaceCoordAMD;
4358 break;
4359#endif
Rex Xu338b1852016-05-05 20:38:33 +08004360
John Kessenich140f3df2015-06-26 16:58:36 -06004361 default:
4362 return 0;
4363 }
4364
4365 spv::Id id;
4366 if (libCall >= 0) {
4367 std::vector<spv::Id> args;
4368 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004369 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004370 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004371 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004372 }
John Kessenich140f3df2015-06-26 16:58:36 -06004373
qining25262b32016-05-06 17:25:16 -04004374 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004375 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004376}
4377
John Kessenich7a53f762016-01-20 11:19:27 -07004378// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004379spv::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 -07004380{
4381 // Handle unary operations vector by vector.
4382 // The result type is the same type as the original type.
4383 // The algorithm is to:
4384 // - break the matrix into vectors
4385 // - apply the operation to each vector
4386 // - make a matrix out the vector results
4387
4388 // get the types sorted out
4389 int numCols = builder.getNumColumns(operand);
4390 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004391 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4392 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004393 std::vector<spv::Id> results;
4394
4395 // do each vector op
4396 for (int c = 0; c < numCols; ++c) {
4397 std::vector<unsigned int> indexes;
4398 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004399 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4400 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4401 addDecoration(destVec, noContraction);
4402 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004403 }
4404
4405 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004406 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004407}
4408
Rex Xu73e3ce72016-04-27 18:48:17 +08004409spv::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 -06004410{
4411 spv::Op convOp = spv::OpNop;
4412 spv::Id zero = 0;
4413 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004414 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004415
4416 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4417
4418 switch (op) {
4419 case glslang::EOpConvIntToBool:
4420 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004421 case glslang::EOpConvInt64ToBool:
4422 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004423#ifdef AMD_EXTENSIONS
4424 case glslang::EOpConvInt16ToBool:
4425 case glslang::EOpConvUint16ToBool:
4426#endif
4427 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4428 zero = builder.makeUint64Constant(0);
4429#ifdef AMD_EXTENSIONS
4430 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4431 zero = builder.makeUint16Constant(0);
4432#endif
4433 else
4434 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004435 zero = makeSmearedConstant(zero, vectorSize);
4436 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4437
4438 case glslang::EOpConvFloatToBool:
4439 zero = builder.makeFloatConstant(0.0F);
4440 zero = makeSmearedConstant(zero, vectorSize);
4441 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4442
4443 case glslang::EOpConvDoubleToBool:
4444 zero = builder.makeDoubleConstant(0.0);
4445 zero = makeSmearedConstant(zero, vectorSize);
4446 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4447
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004448#ifdef AMD_EXTENSIONS
4449 case glslang::EOpConvFloat16ToBool:
4450 zero = builder.makeFloat16Constant(0.0F);
4451 zero = makeSmearedConstant(zero, vectorSize);
4452 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4453#endif
4454
John Kessenich140f3df2015-06-26 16:58:36 -06004455 case glslang::EOpConvBoolToFloat:
4456 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004457 zero = builder.makeFloatConstant(0.0F);
4458 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004459 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004460
John Kessenich140f3df2015-06-26 16:58:36 -06004461 case glslang::EOpConvBoolToDouble:
4462 convOp = spv::OpSelect;
4463 zero = builder.makeDoubleConstant(0.0);
4464 one = builder.makeDoubleConstant(1.0);
4465 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004466
4467#ifdef AMD_EXTENSIONS
4468 case glslang::EOpConvBoolToFloat16:
4469 convOp = spv::OpSelect;
4470 zero = builder.makeFloat16Constant(0.0F);
4471 one = builder.makeFloat16Constant(1.0F);
4472 break;
4473#endif
4474
John Kessenich140f3df2015-06-26 16:58:36 -06004475 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004476 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004477#ifdef AMD_EXTENSIONS
4478 case glslang::EOpConvBoolToInt16:
4479#endif
4480 if (op == glslang::EOpConvBoolToInt64)
4481 zero = builder.makeInt64Constant(0);
4482#ifdef AMD_EXTENSIONS
4483 else if (op == glslang::EOpConvBoolToInt16)
4484 zero = builder.makeInt16Constant(0);
4485#endif
4486 else
4487 zero = builder.makeIntConstant(0);
4488
4489 if (op == glslang::EOpConvBoolToInt64)
4490 one = builder.makeInt64Constant(1);
4491#ifdef AMD_EXTENSIONS
4492 else if (op == glslang::EOpConvBoolToInt16)
4493 one = builder.makeInt16Constant(1);
4494#endif
4495 else
4496 one = builder.makeIntConstant(1);
4497
John Kessenich140f3df2015-06-26 16:58:36 -06004498 convOp = spv::OpSelect;
4499 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004500
John Kessenich140f3df2015-06-26 16:58:36 -06004501 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004502 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004503#ifdef AMD_EXTENSIONS
4504 case glslang::EOpConvBoolToUint16:
4505#endif
4506 if (op == glslang::EOpConvBoolToUint64)
4507 zero = builder.makeUint64Constant(0);
4508#ifdef AMD_EXTENSIONS
4509 else if (op == glslang::EOpConvBoolToUint16)
4510 zero = builder.makeUint16Constant(0);
4511#endif
4512 else
4513 zero = builder.makeUintConstant(0);
4514
4515 if (op == glslang::EOpConvBoolToUint64)
4516 one = builder.makeUint64Constant(1);
4517#ifdef AMD_EXTENSIONS
4518 else if (op == glslang::EOpConvBoolToUint16)
4519 one = builder.makeUint16Constant(1);
4520#endif
4521 else
4522 one = builder.makeUintConstant(1);
4523
John Kessenich140f3df2015-06-26 16:58:36 -06004524 convOp = spv::OpSelect;
4525 break;
4526
4527 case glslang::EOpConvIntToFloat:
4528 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004529 case glslang::EOpConvInt64ToFloat:
4530 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004531#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004532 case glslang::EOpConvInt16ToFloat:
4533 case glslang::EOpConvInt16ToDouble:
4534 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004535 case glslang::EOpConvIntToFloat16:
4536 case glslang::EOpConvInt64ToFloat16:
4537#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004538 convOp = spv::OpConvertSToF;
4539 break;
4540
4541 case glslang::EOpConvUintToFloat:
4542 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004543 case glslang::EOpConvUint64ToFloat:
4544 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004545#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004546 case glslang::EOpConvUint16ToFloat:
4547 case glslang::EOpConvUint16ToDouble:
4548 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004549 case glslang::EOpConvUintToFloat16:
4550 case glslang::EOpConvUint64ToFloat16:
4551#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004552 convOp = spv::OpConvertUToF;
4553 break;
4554
4555 case glslang::EOpConvDoubleToFloat:
4556 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004557#ifdef AMD_EXTENSIONS
4558 case glslang::EOpConvDoubleToFloat16:
4559 case glslang::EOpConvFloat16ToDouble:
4560 case glslang::EOpConvFloatToFloat16:
4561 case glslang::EOpConvFloat16ToFloat:
4562#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004563 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004564 if (builder.isMatrixType(destType))
4565 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004566 break;
4567
4568 case glslang::EOpConvFloatToInt:
4569 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004570 case glslang::EOpConvFloatToInt64:
4571 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004572#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004573 case glslang::EOpConvFloatToInt16:
4574 case glslang::EOpConvDoubleToInt16:
4575 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004576 case glslang::EOpConvFloat16ToInt:
4577 case glslang::EOpConvFloat16ToInt64:
4578#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004579 convOp = spv::OpConvertFToS;
4580 break;
4581
4582 case glslang::EOpConvUintToInt:
4583 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004584 case glslang::EOpConvUint64ToInt64:
4585 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004586#ifdef AMD_EXTENSIONS
4587 case glslang::EOpConvUint16ToInt16:
4588 case glslang::EOpConvInt16ToUint16:
4589#endif
qininge24aa5e2016-04-07 15:40:27 -04004590 if (builder.isInSpecConstCodeGenMode()) {
4591 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004592 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4593 zero = builder.makeUint64Constant(0);
4594#ifdef AMD_EXTENSIONS
4595 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4596 zero = builder.makeUint16Constant(0);
4597#endif
4598 else
4599 zero = builder.makeUintConstant(0);
4600
qining189b2032016-04-12 23:16:20 -04004601 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004602 // Use OpIAdd, instead of OpBitcast to do the conversion when
4603 // generating for OpSpecConstantOp instruction.
4604 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4605 }
4606 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004607 convOp = spv::OpBitcast;
4608 break;
4609
4610 case glslang::EOpConvFloatToUint:
4611 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004612 case glslang::EOpConvFloatToUint64:
4613 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004614#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004615 case glslang::EOpConvFloatToUint16:
4616 case glslang::EOpConvDoubleToUint16:
4617 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004618 case glslang::EOpConvFloat16ToUint:
4619 case glslang::EOpConvFloat16ToUint64:
4620#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004621 convOp = spv::OpConvertFToU;
4622 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004623
4624 case glslang::EOpConvIntToInt64:
4625 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004626#ifdef AMD_EXTENSIONS
4627 case glslang::EOpConvIntToInt16:
4628 case glslang::EOpConvInt16ToInt:
4629 case glslang::EOpConvInt64ToInt16:
4630 case glslang::EOpConvInt16ToInt64:
4631#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004632 convOp = spv::OpSConvert;
4633 break;
4634
4635 case glslang::EOpConvUintToUint64:
4636 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004637#ifdef AMD_EXTENSIONS
4638 case glslang::EOpConvUintToUint16:
4639 case glslang::EOpConvUint16ToUint:
4640 case glslang::EOpConvUint64ToUint16:
4641 case glslang::EOpConvUint16ToUint64:
4642#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004643 convOp = spv::OpUConvert;
4644 break;
4645
4646 case glslang::EOpConvIntToUint64:
4647 case glslang::EOpConvInt64ToUint:
4648 case glslang::EOpConvUint64ToInt:
4649 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004650#ifdef AMD_EXTENSIONS
4651 case glslang::EOpConvInt16ToUint:
4652 case glslang::EOpConvUintToInt16:
4653 case glslang::EOpConvInt16ToUint64:
4654 case glslang::EOpConvUint64ToInt16:
4655 case glslang::EOpConvUint16ToInt:
4656 case glslang::EOpConvIntToUint16:
4657 case glslang::EOpConvUint16ToInt64:
4658 case glslang::EOpConvInt64ToUint16:
4659#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004660 // OpSConvert/OpUConvert + OpBitCast
4661 switch (op) {
4662 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004663#ifdef AMD_EXTENSIONS
4664 case glslang::EOpConvInt16ToUint64:
4665#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004666 convOp = spv::OpSConvert;
4667 type = builder.makeIntType(64);
4668 break;
4669 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004670#ifdef AMD_EXTENSIONS
4671 case glslang::EOpConvInt16ToUint:
4672#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004673 convOp = spv::OpSConvert;
4674 type = builder.makeIntType(32);
4675 break;
4676 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004677#ifdef AMD_EXTENSIONS
4678 case glslang::EOpConvUint16ToInt:
4679#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004680 convOp = spv::OpUConvert;
4681 type = builder.makeUintType(32);
4682 break;
4683 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004684#ifdef AMD_EXTENSIONS
4685 case glslang::EOpConvUint16ToInt64:
4686#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004687 convOp = spv::OpUConvert;
4688 type = builder.makeUintType(64);
4689 break;
Rex Xucabbb782017-03-24 13:41:14 +08004690#ifdef AMD_EXTENSIONS
4691 case glslang::EOpConvUintToInt16:
4692 case glslang::EOpConvUint64ToInt16:
4693 convOp = spv::OpUConvert;
4694 type = builder.makeUintType(16);
4695 break;
4696 case glslang::EOpConvIntToUint16:
4697 case glslang::EOpConvInt64ToUint16:
4698 convOp = spv::OpSConvert;
4699 type = builder.makeIntType(16);
4700 break;
4701#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004702 default:
4703 assert(0);
4704 break;
4705 }
4706
4707 if (vectorSize > 0)
4708 type = builder.makeVectorType(type, vectorSize);
4709
4710 operand = builder.createUnaryOp(convOp, type, operand);
4711
4712 if (builder.isInSpecConstCodeGenMode()) {
4713 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004714#ifdef AMD_EXTENSIONS
4715 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4716 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4717 zero = builder.makeUint64Constant(0);
4718 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4719 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4720 zero = builder.makeUint16Constant(0);
4721 else
4722 zero = builder.makeUintConstant(0);
4723#else
4724 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4725 zero = builder.makeUint64Constant(0);
4726 else
4727 zero = builder.makeUintConstant(0);
4728#endif
4729
Rex Xu8ff43de2016-04-22 16:51:45 +08004730 zero = makeSmearedConstant(zero, vectorSize);
4731 // Use OpIAdd, instead of OpBitcast to do the conversion when
4732 // generating for OpSpecConstantOp instruction.
4733 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4734 }
4735 // For normal run-time conversion instruction, use OpBitcast.
4736 convOp = spv::OpBitcast;
4737 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004738 default:
4739 break;
4740 }
4741
4742 spv::Id result = 0;
4743 if (convOp == spv::OpNop)
4744 return result;
4745
4746 if (convOp == spv::OpSelect) {
4747 zero = makeSmearedConstant(zero, vectorSize);
4748 one = makeSmearedConstant(one, vectorSize);
4749 result = builder.createTriOp(convOp, destType, operand, one, zero);
4750 } else
4751 result = builder.createUnaryOp(convOp, destType, operand);
4752
John Kessenich32cfd492016-02-02 12:37:46 -07004753 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004754}
4755
4756spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4757{
4758 if (vectorSize == 0)
4759 return constant;
4760
4761 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4762 std::vector<spv::Id> components;
4763 for (int c = 0; c < vectorSize; ++c)
4764 components.push_back(constant);
4765 return builder.makeCompositeConstant(vectorTypeId, components);
4766}
4767
John Kessenich426394d2015-07-23 10:22:48 -06004768// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004769spv::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 -06004770{
4771 spv::Op opCode = spv::OpNop;
4772
4773 switch (op) {
4774 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004775 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004776 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004777 opCode = spv::OpAtomicIAdd;
4778 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004779 case glslang::EOpAtomicCounterSubtract:
4780 opCode = spv::OpAtomicISub;
4781 break;
John Kessenich426394d2015-07-23 10:22:48 -06004782 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004783 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004784 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08004785 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004786 break;
4787 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004788 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004789 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08004790 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004791 break;
4792 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004793 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004794 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004795 opCode = spv::OpAtomicAnd;
4796 break;
4797 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004798 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004799 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004800 opCode = spv::OpAtomicOr;
4801 break;
4802 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004803 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004804 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004805 opCode = spv::OpAtomicXor;
4806 break;
4807 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004808 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004809 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004810 opCode = spv::OpAtomicExchange;
4811 break;
4812 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004813 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004814 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004815 opCode = spv::OpAtomicCompareExchange;
4816 break;
4817 case glslang::EOpAtomicCounterIncrement:
4818 opCode = spv::OpAtomicIIncrement;
4819 break;
4820 case glslang::EOpAtomicCounterDecrement:
4821 opCode = spv::OpAtomicIDecrement;
4822 break;
4823 case glslang::EOpAtomicCounter:
4824 opCode = spv::OpAtomicLoad;
4825 break;
4826 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004827 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004828 break;
4829 }
4830
Rex Xue8fe8b02017-09-26 15:42:56 +08004831 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
4832 builder.addCapability(spv::CapabilityInt64Atomics);
4833
John Kessenich426394d2015-07-23 10:22:48 -06004834 // Sort out the operands
4835 // - mapping from glslang -> SPV
4836 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004837 // - compare-exchange swaps the value and comparator
4838 // - compare-exchange has an extra memory semantics
John Kessenich48d6e792017-10-06 21:21:48 -06004839 // - EOpAtomicCounterDecrement needs a post decrement
John Kessenich426394d2015-07-23 10:22:48 -06004840 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4841 auto opIt = operands.begin(); // walk the glslang operands
4842 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004843 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4844 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4845 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004846 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4847 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004848 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004849 spvAtomicOperands.push_back(*(opIt + 1));
4850 spvAtomicOperands.push_back(*opIt);
4851 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004852 }
John Kessenich426394d2015-07-23 10:22:48 -06004853
John Kessenich3e60a6f2015-09-14 22:45:16 -06004854 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004855 for (; opIt != operands.end(); ++opIt)
4856 spvAtomicOperands.push_back(*opIt);
4857
John Kessenich48d6e792017-10-06 21:21:48 -06004858 spv::Id resultId = builder.createOp(opCode, typeId, spvAtomicOperands);
4859
4860 // GLSL and HLSL atomic-counter decrement return post-decrement value,
4861 // while SPIR-V returns pre-decrement value. Translate between these semantics.
4862 if (op == glslang::EOpAtomicCounterDecrement)
4863 resultId = builder.createBinOp(spv::OpISub, typeId, resultId, builder.makeIntConstant(1));
4864
4865 return resultId;
John Kessenich426394d2015-07-23 10:22:48 -06004866}
4867
John Kessenich91cef522016-05-05 16:45:40 -06004868// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004869spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004870{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004871#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004872 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004873 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004874#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004875
Rex Xu51596642016-09-21 18:56:12 +08004876 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004877 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004878 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4879
chaocf200da82016-12-20 12:44:35 -08004880 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4881 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004882 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4883 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004884 } else if (op == glslang::EOpAnyInvocation ||
4885 op == glslang::EOpAllInvocations ||
4886 op == glslang::EOpAllInvocationsEqual) {
4887 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4888 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004889 } else {
4890 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004891#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004892 if (op == glslang::EOpMinInvocationsNonUniform ||
4893 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004894 op == glslang::EOpAddInvocationsNonUniform ||
4895 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4896 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4897 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4898 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4899 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4900 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004901 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004902#endif
Rex Xu51596642016-09-21 18:56:12 +08004903
4904 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004905#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004906 switch (op) {
4907 case glslang::EOpMinInvocations:
4908 case glslang::EOpMaxInvocations:
4909 case glslang::EOpAddInvocations:
4910 case glslang::EOpMinInvocationsNonUniform:
4911 case glslang::EOpMaxInvocationsNonUniform:
4912 case glslang::EOpAddInvocationsNonUniform:
4913 groupOperation = spv::GroupOperationReduce;
4914 spvGroupOperands.push_back(groupOperation);
4915 break;
4916 case glslang::EOpMinInvocationsInclusiveScan:
4917 case glslang::EOpMaxInvocationsInclusiveScan:
4918 case glslang::EOpAddInvocationsInclusiveScan:
4919 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4920 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4921 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4922 groupOperation = spv::GroupOperationInclusiveScan;
4923 spvGroupOperands.push_back(groupOperation);
4924 break;
4925 case glslang::EOpMinInvocationsExclusiveScan:
4926 case glslang::EOpMaxInvocationsExclusiveScan:
4927 case glslang::EOpAddInvocationsExclusiveScan:
4928 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4929 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4930 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4931 groupOperation = spv::GroupOperationExclusiveScan;
4932 spvGroupOperands.push_back(groupOperation);
4933 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004934 default:
4935 break;
Rex Xu430ef402016-10-14 17:22:23 +08004936 }
Rex Xu9d93a232016-05-05 12:30:44 +08004937#endif
Rex Xu51596642016-09-21 18:56:12 +08004938 }
4939
4940 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4941 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004942
4943 switch (op) {
4944 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004945 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004946 break;
John Kessenich91cef522016-05-05 16:45:40 -06004947 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004948 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004949 break;
John Kessenich91cef522016-05-05 16:45:40 -06004950 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004951 opCode = spv::OpSubgroupAllEqualKHR;
4952 break;
Rex Xu51596642016-09-21 18:56:12 +08004953 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004954 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004955 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004956 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004957 break;
4958 case glslang::EOpReadFirstInvocation:
4959 opCode = spv::OpSubgroupFirstInvocationKHR;
4960 break;
4961 case glslang::EOpBallot:
4962 {
4963 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4964 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4965 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4966 //
4967 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4968 //
4969 spv::Id uintType = builder.makeUintType(32);
4970 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4971 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4972
4973 std::vector<spv::Id> components;
4974 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4975 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4976
4977 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4978 return builder.createUnaryOp(spv::OpBitcast, typeId,
4979 builder.createCompositeConstruct(uvec2Type, components));
4980 }
4981
Rex Xu9d93a232016-05-05 12:30:44 +08004982#ifdef AMD_EXTENSIONS
4983 case glslang::EOpMinInvocations:
4984 case glslang::EOpMaxInvocations:
4985 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004986 case glslang::EOpMinInvocationsInclusiveScan:
4987 case glslang::EOpMaxInvocationsInclusiveScan:
4988 case glslang::EOpAddInvocationsInclusiveScan:
4989 case glslang::EOpMinInvocationsExclusiveScan:
4990 case glslang::EOpMaxInvocationsExclusiveScan:
4991 case glslang::EOpAddInvocationsExclusiveScan:
4992 if (op == glslang::EOpMinInvocations ||
4993 op == glslang::EOpMinInvocationsInclusiveScan ||
4994 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004995 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004996 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004997 else {
4998 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004999 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005000 else
Rex Xu51596642016-09-21 18:56:12 +08005001 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08005002 }
Rex Xu430ef402016-10-14 17:22:23 +08005003 } else if (op == glslang::EOpMaxInvocations ||
5004 op == glslang::EOpMaxInvocationsInclusiveScan ||
5005 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08005006 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005007 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005008 else {
5009 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005010 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005011 else
Rex Xu51596642016-09-21 18:56:12 +08005012 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08005013 }
5014 } else {
5015 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005016 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005017 else
Rex Xu51596642016-09-21 18:56:12 +08005018 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08005019 }
5020
Rex Xu2bbbe062016-08-23 15:41:05 +08005021 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005022 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005023
5024 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005025 case glslang::EOpMinInvocationsNonUniform:
5026 case glslang::EOpMaxInvocationsNonUniform:
5027 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08005028 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
5029 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
5030 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
5031 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
5032 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
5033 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
5034 if (op == glslang::EOpMinInvocationsNonUniform ||
5035 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
5036 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005037 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005038 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005039 else {
5040 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005041 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005042 else
Rex Xu51596642016-09-21 18:56:12 +08005043 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005044 }
5045 }
Rex Xu430ef402016-10-14 17:22:23 +08005046 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5047 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5048 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005049 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005050 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005051 else {
5052 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005053 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005054 else
Rex Xu51596642016-09-21 18:56:12 +08005055 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005056 }
5057 }
5058 else {
5059 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005060 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005061 else
Rex Xu51596642016-09-21 18:56:12 +08005062 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005063 }
5064
Rex Xu2bbbe062016-08-23 15:41:05 +08005065 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005066 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005067
5068 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005069#endif
John Kessenich91cef522016-05-05 16:45:40 -06005070 default:
5071 logger->missingFunctionality("invocation operation");
5072 return spv::NoResult;
5073 }
Rex Xu51596642016-09-21 18:56:12 +08005074
5075 assert(opCode != spv::OpNop);
5076 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005077}
5078
Rex Xu2bbbe062016-08-23 15:41:05 +08005079// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005080spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005081{
Rex Xub7072052016-09-26 15:53:40 +08005082#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005083 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5084 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005085 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005086 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005087 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5088 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5089 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005090#else
5091 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5092 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005093 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5094 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005095#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005096
5097 // Handle group invocation operations scalar by scalar.
5098 // The result type is the same type as the original type.
5099 // The algorithm is to:
5100 // - break the vector into scalars
5101 // - apply the operation to each scalar
5102 // - make a vector out the scalar results
5103
5104 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005105 int numComponents = builder.getNumComponents(operands[0]);
5106 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005107 std::vector<spv::Id> results;
5108
5109 // do each scalar op
5110 for (int comp = 0; comp < numComponents; ++comp) {
5111 std::vector<unsigned int> indexes;
5112 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005113 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005114 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005115 if (op == spv::OpSubgroupReadInvocationKHR) {
5116 spvGroupOperands.push_back(scalar);
5117 spvGroupOperands.push_back(operands[1]);
5118 } else if (op == spv::OpGroupBroadcast) {
5119 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005120 spvGroupOperands.push_back(scalar);
5121 spvGroupOperands.push_back(operands[1]);
5122 } else {
chaocf200da82016-12-20 12:44:35 -08005123 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005124 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005125 spvGroupOperands.push_back(scalar);
5126 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005127
Rex Xub7072052016-09-26 15:53:40 +08005128 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005129 }
5130
5131 // put the pieces together
5132 return builder.createCompositeConstruct(typeId, results);
5133}
Rex Xu2bbbe062016-08-23 15:41:05 +08005134
John Kessenich5e4b1242015-08-06 22:53:06 -06005135spv::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 -06005136{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005137#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005138 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005139 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5140#else
Rex Xucabbb782017-03-24 13:41:14 +08005141 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005142 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005143#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005144
John Kessenich140f3df2015-06-26 16:58:36 -06005145 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005146 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005147 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005148 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005149 spv::Id typeId0 = 0;
5150 if (consumedOperands > 0)
5151 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005152 spv::Id typeId1 = 0;
5153 if (consumedOperands > 1)
5154 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005155 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005156
5157 switch (op) {
5158 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005159 if (isFloat)
5160 libCall = spv::GLSLstd450FMin;
5161 else if (isUnsigned)
5162 libCall = spv::GLSLstd450UMin;
5163 else
5164 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005165 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005166 break;
5167 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005168 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005169 break;
5170 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005171 if (isFloat)
5172 libCall = spv::GLSLstd450FMax;
5173 else if (isUnsigned)
5174 libCall = spv::GLSLstd450UMax;
5175 else
5176 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005177 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005178 break;
5179 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005180 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005181 break;
5182 case glslang::EOpDot:
5183 opCode = spv::OpDot;
5184 break;
5185 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005186 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005187 break;
5188
5189 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005190 if (isFloat)
5191 libCall = spv::GLSLstd450FClamp;
5192 else if (isUnsigned)
5193 libCall = spv::GLSLstd450UClamp;
5194 else
5195 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005196 builder.promoteScalar(precision, operands.front(), operands[1]);
5197 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005198 break;
5199 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005200 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5201 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005202 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005203 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005204 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005205 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005206 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005207 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005208 break;
5209 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005210 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005211 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005212 break;
5213 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005214 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005215 builder.promoteScalar(precision, operands[0], operands[2]);
5216 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005217 break;
5218
5219 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005220 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005221 break;
5222 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005223 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005224 break;
5225 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005226 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005227 break;
5228 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005229 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005230 break;
5231 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005232 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005233 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005234 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005235 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005236 libCall = spv::GLSLstd450InterpolateAtSample;
5237 break;
5238 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005239 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005240 libCall = spv::GLSLstd450InterpolateAtOffset;
5241 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005242 case glslang::EOpAddCarry:
5243 opCode = spv::OpIAddCarry;
5244 typeId = builder.makeStructResultType(typeId0, typeId0);
5245 consumedOperands = 2;
5246 break;
5247 case glslang::EOpSubBorrow:
5248 opCode = spv::OpISubBorrow;
5249 typeId = builder.makeStructResultType(typeId0, typeId0);
5250 consumedOperands = 2;
5251 break;
5252 case glslang::EOpUMulExtended:
5253 opCode = spv::OpUMulExtended;
5254 typeId = builder.makeStructResultType(typeId0, typeId0);
5255 consumedOperands = 2;
5256 break;
5257 case glslang::EOpIMulExtended:
5258 opCode = spv::OpSMulExtended;
5259 typeId = builder.makeStructResultType(typeId0, typeId0);
5260 consumedOperands = 2;
5261 break;
5262 case glslang::EOpBitfieldExtract:
5263 if (isUnsigned)
5264 opCode = spv::OpBitFieldUExtract;
5265 else
5266 opCode = spv::OpBitFieldSExtract;
5267 break;
5268 case glslang::EOpBitfieldInsert:
5269 opCode = spv::OpBitFieldInsert;
5270 break;
5271
5272 case glslang::EOpFma:
5273 libCall = spv::GLSLstd450Fma;
5274 break;
5275 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005276 {
5277 libCall = spv::GLSLstd450FrexpStruct;
5278 assert(builder.isPointerType(typeId1));
5279 typeId1 = builder.getContainedTypeId(typeId1);
5280#ifdef AMD_EXTENSIONS
5281 int width = builder.getScalarTypeWidth(typeId1);
5282#else
5283 int width = 32;
5284#endif
5285 if (builder.getNumComponents(operands[0]) == 1)
5286 frexpIntType = builder.makeIntegerType(width, true);
5287 else
5288 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5289 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5290 consumedOperands = 1;
5291 }
John Kessenich55e7d112015-11-15 21:33:39 -07005292 break;
5293 case glslang::EOpLdexp:
5294 libCall = spv::GLSLstd450Ldexp;
5295 break;
5296
Rex Xu574ab042016-04-14 16:53:07 +08005297 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005298 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005299
Rex Xu9d93a232016-05-05 12:30:44 +08005300#ifdef AMD_EXTENSIONS
5301 case glslang::EOpSwizzleInvocations:
5302 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5303 libCall = spv::SwizzleInvocationsAMD;
5304 break;
5305 case glslang::EOpSwizzleInvocationsMasked:
5306 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5307 libCall = spv::SwizzleInvocationsMaskedAMD;
5308 break;
5309 case glslang::EOpWriteInvocation:
5310 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5311 libCall = spv::WriteInvocationAMD;
5312 break;
5313
5314 case glslang::EOpMin3:
5315 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5316 if (isFloat)
5317 libCall = spv::FMin3AMD;
5318 else {
5319 if (isUnsigned)
5320 libCall = spv::UMin3AMD;
5321 else
5322 libCall = spv::SMin3AMD;
5323 }
5324 break;
5325 case glslang::EOpMax3:
5326 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5327 if (isFloat)
5328 libCall = spv::FMax3AMD;
5329 else {
5330 if (isUnsigned)
5331 libCall = spv::UMax3AMD;
5332 else
5333 libCall = spv::SMax3AMD;
5334 }
5335 break;
5336 case glslang::EOpMid3:
5337 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5338 if (isFloat)
5339 libCall = spv::FMid3AMD;
5340 else {
5341 if (isUnsigned)
5342 libCall = spv::UMid3AMD;
5343 else
5344 libCall = spv::SMid3AMD;
5345 }
5346 break;
5347
5348 case glslang::EOpInterpolateAtVertex:
5349 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5350 libCall = spv::InterpolateAtVertexAMD;
5351 break;
5352#endif
5353
John Kessenich140f3df2015-06-26 16:58:36 -06005354 default:
5355 return 0;
5356 }
5357
5358 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005359 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005360 // Use an extended instruction from the standard library.
5361 // Construct the call arguments, without modifying the original operands vector.
5362 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5363 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005364 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005365 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005366 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005367 case 0:
5368 // should all be handled by visitAggregate and createNoArgOperation
5369 assert(0);
5370 return 0;
5371 case 1:
5372 // should all be handled by createUnaryOperation
5373 assert(0);
5374 return 0;
5375 case 2:
5376 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5377 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005378 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005379 // anything 3 or over doesn't have l-value operands, so all should be consumed
5380 assert(consumedOperands == operands.size());
5381 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005382 break;
5383 }
5384 }
5385
John Kessenich55e7d112015-11-15 21:33:39 -07005386 // Decode the return types that were structures
5387 switch (op) {
5388 case glslang::EOpAddCarry:
5389 case glslang::EOpSubBorrow:
5390 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5391 id = builder.createCompositeExtract(id, typeId0, 0);
5392 break;
5393 case glslang::EOpUMulExtended:
5394 case glslang::EOpIMulExtended:
5395 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5396 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5397 break;
5398 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005399 {
5400 assert(operands.size() == 2);
5401 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5402 // "exp" is floating-point type (from HLSL intrinsic)
5403 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5404 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5405 builder.createStore(member1, operands[1]);
5406 } else
5407 // "exp" is integer type (from GLSL built-in function)
5408 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5409 id = builder.createCompositeExtract(id, typeId0, 0);
5410 }
John Kessenich55e7d112015-11-15 21:33:39 -07005411 break;
5412 default:
5413 break;
5414 }
5415
John Kessenich32cfd492016-02-02 12:37:46 -07005416 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005417}
5418
Rex Xu9d93a232016-05-05 12:30:44 +08005419// Intrinsics with no arguments (or no return value, and no precision).
5420spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005421{
5422 // TODO: get the barrier operands correct
5423
5424 switch (op) {
5425 case glslang::EOpEmitVertex:
5426 builder.createNoResultOp(spv::OpEmitVertex);
5427 return 0;
5428 case glslang::EOpEndPrimitive:
5429 builder.createNoResultOp(spv::OpEndPrimitive);
5430 return 0;
5431 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005432 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005433 return 0;
5434 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005435 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005436 return 0;
5437 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005438 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005439 return 0;
5440 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005441 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005442 return 0;
5443 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005444 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005445 return 0;
5446 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005447 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005448 return 0;
5449 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005450 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005451 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005452 case glslang::EOpAllMemoryBarrierWithGroupSync:
5453 // Control barrier with non-"None" semantic is also a memory barrier.
5454 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5455 return 0;
5456 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5457 // Control barrier with non-"None" semantic is also a memory barrier.
5458 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5459 return 0;
5460 case glslang::EOpWorkgroupMemoryBarrier:
5461 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5462 return 0;
5463 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5464 // Control barrier with non-"None" semantic is also a memory barrier.
5465 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5466 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005467#ifdef AMD_EXTENSIONS
5468 case glslang::EOpTime:
5469 {
5470 std::vector<spv::Id> args; // Dummy arguments
5471 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5472 return builder.setPrecision(id, precision);
5473 }
5474#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005475 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005476 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005477 return 0;
5478 }
5479}
5480
5481spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5482{
John Kessenich2f273362015-07-18 22:34:27 -06005483 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005484 spv::Id id;
5485 if (symbolValues.end() != iter) {
5486 id = iter->second;
5487 return id;
5488 }
5489
5490 // it was not found, create it
5491 id = createSpvVariable(symbol);
5492 symbolValues[symbol->getId()] = id;
5493
Rex Xuc884b4a2016-06-29 15:03:44 +08005494 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005495 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005496 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005497 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005498 if (symbol->getType().getQualifier().hasSpecConstantId())
5499 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005500 if (symbol->getQualifier().hasIndex())
5501 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5502 if (symbol->getQualifier().hasComponent())
5503 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
John Kessenich91e4aa52016-07-07 17:46:42 -06005504 // atomic counters use this:
5505 if (symbol->getQualifier().hasOffset())
5506 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005507 }
5508
scygan2c864272016-05-18 18:09:17 +02005509 if (symbol->getQualifier().hasLocation())
5510 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005511 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005512 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005513 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005514 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005515 }
John Kessenich140f3df2015-06-26 16:58:36 -06005516 if (symbol->getQualifier().hasSet())
5517 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005518 else if (IsDescriptorResource(symbol->getType())) {
5519 // default to 0
5520 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5521 }
John Kessenich140f3df2015-06-26 16:58:36 -06005522 if (symbol->getQualifier().hasBinding())
5523 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005524 if (symbol->getQualifier().hasAttachment())
5525 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005526 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005527 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005528 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005529 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenichedaf5562017-12-15 06:21:46 -07005530 if (symbol->getQualifier().hasXfbBuffer()) {
John Kessenich140f3df2015-06-26 16:58:36 -06005531 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
John Kessenichedaf5562017-12-15 06:21:46 -07005532 unsigned stride = glslangIntermediate->getXfbStride(symbol->getQualifier().layoutXfbBuffer);
5533 if (stride != glslang::TQualifier::layoutXfbStrideEnd)
5534 builder.addDecoration(id, spv::DecorationXfbStride, stride);
5535 }
5536 if (symbol->getQualifier().hasXfbOffset())
5537 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005538 }
5539
Rex Xu1da878f2016-02-21 20:59:01 +08005540 if (symbol->getType().isImage()) {
5541 std::vector<spv::Decoration> memory;
5542 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5543 for (unsigned int i = 0; i < memory.size(); ++i)
5544 addDecoration(id, memory[i]);
5545 }
5546
John Kessenich140f3df2015-06-26 16:58:36 -06005547 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005548 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005549 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005550 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005551
John Kessenichecba76f2017-01-06 00:34:48 -07005552#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005553 if (builtIn == spv::BuiltInSampleMask) {
5554 spv::Decoration decoration;
5555 // GL_NV_sample_mask_override_coverage extension
5556 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005557 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005558 else
5559 decoration = (spv::Decoration)spv::DecorationMax;
5560 addDecoration(id, decoration);
5561 if (decoration != spv::DecorationMax) {
5562 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5563 }
5564 }
chaoc771d89f2017-01-13 01:10:53 -08005565 else if (builtIn == spv::BuiltInLayer) {
5566 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06005567 if (symbol->getQualifier().layoutViewportRelative) {
chaoc771d89f2017-01-13 01:10:53 -08005568 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5569 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5570 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5571 }
John Kessenichb41bff62017-08-11 13:07:17 -06005572 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
chaoc771d89f2017-01-13 01:10:53 -08005573 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5574 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5575 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5576 }
5577 }
5578
chaoc6e5acae2016-12-20 13:28:52 -08005579 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005580 addDecoration(id, spv::DecorationPassthroughNV);
5581 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005582 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5583 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005584#endif
5585
John Kessenich140f3df2015-06-26 16:58:36 -06005586 return id;
5587}
5588
John Kessenich55e7d112015-11-15 21:33:39 -07005589// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005590void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5591{
John Kessenich4016e382016-07-15 11:53:56 -06005592 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005593 builder.addDecoration(id, dec);
5594}
5595
John Kessenich55e7d112015-11-15 21:33:39 -07005596// If 'dec' is valid, add a one-operand decoration to an object
5597void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5598{
John Kessenich4016e382016-07-15 11:53:56 -06005599 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005600 builder.addDecoration(id, dec, value);
5601}
5602
5603// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005604void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5605{
John Kessenich4016e382016-07-15 11:53:56 -06005606 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005607 builder.addMemberDecoration(id, (unsigned)member, dec);
5608}
5609
John Kessenich92187592016-02-01 13:45:25 -07005610// If 'dec' is valid, add a one-operand decoration to a struct member
5611void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5612{
John Kessenich4016e382016-07-15 11:53:56 -06005613 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005614 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5615}
5616
John Kessenich55e7d112015-11-15 21:33:39 -07005617// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005618// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005619//
5620// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5621//
5622// Recursively walk the nodes. The nodes form a tree whose leaves are
5623// regular constants, which themselves are trees that createSpvConstant()
5624// recursively walks. So, this function walks the "top" of the tree:
5625// - emit specialization constant-building instructions for specConstant
5626// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005627spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005628{
John Kessenich7cc0e282016-03-20 00:46:02 -06005629 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005630
qining4f4bb812016-04-03 23:55:17 -04005631 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005632 if (! node.getQualifier().specConstant) {
5633 // hand off to the non-spec-constant path
5634 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5635 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005636 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005637 nextConst, false);
5638 }
5639
5640 // We now know we have a specialization constant to build
5641
John Kessenichd94c0032016-05-30 19:29:40 -06005642 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005643 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5644 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5645 std::vector<spv::Id> dimConstId;
5646 for (int dim = 0; dim < 3; ++dim) {
5647 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5648 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5649 if (specConst)
5650 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5651 }
5652 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5653 }
5654
5655 // An AST node labelled as specialization constant should be a symbol node.
5656 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5657 if (auto* sn = node.getAsSymbolNode()) {
5658 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005659 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5660 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5661 // will set the builder into spec constant op instruction generating mode.
5662 sub_tree->traverse(this);
5663 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005664 } else if (auto* const_union_array = &sn->getConstArray()){
5665 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005666 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5667 builder.addName(id, sn->getName().c_str());
5668 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005669 }
5670 }
qining4f4bb812016-04-03 23:55:17 -04005671
5672 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5673 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005674 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005675 exit(1);
5676 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005677}
5678
John Kessenich140f3df2015-06-26 16:58:36 -06005679// Use 'consts' as the flattened glslang source of scalar constants to recursively
5680// build the aggregate SPIR-V constant.
5681//
5682// If there are not enough elements present in 'consts', 0 will be substituted;
5683// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5684//
qining08408382016-03-21 09:51:37 -04005685spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005686{
5687 // vector of constants for SPIR-V
5688 std::vector<spv::Id> spvConsts;
5689
5690 // Type is used for struct and array constants
5691 spv::Id typeId = convertGlslangToSpvType(glslangType);
5692
5693 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005694 glslang::TType elementType(glslangType, 0);
5695 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005696 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005697 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005698 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005699 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005700 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005701 } else if (glslangType.getStruct()) {
5702 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5703 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005704 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005705 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005706 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5707 bool zero = nextConst >= consts.size();
5708 switch (glslangType.getBasicType()) {
5709 case glslang::EbtInt:
5710 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5711 break;
5712 case glslang::EbtUint:
5713 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5714 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005715 case glslang::EbtInt64:
5716 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5717 break;
5718 case glslang::EbtUint64:
5719 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5720 break;
Rex Xucabbb782017-03-24 13:41:14 +08005721#ifdef AMD_EXTENSIONS
5722 case glslang::EbtInt16:
5723 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5724 break;
5725 case glslang::EbtUint16:
5726 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5727 break;
5728#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005729 case glslang::EbtFloat:
5730 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5731 break;
5732 case glslang::EbtDouble:
5733 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5734 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005735#ifdef AMD_EXTENSIONS
5736 case glslang::EbtFloat16:
5737 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5738 break;
5739#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005740 case glslang::EbtBool:
5741 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5742 break;
5743 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005744 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005745 break;
5746 }
5747 ++nextConst;
5748 }
5749 } else {
5750 // we have a non-aggregate (scalar) constant
5751 bool zero = nextConst >= consts.size();
5752 spv::Id scalar = 0;
5753 switch (glslangType.getBasicType()) {
5754 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005755 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005756 break;
5757 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005758 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005759 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005760 case glslang::EbtInt64:
5761 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5762 break;
5763 case glslang::EbtUint64:
5764 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5765 break;
Rex Xucabbb782017-03-24 13:41:14 +08005766#ifdef AMD_EXTENSIONS
5767 case glslang::EbtInt16:
5768 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5769 break;
5770 case glslang::EbtUint16:
5771 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5772 break;
5773#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005774 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005775 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005776 break;
5777 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005778 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005779 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005780#ifdef AMD_EXTENSIONS
5781 case glslang::EbtFloat16:
5782 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5783 break;
5784#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005785 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005786 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005787 break;
5788 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005789 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005790 break;
5791 }
5792 ++nextConst;
5793 return scalar;
5794 }
5795
5796 return builder.makeCompositeConstant(typeId, spvConsts);
5797}
5798
John Kessenich7c1aa102015-10-15 13:29:11 -06005799// Return true if the node is a constant or symbol whose reading has no
5800// non-trivial observable cost or effect.
5801bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5802{
5803 // don't know what this is
5804 if (node == nullptr)
5805 return false;
5806
5807 // a constant is safe
5808 if (node->getAsConstantUnion() != nullptr)
5809 return true;
5810
5811 // not a symbol means non-trivial
5812 if (node->getAsSymbolNode() == nullptr)
5813 return false;
5814
5815 // a symbol, depends on what's being read
5816 switch (node->getType().getQualifier().storage) {
5817 case glslang::EvqTemporary:
5818 case glslang::EvqGlobal:
5819 case glslang::EvqIn:
5820 case glslang::EvqInOut:
5821 case glslang::EvqConst:
5822 case glslang::EvqConstReadOnly:
5823 case glslang::EvqUniform:
5824 return true;
5825 default:
5826 return false;
5827 }
qining25262b32016-05-06 17:25:16 -04005828}
John Kessenich7c1aa102015-10-15 13:29:11 -06005829
5830// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005831// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005832// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005833// Return true if trivial.
5834bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5835{
5836 if (node == nullptr)
5837 return false;
5838
John Kessenich84cc15f2017-05-24 16:44:47 -06005839 // count non scalars as trivial, as well as anything coming from HLSL
5840 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005841 return true;
5842
John Kessenich7c1aa102015-10-15 13:29:11 -06005843 // symbols and constants are trivial
5844 if (isTrivialLeaf(node))
5845 return true;
5846
5847 // otherwise, it needs to be a simple operation or one or two leaf nodes
5848
5849 // not a simple operation
5850 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5851 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5852 if (binaryNode == nullptr && unaryNode == nullptr)
5853 return false;
5854
5855 // not on leaf nodes
5856 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5857 return false;
5858
5859 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5860 return false;
5861 }
5862
5863 switch (node->getAsOperator()->getOp()) {
5864 case glslang::EOpLogicalNot:
5865 case glslang::EOpConvIntToBool:
5866 case glslang::EOpConvUintToBool:
5867 case glslang::EOpConvFloatToBool:
5868 case glslang::EOpConvDoubleToBool:
5869 case glslang::EOpEqual:
5870 case glslang::EOpNotEqual:
5871 case glslang::EOpLessThan:
5872 case glslang::EOpGreaterThan:
5873 case glslang::EOpLessThanEqual:
5874 case glslang::EOpGreaterThanEqual:
5875 case glslang::EOpIndexDirect:
5876 case glslang::EOpIndexDirectStruct:
5877 case glslang::EOpLogicalXor:
5878 case glslang::EOpAny:
5879 case glslang::EOpAll:
5880 return true;
5881 default:
5882 return false;
5883 }
5884}
5885
5886// Emit short-circuiting code, where 'right' is never evaluated unless
5887// the left side is true (for &&) or false (for ||).
5888spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5889{
5890 spv::Id boolTypeId = builder.makeBoolType();
5891
5892 // emit left operand
5893 builder.clearAccessChain();
5894 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005895 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005896
5897 // Operands to accumulate OpPhi operands
5898 std::vector<spv::Id> phiOperands;
5899 // accumulate left operand's phi information
5900 phiOperands.push_back(leftId);
5901 phiOperands.push_back(builder.getBuildPoint()->getId());
5902
5903 // Make the two kinds of operation symmetric with a "!"
5904 // || => emit "if (! left) result = right"
5905 // && => emit "if ( left) result = right"
5906 //
5907 // TODO: this runtime "not" for || could be avoided by adding functionality
5908 // to 'builder' to have an "else" without an "then"
5909 if (op == glslang::EOpLogicalOr)
5910 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5911
5912 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005913 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005914
5915 // emit right operand as the "then" part of the "if"
5916 builder.clearAccessChain();
5917 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005918 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005919
5920 // accumulate left operand's phi information
5921 phiOperands.push_back(rightId);
5922 phiOperands.push_back(builder.getBuildPoint()->getId());
5923
5924 // finish the "if"
5925 ifBuilder.makeEndIf();
5926
5927 // phi together the two results
5928 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5929}
5930
Rex Xu9d93a232016-05-05 12:30:44 +08005931// Return type Id of the imported set of extended instructions corresponds to the name.
5932// Import this set if it has not been imported yet.
5933spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5934{
5935 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5936 return extBuiltinMap[name];
5937 else {
Rex Xu51596642016-09-21 18:56:12 +08005938 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005939 spv::Id extBuiltins = builder.import(name);
5940 extBuiltinMap[name] = extBuiltins;
5941 return extBuiltins;
5942 }
5943}
5944
John Kessenich140f3df2015-06-26 16:58:36 -06005945}; // end anonymous namespace
5946
5947namespace glslang {
5948
John Kessenich68d78fd2015-07-12 19:28:10 -06005949void GetSpirvVersion(std::string& version)
5950{
John Kessenich9e55f632015-07-15 10:03:39 -06005951 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005952 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005953 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005954 version = buf;
5955}
5956
John Kessenicha372a3e2017-11-02 22:32:14 -06005957// For low-order part of the generator's magic number. Bump up
5958// when there is a change in the style (e.g., if SSA form changes,
5959// or a different instruction sequence to do something gets used).
5960int GetSpirvGeneratorVersion()
5961{
5962 return 2;
5963}
5964
John Kessenich140f3df2015-06-26 16:58:36 -06005965// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005966void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005967{
5968 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005969 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005970 if (out.fail())
5971 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005972 for (int i = 0; i < (int)spirv.size(); ++i) {
5973 unsigned int word = spirv[i];
5974 out.write((const char*)&word, 4);
5975 }
5976 out.close();
5977}
5978
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005979// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005980void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005981{
5982 std::ofstream out;
5983 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005984 if (out.fail())
5985 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005986 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005987 if (varName != nullptr) {
5988 out << "\t #pragma once" << std::endl;
5989 out << "const uint32_t " << varName << "[] = {" << std::endl;
5990 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005991 const int WORDS_PER_LINE = 8;
5992 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5993 out << "\t";
5994 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5995 const unsigned int word = spirv[i + j];
5996 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5997 if (i + j + 1 < (int)spirv.size()) {
5998 out << ",";
5999 }
6000 }
6001 out << std::endl;
6002 }
Flavio15017db2017-02-15 14:29:33 -08006003 if (varName != nullptr) {
6004 out << "};";
6005 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05006006 out.close();
6007}
6008
GregFcd1f1692017-09-21 18:40:22 -06006009#ifdef ENABLE_OPT
6010void errHandler(const std::string& str) {
6011 std::cerr << str << std::endl;
6012}
6013#endif
6014
John Kessenich140f3df2015-06-26 16:58:36 -06006015//
6016// Set up the glslang traversal
6017//
John Kessenich121853f2017-05-31 17:11:16 -06006018void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06006019{
Lei Zhang17535f72016-05-04 15:55:59 -04006020 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06006021 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04006022}
6023
John Kessenich121853f2017-05-31 17:11:16 -06006024void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
6025 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04006026{
John Kessenich140f3df2015-06-26 16:58:36 -06006027 TIntermNode* root = intermediate.getTreeRoot();
6028
6029 if (root == 0)
6030 return;
6031
John Kessenich121853f2017-05-31 17:11:16 -06006032 glslang::SpvOptions defaultOptions;
6033 if (options == nullptr)
6034 options = &defaultOptions;
6035
John Kessenich140f3df2015-06-26 16:58:36 -06006036 glslang::GetThreadPoolAllocator().push();
6037
John Kessenich121853f2017-05-31 17:11:16 -06006038 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06006039 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07006040 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06006041 it.dumpSpv(spirv);
6042
GregFcd1f1692017-09-21 18:40:22 -06006043#ifdef ENABLE_OPT
6044 // If from HLSL, run spirv-opt to "legalize" the SPIR-V for Vulkan
6045 // eg. forward and remove memory writes of opaque types.
6046 if ((intermediate.getSource() == EShSourceHlsl ||
6047 options->optimizeSize) &&
6048 !options->disableOptimizer) {
6049 spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
6050
6051 spvtools::Optimizer optimizer(target_env);
6052 optimizer.SetMessageConsumer([](spv_message_level_t level,
6053 const char* source,
6054 const spv_position_t& position,
6055 const char* message) {
6056 std::cerr << StringifyMessage(level, source, position, message)
6057 << std::endl;
6058 });
6059
6060 optimizer.RegisterPass(CreateInlineExhaustivePass());
6061 optimizer.RegisterPass(CreateLocalAccessChainConvertPass());
6062 optimizer.RegisterPass(CreateLocalSingleBlockLoadStoreElimPass());
6063 optimizer.RegisterPass(CreateLocalSingleStoreElimPass());
6064 optimizer.RegisterPass(CreateInsertExtractElimPass());
6065 optimizer.RegisterPass(CreateAggressiveDCEPass());
6066 optimizer.RegisterPass(CreateDeadBranchElimPass());
GregFcc80d802017-10-23 16:48:42 -06006067 optimizer.RegisterPass(CreateCFGCleanupPass());
GregFcd1f1692017-09-21 18:40:22 -06006068 optimizer.RegisterPass(CreateBlockMergePass());
6069 optimizer.RegisterPass(CreateLocalMultiStoreElimPass());
6070 optimizer.RegisterPass(CreateInsertExtractElimPass());
6071 optimizer.RegisterPass(CreateAggressiveDCEPass());
6072 // TODO(greg-lunarg): Add this when AMD driver issues are resolved
6073 // if (options->optimizeSize)
6074 // optimizer.RegisterPass(CreateCommonUniformElimPass());
6075
6076 if (!optimizer.Run(spirv.data(), spirv.size(), &spirv))
6077 return;
6078
6079 // Remove dead module-level objects: functions, types, vars
6080 // TODO(greg-lunarg): Switch to spirv-opt versions when available
6081 spv::spirvbin_t Remapper(0);
6082 Remapper.registerErrorHandler(errHandler);
6083 Remapper.remap(spirv, spv::spirvbin_t::DCE_ALL);
6084 }
6085#endif
6086
John Kessenich140f3df2015-06-26 16:58:36 -06006087 glslang::GetThreadPoolAllocator().pop();
6088}
6089
6090}; // end namespace glslang