blob: 4a16f6af39302d7365da5895534634b6220e5f6c [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
John Kessenich927608b2017-01-06 12:34:14 -070023// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060035
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080050#ifdef NV_EXTENSIONS
51 #include "GLSL.ext.NV.h"
52#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
John Kessenich55e7d112015-11-15 21:33:39 -070071// For low-order part of the generator's magic number. Bump up
72// when there is a change in the style (e.g., if SSA form changes,
73// or a different instruction sequence to do something gets used).
74const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060075
qining4c912612016-04-01 10:35:16 -040076namespace {
77class SpecConstantOpModeGuard {
78public:
79 SpecConstantOpModeGuard(spv::Builder* builder)
80 : builder_(builder) {
81 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040082 }
83 ~SpecConstantOpModeGuard() {
84 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
85 : builder_->setToNormalCodeGenMode();
86 }
qining40887662016-04-03 22:20:42 -040087 void turnOnSpecConstantOpMode() {
88 builder_->setToSpecConstCodeGenMode();
89 }
qining4c912612016-04-01 10:35:16 -040090
91private:
92 spv::Builder* builder_;
93 bool previous_flag_;
94};
95}
96
John Kessenich140f3df2015-06-26 16:58:36 -060097//
98// The main holder of information for translating glslang to SPIR-V.
99//
100// Derives from the AST walking base class.
101//
102class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
103public:
Lei Zhang17535f72016-05-04 15:55:59 -0400104 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenichfca82622016-11-26 13:23:20 -0700105 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600106
107 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
108 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
109 void visitConstantUnion(glslang::TIntermConstantUnion*);
110 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
111 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
112 void visitSymbol(glslang::TIntermSymbol* symbol);
113 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
114 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
115 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
116
John Kessenichfca82622016-11-26 13:23:20 -0700117 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700118 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600119
120protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800121 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800122 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100123 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700124 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600125 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
126 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600127 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
128 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
129 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600130 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700131 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600132 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600133 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
134 glslang::TLayoutPacking, const glslang::TQualifier&);
135 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
136 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700137 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700138 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800139 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600140 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700141 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700142 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
143 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
144 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 +0100145 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600146
John Kessenich6fccb3c2016-09-19 16:01:41 -0600147 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600148 void makeFunctions(const glslang::TIntermSequence&);
149 void makeGlobalInitializers(const glslang::TIntermSequence&);
150 void visitFunctions(const glslang::TIntermSequence&);
151 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800152 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600153 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
154 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600155 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
156
qining25262b32016-05-06 17:25:16 -0400157 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);
158 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
159 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 +0800160 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 +0800161 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 -0600162 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800163 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 +0800164 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800165 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600166 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 +0800167 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600168 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
169 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700170 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600171 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700172 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400173 spv::Id createSpvConstant(const glslang::TIntermTyped&);
174 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600175 bool isTrivialLeaf(const glslang::TIntermTyped* node);
176 bool isTrivial(const glslang::TIntermTyped* node);
177 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800178 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600179
180 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600181 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700182 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600183 int sequenceDepth;
184
Lei Zhang17535f72016-05-04 15:55:59 -0400185 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400186
John Kessenich140f3df2015-06-26 16:58:36 -0600187 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
188 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700189 bool inEntryPoint;
190 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700191 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 -0700192 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600193 const glslang::TIntermediate* glslangIntermediate;
194 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800195 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600196
John Kessenich2f273362015-07-18 22:34:27 -0600197 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600198 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600199 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700200 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600201 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 -0600202 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600203};
204
205//
206// Helper functions for translating glslang representations to SPIR-V enumerants.
207//
208
209// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700210spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600211{
John Kessenich66e2faf2016-03-12 18:34:36 -0700212 switch (source) {
213 case glslang::EShSourceGlsl:
214 switch (profile) {
215 case ENoProfile:
216 case ECoreProfile:
217 case ECompatibilityProfile:
218 return spv::SourceLanguageGLSL;
219 case EEsProfile:
220 return spv::SourceLanguageESSL;
221 default:
222 return spv::SourceLanguageUnknown;
223 }
224 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600225 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600226 default:
227 return spv::SourceLanguageUnknown;
228 }
229}
230
231// Translate glslang language (stage) to SPIR-V execution model.
232spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
233{
234 switch (stage) {
235 case EShLangVertex: return spv::ExecutionModelVertex;
236 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
237 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
238 case EShLangGeometry: return spv::ExecutionModelGeometry;
239 case EShLangFragment: return spv::ExecutionModelFragment;
240 case EShLangCompute: return spv::ExecutionModelGLCompute;
241 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700242 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600243 return spv::ExecutionModelFragment;
244 }
245}
246
247// Translate glslang type to SPIR-V storage class.
248spv::StorageClass TranslateStorageClass(const glslang::TType& type)
249{
250 if (type.getQualifier().isPipeInput())
251 return spv::StorageClassInput;
252 else if (type.getQualifier().isPipeOutput())
253 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700254 else if (type.getBasicType() == glslang::EbtAtomicUint)
255 return spv::StorageClassAtomicCounter;
John Kessenich4a57dce2017-02-24 19:15:46 -0700256 else if (type.containsOpaque())
257 return spv::StorageClassUniformConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600258 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700259 if (type.getQualifier().layoutPushConstant)
260 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600261 if (type.getBasicType() == glslang::EbtBlock)
262 return spv::StorageClassUniform;
263 else
264 return spv::StorageClassUniformConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600265 } else {
266 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700267 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
268 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600269 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
270 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400271 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700272 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600273 return spv::StorageClassFunction;
274 }
275 }
276}
277
278// Translate glslang sampler type to SPIR-V dimensionality.
279spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
280{
281 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700282 case glslang::Esd1D: return spv::Dim1D;
283 case glslang::Esd2D: return spv::Dim2D;
284 case glslang::Esd3D: return spv::Dim3D;
285 case glslang::EsdCube: return spv::DimCube;
286 case glslang::EsdRect: return spv::DimRect;
287 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700288 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600289 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700290 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600291 return spv::Dim2D;
292 }
293}
294
John Kessenichf6640762016-08-01 19:44:00 -0600295// Translate glslang precision to SPIR-V precision decorations.
296spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600297{
John Kessenichf6640762016-08-01 19:44:00 -0600298 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700299 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600300 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600301 default:
302 return spv::NoPrecision;
303 }
304}
305
John Kessenichf6640762016-08-01 19:44:00 -0600306// Translate glslang type to SPIR-V precision decorations.
307spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
308{
309 return TranslatePrecisionDecoration(type.getQualifier().precision);
310}
311
John Kessenich140f3df2015-06-26 16:58:36 -0600312// Translate glslang type to SPIR-V block decorations.
313spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
314{
315 if (type.getBasicType() == glslang::EbtBlock) {
316 switch (type.getQualifier().storage) {
317 case glslang::EvqUniform: return spv::DecorationBlock;
318 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
319 case glslang::EvqVaryingIn: return spv::DecorationBlock;
320 case glslang::EvqVaryingOut: return spv::DecorationBlock;
321 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700322 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600323 break;
324 }
325 }
326
John Kessenich4016e382016-07-15 11:53:56 -0600327 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600328}
329
Rex Xu1da878f2016-02-21 20:59:01 +0800330// Translate glslang type to SPIR-V memory decorations.
331void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
332{
333 if (qualifier.coherent)
334 memory.push_back(spv::DecorationCoherent);
335 if (qualifier.volatil)
336 memory.push_back(spv::DecorationVolatile);
337 if (qualifier.restrict)
338 memory.push_back(spv::DecorationRestrict);
339 if (qualifier.readonly)
340 memory.push_back(spv::DecorationNonWritable);
341 if (qualifier.writeonly)
342 memory.push_back(spv::DecorationNonReadable);
343}
344
John Kessenich140f3df2015-06-26 16:58:36 -0600345// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700346spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600347{
348 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700349 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600350 case glslang::ElmRowMajor:
351 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700352 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600353 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700354 default:
355 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600356 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600357 }
358 } else {
359 switch (type.getBasicType()) {
360 default:
John Kessenich4016e382016-07-15 11:53:56 -0600361 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600362 break;
363 case glslang::EbtBlock:
364 switch (type.getQualifier().storage) {
365 case glslang::EvqUniform:
366 case glslang::EvqBuffer:
367 switch (type.getQualifier().layoutPacking) {
368 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600369 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
370 default:
John Kessenich4016e382016-07-15 11:53:56 -0600371 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600372 }
373 case glslang::EvqVaryingIn:
374 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700375 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600376 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600377 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700378 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600379 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600380 }
381 }
382 }
383}
384
385// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600386// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700387// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800388spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600389{
Rex Xubbceed72016-05-21 09:40:44 +0800390 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700391 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600392 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800393 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700394 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700395 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600396 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800397#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800398 else if (qualifier.explicitInterp) {
399 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800400 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800401 }
Rex Xu9d93a232016-05-05 12:30:44 +0800402#endif
Rex Xubbceed72016-05-21 09:40:44 +0800403 else
John Kessenich4016e382016-07-15 11:53:56 -0600404 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800405}
406
407// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600408// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800409// should be applied.
410spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
411{
412 if (qualifier.patch)
413 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700414 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600415 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700416 else if (qualifier.sample) {
417 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600418 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700419 } else
John Kessenich4016e382016-07-15 11:53:56 -0600420 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600421}
422
John Kessenich92187592016-02-01 13:45:25 -0700423// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700424spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600425{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700426 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600427 return spv::DecorationInvariant;
428 else
John Kessenich4016e382016-07-15 11:53:56 -0600429 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600430}
431
qining9220dbb2016-05-04 17:34:38 -0400432// If glslang type is noContraction, return SPIR-V NoContraction decoration.
433spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
434{
435 if (qualifier.noContraction)
436 return spv::DecorationNoContraction;
437 else
John Kessenich4016e382016-07-15 11:53:56 -0600438 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400439}
440
David Netoa901ffe2016-06-08 14:11:40 +0100441// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
442// associated capabilities when required. For some built-in variables, a capability
443// is generated only when using the variable in an executable instruction, but not when
444// just declaring a struct member variable with it. This is true for PointSize,
445// ClipDistance, and CullDistance.
446spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600447{
448 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700449 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600450 // Defer adding the capability until the built-in is actually used.
451 if (! memberDeclaration) {
452 switch (glslangIntermediate->getStage()) {
453 case EShLangGeometry:
454 builder.addCapability(spv::CapabilityGeometryPointSize);
455 break;
456 case EShLangTessControl:
457 case EShLangTessEvaluation:
458 builder.addCapability(spv::CapabilityTessellationPointSize);
459 break;
460 default:
461 break;
462 }
John Kessenich92187592016-02-01 13:45:25 -0700463 }
464 return spv::BuiltInPointSize;
465
John Kessenichebb50532016-05-16 19:22:05 -0600466 // These *Distance capabilities logically belong here, but if the member is declared and
467 // then never used, consumers of SPIR-V prefer the capability not be declared.
468 // They are now generated when used, rather than here when declared.
469 // Potentially, the specification should be more clear what the minimum
470 // use needed is to trigger the capability.
471 //
John Kessenich92187592016-02-01 13:45:25 -0700472 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100473 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800474 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700475 return spv::BuiltInClipDistance;
476
477 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100478 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800479 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700480 return spv::BuiltInCullDistance;
481
482 case glslang::EbvViewportIndex:
Rex Xu5e317ff2017-03-16 23:02:39 +0800483 if (!memberDeclaration) {
484 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800485#ifdef NV_EXTENSIONS
Rex Xu5e317ff2017-03-16 23:02:39 +0800486 if (glslangIntermediate->getStage() == EShLangVertex ||
487 glslangIntermediate->getStage() == EShLangTessControl ||
488 glslangIntermediate->getStage() == EShLangTessEvaluation) {
489
490 builder.addExtension(spv::E_SPV_NV_viewport_array2);
491 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
492 }
chaoc771d89f2017-01-13 01:10:53 -0800493#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800494 }
John Kessenich92187592016-02-01 13:45:25 -0700495 return spv::BuiltInViewportIndex;
496
John Kessenich5e801132016-02-15 11:09:46 -0700497 case glslang::EbvSampleId:
498 builder.addCapability(spv::CapabilitySampleRateShading);
499 return spv::BuiltInSampleId;
500
501 case glslang::EbvSamplePosition:
502 builder.addCapability(spv::CapabilitySampleRateShading);
503 return spv::BuiltInSamplePosition;
504
505 case glslang::EbvSampleMask:
506 builder.addCapability(spv::CapabilitySampleRateShading);
507 return spv::BuiltInSampleMask;
508
John Kessenich78a45572016-07-08 14:05:15 -0600509 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800510 if (!memberDeclaration) {
511 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800512#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -0800513 if (glslangIntermediate->getStage() == EShLangVertex ||
514 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800515 glslangIntermediate->getStage() == EShLangTessEvaluation) {
516
chaoc771d89f2017-01-13 01:10:53 -0800517 builder.addExtension(spv::E_SPV_NV_viewport_array2);
518 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
519 }
chaoc771d89f2017-01-13 01:10:53 -0800520#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800521 }
522
John Kessenich78a45572016-07-08 14:05:15 -0600523 return spv::BuiltInLayer;
524
John Kessenich140f3df2015-06-26 16:58:36 -0600525 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600526 case glslang::EbvVertexId: return spv::BuiltInVertexId;
527 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700528 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
529 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800530
John Kessenichda581a22015-10-14 14:10:30 -0600531 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800532 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
533 builder.addCapability(spv::CapabilityDrawParameters);
534 return spv::BuiltInBaseVertex;
535
John Kessenichda581a22015-10-14 14:10:30 -0600536 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800537 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
538 builder.addCapability(spv::CapabilityDrawParameters);
539 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200540
John Kessenichda581a22015-10-14 14:10:30 -0600541 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800542 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
543 builder.addCapability(spv::CapabilityDrawParameters);
544 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200545
546 case glslang::EbvPrimitiveId:
547 if (glslangIntermediate->getStage() == EShLangFragment)
548 builder.addCapability(spv::CapabilityGeometry);
549 return spv::BuiltInPrimitiveId;
550
John Kessenich140f3df2015-06-26 16:58:36 -0600551 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600552 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
553 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
554 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
555 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
556 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
557 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
558 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600559 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
560 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
561 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
562 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
563 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
564 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
565 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
566 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800567
Rex Xu574ab042016-04-14 16:53:07 +0800568 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800569 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800570 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
571 return spv::BuiltInSubgroupSize;
572
Rex Xu574ab042016-04-14 16:53:07 +0800573 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800574 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800575 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
576 return spv::BuiltInSubgroupLocalInvocationId;
577
Rex Xu574ab042016-04-14 16:53:07 +0800578 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800579 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
580 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
581 return spv::BuiltInSubgroupEqMaskKHR;
582
Rex Xu574ab042016-04-14 16:53:07 +0800583 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800584 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
585 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
586 return spv::BuiltInSubgroupGeMaskKHR;
587
Rex Xu574ab042016-04-14 16:53:07 +0800588 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800589 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
590 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
591 return spv::BuiltInSubgroupGtMaskKHR;
592
Rex Xu574ab042016-04-14 16:53:07 +0800593 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800594 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
595 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
596 return spv::BuiltInSubgroupLeMaskKHR;
597
Rex Xu574ab042016-04-14 16:53:07 +0800598 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800599 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
600 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
601 return spv::BuiltInSubgroupLtMaskKHR;
602
Rex Xu9d93a232016-05-05 12:30:44 +0800603#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800604 case glslang::EbvBaryCoordNoPersp:
605 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
606 return spv::BuiltInBaryCoordNoPerspAMD;
607
608 case glslang::EbvBaryCoordNoPerspCentroid:
609 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
610 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
611
612 case glslang::EbvBaryCoordNoPerspSample:
613 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
614 return spv::BuiltInBaryCoordNoPerspSampleAMD;
615
616 case glslang::EbvBaryCoordSmooth:
617 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
618 return spv::BuiltInBaryCoordSmoothAMD;
619
620 case glslang::EbvBaryCoordSmoothCentroid:
621 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
622 return spv::BuiltInBaryCoordSmoothCentroidAMD;
623
624 case glslang::EbvBaryCoordSmoothSample:
625 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
626 return spv::BuiltInBaryCoordSmoothSampleAMD;
627
628 case glslang::EbvBaryCoordPullModel:
629 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
630 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800631#endif
chaoc771d89f2017-01-13 01:10:53 -0800632
John Kessenich6c8aaac2017-02-27 01:20:51 -0700633 case glslang::EbvDeviceIndex:
634 builder.addExtension(spv::E_SPV_KHR_device_group);
635 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700636 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700637
638 case glslang::EbvViewIndex:
639 builder.addExtension(spv::E_SPV_KHR_multiview);
640 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700641 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700642
chaoc771d89f2017-01-13 01:10:53 -0800643#ifdef NV_EXTENSIONS
644 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800645 if (!memberDeclaration) {
646 builder.addExtension(spv::E_SPV_NV_viewport_array2);
647 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
648 }
chaoc771d89f2017-01-13 01:10:53 -0800649 return spv::BuiltInViewportMaskNV;
650 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800651 if (!memberDeclaration) {
652 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
653 builder.addCapability(spv::CapabilityShaderStereoViewNV);
654 }
chaoc771d89f2017-01-13 01:10:53 -0800655 return spv::BuiltInSecondaryPositionNV;
656 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800657 if (!memberDeclaration) {
658 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
659 builder.addCapability(spv::CapabilityShaderStereoViewNV);
660 }
chaoc771d89f2017-01-13 01:10:53 -0800661 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800662 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800663 if (!memberDeclaration) {
664 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
665 builder.addCapability(spv::CapabilityPerViewAttributesNV);
666 }
chaocdf3956c2017-02-14 14:52:34 -0800667 return spv::BuiltInPositionPerViewNV;
668 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800669 if (!memberDeclaration) {
670 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
671 builder.addCapability(spv::CapabilityPerViewAttributesNV);
672 }
chaocdf3956c2017-02-14 14:52:34 -0800673 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800674#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800675 default:
676 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600677 }
678}
679
Rex Xufc618912015-09-09 16:42:49 +0800680// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700681spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800682{
683 assert(type.getBasicType() == glslang::EbtSampler);
684
John Kessenich5d0fa972016-02-15 11:57:00 -0700685 // Check for capabilities
686 switch (type.getQualifier().layoutFormat) {
687 case glslang::ElfRg32f:
688 case glslang::ElfRg16f:
689 case glslang::ElfR11fG11fB10f:
690 case glslang::ElfR16f:
691 case glslang::ElfRgba16:
692 case glslang::ElfRgb10A2:
693 case glslang::ElfRg16:
694 case glslang::ElfRg8:
695 case glslang::ElfR16:
696 case glslang::ElfR8:
697 case glslang::ElfRgba16Snorm:
698 case glslang::ElfRg16Snorm:
699 case glslang::ElfRg8Snorm:
700 case glslang::ElfR16Snorm:
701 case glslang::ElfR8Snorm:
702
703 case glslang::ElfRg32i:
704 case glslang::ElfRg16i:
705 case glslang::ElfRg8i:
706 case glslang::ElfR16i:
707 case glslang::ElfR8i:
708
709 case glslang::ElfRgb10a2ui:
710 case glslang::ElfRg32ui:
711 case glslang::ElfRg16ui:
712 case glslang::ElfRg8ui:
713 case glslang::ElfR16ui:
714 case glslang::ElfR8ui:
715 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
716 break;
717
718 default:
719 break;
720 }
721
722 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800723 switch (type.getQualifier().layoutFormat) {
724 case glslang::ElfNone: return spv::ImageFormatUnknown;
725 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
726 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
727 case glslang::ElfR32f: return spv::ImageFormatR32f;
728 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
729 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
730 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
731 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
732 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
733 case glslang::ElfR16f: return spv::ImageFormatR16f;
734 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
735 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
736 case glslang::ElfRg16: return spv::ImageFormatRg16;
737 case glslang::ElfRg8: return spv::ImageFormatRg8;
738 case glslang::ElfR16: return spv::ImageFormatR16;
739 case glslang::ElfR8: return spv::ImageFormatR8;
740 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
741 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
742 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
743 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
744 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
745 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
746 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
747 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
748 case glslang::ElfR32i: return spv::ImageFormatR32i;
749 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
750 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
751 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
752 case glslang::ElfR16i: return spv::ImageFormatR16i;
753 case glslang::ElfR8i: return spv::ImageFormatR8i;
754 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
755 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
756 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
757 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
758 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
759 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
760 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
761 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
762 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
763 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600764 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800765 }
766}
767
qining25262b32016-05-06 17:25:16 -0400768// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700769// descriptor set.
770bool IsDescriptorResource(const glslang::TType& type)
771{
John Kessenichf7497e22016-03-08 21:36:22 -0700772 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700773 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700774 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700775
776 // non block...
777 // basically samplerXXX/subpass/sampler/texture are all included
778 // if they are the global-scope-class, not the function parameter
779 // (or local, if they ever exist) class.
780 if (type.getBasicType() == glslang::EbtSampler)
781 return type.getQualifier().isUniformOrBuffer();
782
783 // None of the above.
784 return false;
785}
786
John Kesseniche0b6cad2015-12-24 10:30:13 -0700787void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
788{
789 if (child.layoutMatrix == glslang::ElmNone)
790 child.layoutMatrix = parent.layoutMatrix;
791
792 if (parent.invariant)
793 child.invariant = true;
794 if (parent.nopersp)
795 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800796#ifdef AMD_EXTENSIONS
797 if (parent.explicitInterp)
798 child.explicitInterp = true;
799#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700800 if (parent.flat)
801 child.flat = true;
802 if (parent.centroid)
803 child.centroid = true;
804 if (parent.patch)
805 child.patch = true;
806 if (parent.sample)
807 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800808 if (parent.coherent)
809 child.coherent = true;
810 if (parent.volatil)
811 child.volatil = true;
812 if (parent.restrict)
813 child.restrict = true;
814 if (parent.readonly)
815 child.readonly = true;
816 if (parent.writeonly)
817 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700818}
819
John Kessenichf2b7f332016-09-01 17:05:23 -0600820bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700821{
John Kessenich7b9fa252016-01-21 18:56:57 -0700822 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600823 // - struct members might inherit from a struct declaration
824 // (note that non-block structs don't explicitly inherit,
825 // only implicitly, meaning no decoration involved)
826 // - affect decorations on the struct members
827 // (note smooth does not, and expecting something like volatile
828 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700829 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600830 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700831}
832
John Kessenich140f3df2015-06-26 16:58:36 -0600833//
834// Implement the TGlslangToSpvTraverser class.
835//
836
Lei Zhang17535f72016-05-04 15:55:59 -0400837TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600838 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
839 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400840 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700841 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600842 glslangIntermediate(glslangIntermediate)
843{
844 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
845
846 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700847 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600848 stdBuiltins = builder.import("GLSL.std.450");
849 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600850 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
851 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600852
853 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600854 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
855 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600856 builder.addSourceExtension(it->c_str());
857
858 // Add the top-level modes for this shader.
859
John Kessenich92187592016-02-01 13:45:25 -0700860 if (glslangIntermediate->getXfbMode()) {
861 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600862 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700863 }
John Kessenich140f3df2015-06-26 16:58:36 -0600864
865 unsigned int mode;
866 switch (glslangIntermediate->getStage()) {
867 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600868 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600869 break;
870
steve-lunarge7412492017-03-23 11:56:07 -0600871 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600872 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600873 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600874
steve-lunarge7412492017-03-23 11:56:07 -0600875 glslang::TLayoutGeometry primitive;
876
877 if (glslangIntermediate->getStage() == EShLangTessControl) {
878 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
879 primitive = glslangIntermediate->getOutputPrimitive();
880 } else {
881 primitive = glslangIntermediate->getInputPrimitive();
882 }
883
884 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700885 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
886 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
887 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600888 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600889 }
John Kessenich4016e382016-07-15 11:53:56 -0600890 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600891 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
892
John Kesseniche6903322015-10-13 16:29:02 -0600893 switch (glslangIntermediate->getVertexSpacing()) {
894 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
895 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
896 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600897 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600898 }
John Kessenich4016e382016-07-15 11:53:56 -0600899 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600900 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
901
902 switch (glslangIntermediate->getVertexOrder()) {
903 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
904 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600905 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600906 }
John Kessenich4016e382016-07-15 11:53:56 -0600907 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600908 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
909
910 if (glslangIntermediate->getPointMode())
911 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600912 break;
913
914 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600915 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600916 switch (glslangIntermediate->getInputPrimitive()) {
917 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
918 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
919 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700920 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600921 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600922 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600923 }
John Kessenich4016e382016-07-15 11:53:56 -0600924 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600925 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600926
John Kessenich140f3df2015-06-26 16:58:36 -0600927 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
928
929 switch (glslangIntermediate->getOutputPrimitive()) {
930 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
931 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
932 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600933 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600934 }
John Kessenich4016e382016-07-15 11:53:56 -0600935 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600936 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
937 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
938 break;
939
940 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600941 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600942 if (glslangIntermediate->getPixelCenterInteger())
943 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600944
John Kessenich140f3df2015-06-26 16:58:36 -0600945 if (glslangIntermediate->getOriginUpperLeft())
946 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600947 else
948 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600949
950 if (glslangIntermediate->getEarlyFragmentTests())
951 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
952
953 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600954 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
955 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600956 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600957 }
John Kessenich4016e382016-07-15 11:53:56 -0600958 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600959 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
960
961 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
962 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600963 break;
964
965 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600966 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600967 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
968 glslangIntermediate->getLocalSize(1),
969 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600970 break;
971
972 default:
973 break;
974 }
John Kessenich140f3df2015-06-26 16:58:36 -0600975}
976
John Kessenichfca82622016-11-26 13:23:20 -0700977// Finish creating SPV, after the traversal is complete.
978void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700979{
John Kessenich517fe7a2016-11-26 13:31:47 -0700980 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700981 builder.setBuildPoint(shaderEntry->getLastBlock());
982 builder.leaveFunction();
983 }
984
John Kessenich7ba63412015-12-20 17:37:07 -0700985 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100986 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
987 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700988
qiningda397332016-03-09 19:54:03 -0500989 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700990}
991
John Kessenichfca82622016-11-26 13:23:20 -0700992// Write the SPV into 'out'.
993void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -0600994{
John Kessenichfca82622016-11-26 13:23:20 -0700995 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -0600996}
997
998//
999// Implement the traversal functions.
1000//
1001// Return true from interior nodes to have the external traversal
1002// continue on to children. Return false if children were
1003// already processed.
1004//
1005
1006//
qining25262b32016-05-06 17:25:16 -04001007// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001008// - uniform/input reads
1009// - output writes
1010// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1011// - something simple that degenerates into the last bullet
1012//
1013void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1014{
qining75d1d802016-04-06 14:42:01 -04001015 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1016 if (symbol->getType().getQualifier().isSpecConstant())
1017 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1018
John Kessenich140f3df2015-06-26 16:58:36 -06001019 // getSymbolId() will set up all the IO decorations on the first call.
1020 // Formal function parameters were mapped during makeFunctions().
1021 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001022
1023 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1024 if (builder.isPointer(id)) {
1025 spv::StorageClass sc = builder.getStorageClass(id);
1026 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1027 iOSet.insert(id);
1028 }
1029
1030 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001031 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001032 // Prepare to generate code for the access
1033
1034 // L-value chains will be computed left to right. We're on the symbol now,
1035 // which is the left-most part of the access chain, so now is "clear" time,
1036 // followed by setting the base.
1037 builder.clearAccessChain();
1038
1039 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001040 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001041 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001042 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001043 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001044 // These are also pure R-values.
1045 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001046 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001047 builder.setAccessChainRValue(id);
1048 else
1049 builder.setAccessChainLValue(id);
1050 }
1051}
1052
1053bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1054{
qining40887662016-04-03 22:20:42 -04001055 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1056 if (node->getType().getQualifier().isSpecConstant())
1057 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1058
John Kessenich140f3df2015-06-26 16:58:36 -06001059 // First, handle special cases
1060 switch (node->getOp()) {
1061 case glslang::EOpAssign:
1062 case glslang::EOpAddAssign:
1063 case glslang::EOpSubAssign:
1064 case glslang::EOpMulAssign:
1065 case glslang::EOpVectorTimesMatrixAssign:
1066 case glslang::EOpVectorTimesScalarAssign:
1067 case glslang::EOpMatrixTimesScalarAssign:
1068 case glslang::EOpMatrixTimesMatrixAssign:
1069 case glslang::EOpDivAssign:
1070 case glslang::EOpModAssign:
1071 case glslang::EOpAndAssign:
1072 case glslang::EOpInclusiveOrAssign:
1073 case glslang::EOpExclusiveOrAssign:
1074 case glslang::EOpLeftShiftAssign:
1075 case glslang::EOpRightShiftAssign:
1076 // A bin-op assign "a += b" means the same thing as "a = a + b"
1077 // where a is evaluated before b. For a simple assignment, GLSL
1078 // says to evaluate the left before the right. So, always, left
1079 // node then right node.
1080 {
1081 // get the left l-value, save it away
1082 builder.clearAccessChain();
1083 node->getLeft()->traverse(this);
1084 spv::Builder::AccessChain lValue = builder.getAccessChain();
1085
1086 // evaluate the right
1087 builder.clearAccessChain();
1088 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001089 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001090
1091 if (node->getOp() != glslang::EOpAssign) {
1092 // the left is also an r-value
1093 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001094 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001095
1096 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001097 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001098 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001099 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1100 node->getType().getBasicType());
1101
1102 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001103 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001104 }
1105
1106 // store the result
1107 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001108 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001109
1110 // assignments are expressions having an rValue after they are evaluated...
1111 builder.clearAccessChain();
1112 builder.setAccessChainRValue(rValue);
1113 }
1114 return false;
1115 case glslang::EOpIndexDirect:
1116 case glslang::EOpIndexDirectStruct:
1117 {
1118 // Get the left part of the access chain.
1119 node->getLeft()->traverse(this);
1120
1121 // Add the next element in the chain
1122
David Netoa901ffe2016-06-08 14:11:40 +01001123 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001124 if (! node->getLeft()->getType().isArray() &&
1125 node->getLeft()->getType().isVector() &&
1126 node->getOp() == glslang::EOpIndexDirect) {
1127 // This is essentially a hard-coded vector swizzle of size 1,
1128 // so short circuit the access-chain stuff with a swizzle.
1129 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001130 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001131 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001132 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001133 int spvIndex = glslangIndex;
1134 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1135 node->getOp() == glslang::EOpIndexDirectStruct)
1136 {
1137 // This may be, e.g., an anonymous block-member selection, which generally need
1138 // index remapping due to hidden members in anonymous blocks.
1139 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1140 assert(remapper.size() > 0);
1141 spvIndex = remapper[glslangIndex];
1142 }
John Kessenichebb50532016-05-16 19:22:05 -06001143
David Netoa901ffe2016-06-08 14:11:40 +01001144 // normal case for indexing array or structure or block
1145 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1146
1147 // Add capabilities here for accessing PointSize and clip/cull distance.
1148 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001149 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001150 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001151 }
1152 }
1153 return false;
1154 case glslang::EOpIndexIndirect:
1155 {
1156 // Structure or array or vector indirection.
1157 // Will use native SPIR-V access-chain for struct and array indirection;
1158 // matrices are arrays of vectors, so will also work for a matrix.
1159 // Will use the access chain's 'component' for variable index into a vector.
1160
1161 // This adapter is building access chains left to right.
1162 // Set up the access chain to the left.
1163 node->getLeft()->traverse(this);
1164
1165 // save it so that computing the right side doesn't trash it
1166 spv::Builder::AccessChain partial = builder.getAccessChain();
1167
1168 // compute the next index in the chain
1169 builder.clearAccessChain();
1170 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001171 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001172
1173 // restore the saved access chain
1174 builder.setAccessChain(partial);
1175
1176 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001177 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001178 else
John Kessenichfa668da2015-09-13 14:46:30 -06001179 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001180 }
1181 return false;
1182 case glslang::EOpVectorSwizzle:
1183 {
1184 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001185 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001186 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001187 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001188 }
1189 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001190 case glslang::EOpMatrixSwizzle:
1191 logger->missingFunctionality("matrix swizzle");
1192 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001193 case glslang::EOpLogicalOr:
1194 case glslang::EOpLogicalAnd:
1195 {
1196
1197 // These may require short circuiting, but can sometimes be done as straight
1198 // binary operations. The right operand must be short circuited if it has
1199 // side effects, and should probably be if it is complex.
1200 if (isTrivial(node->getRight()->getAsTyped()))
1201 break; // handle below as a normal binary operation
1202 // otherwise, we need to do dynamic short circuiting on the right operand
1203 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1204 builder.clearAccessChain();
1205 builder.setAccessChainRValue(result);
1206 }
1207 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001208 default:
1209 break;
1210 }
1211
1212 // Assume generic binary op...
1213
John Kessenich32cfd492016-02-02 12:37:46 -07001214 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001215 builder.clearAccessChain();
1216 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001217 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001218
John Kessenich32cfd492016-02-02 12:37:46 -07001219 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001220 builder.clearAccessChain();
1221 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001222 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001223
John Kessenich32cfd492016-02-02 12:37:46 -07001224 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001225 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001226 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001227 convertGlslangToSpvType(node->getType()), left, right,
1228 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001229
John Kessenich50e57562015-12-21 21:21:11 -07001230 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001231 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001232 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001233 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001234 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001235 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001236 return false;
1237 }
John Kessenich140f3df2015-06-26 16:58:36 -06001238}
1239
1240bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1241{
qining40887662016-04-03 22:20:42 -04001242 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1243 if (node->getType().getQualifier().isSpecConstant())
1244 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1245
John Kessenichfc51d282015-08-19 13:34:18 -06001246 spv::Id result = spv::NoResult;
1247
1248 // try texturing first
1249 result = createImageTextureFunctionCall(node);
1250 if (result != spv::NoResult) {
1251 builder.clearAccessChain();
1252 builder.setAccessChainRValue(result);
1253
1254 return false; // done with this node
1255 }
1256
1257 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001258
1259 if (node->getOp() == glslang::EOpArrayLength) {
1260 // Quite special; won't want to evaluate the operand.
1261
1262 // Normal .length() would have been constant folded by the front-end.
1263 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001264 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001265 assert(node->getOperand()->getType().isRuntimeSizedArray());
1266 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1267 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001268 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1269 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001270
1271 builder.clearAccessChain();
1272 builder.setAccessChainRValue(length);
1273
1274 return false;
1275 }
1276
John Kessenichfc51d282015-08-19 13:34:18 -06001277 // Start by evaluating the operand
1278
John Kessenich8c8505c2016-07-26 12:50:38 -06001279 // Does it need a swizzle inversion? If so, evaluation is inverted;
1280 // operate first on the swizzle base, then apply the swizzle.
1281 spv::Id invertedType = spv::NoType;
1282 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1283 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1284 invertedType = getInvertedSwizzleType(*node->getOperand());
1285
John Kessenich140f3df2015-06-26 16:58:36 -06001286 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001287 if (invertedType != spv::NoType)
1288 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1289 else
1290 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001291
Rex Xufc618912015-09-09 16:42:49 +08001292 spv::Id operand = spv::NoResult;
1293
1294 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1295 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001296 node->getOp() == glslang::EOpAtomicCounter ||
1297 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001298 operand = builder.accessChainGetLValue(); // Special case l-value operands
1299 else
John Kessenich32cfd492016-02-02 12:37:46 -07001300 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001301
John Kessenichf6640762016-08-01 19:44:00 -06001302 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001303 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001304
1305 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001306 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001307 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001308
1309 // if not, then possibly an operation
1310 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001311 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001312
1313 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001314 if (invertedType)
1315 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1316
John Kessenich140f3df2015-06-26 16:58:36 -06001317 builder.clearAccessChain();
1318 builder.setAccessChainRValue(result);
1319
1320 return false; // done with this node
1321 }
1322
1323 // it must be a special case, check...
1324 switch (node->getOp()) {
1325 case glslang::EOpPostIncrement:
1326 case glslang::EOpPostDecrement:
1327 case glslang::EOpPreIncrement:
1328 case glslang::EOpPreDecrement:
1329 {
1330 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001331 spv::Id one = 0;
1332 if (node->getBasicType() == glslang::EbtFloat)
1333 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001334 else if (node->getBasicType() == glslang::EbtDouble)
1335 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001336#ifdef AMD_EXTENSIONS
1337 else if (node->getBasicType() == glslang::EbtFloat16)
1338 one = builder.makeFloat16Constant(1.0F);
1339#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001340 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1341 one = builder.makeInt64Constant(1);
1342 else
1343 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001344 glslang::TOperator op;
1345 if (node->getOp() == glslang::EOpPreIncrement ||
1346 node->getOp() == glslang::EOpPostIncrement)
1347 op = glslang::EOpAdd;
1348 else
1349 op = glslang::EOpSub;
1350
John Kessenichf6640762016-08-01 19:44:00 -06001351 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001352 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001353 convertGlslangToSpvType(node->getType()), operand, one,
1354 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001355 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001356
1357 // The result of operation is always stored, but conditionally the
1358 // consumed result. The consumed result is always an r-value.
1359 builder.accessChainStore(result);
1360 builder.clearAccessChain();
1361 if (node->getOp() == glslang::EOpPreIncrement ||
1362 node->getOp() == glslang::EOpPreDecrement)
1363 builder.setAccessChainRValue(result);
1364 else
1365 builder.setAccessChainRValue(operand);
1366 }
1367
1368 return false;
1369
1370 case glslang::EOpEmitStreamVertex:
1371 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1372 return false;
1373 case glslang::EOpEndStreamPrimitive:
1374 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1375 return false;
1376
1377 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001378 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001379 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001380 }
John Kessenich140f3df2015-06-26 16:58:36 -06001381}
1382
1383bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1384{
qining27e04a02016-04-14 16:40:20 -04001385 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1386 if (node->getType().getQualifier().isSpecConstant())
1387 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1388
John Kessenichfc51d282015-08-19 13:34:18 -06001389 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001390 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1391 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001392
1393 // try texturing
1394 result = createImageTextureFunctionCall(node);
1395 if (result != spv::NoResult) {
1396 builder.clearAccessChain();
1397 builder.setAccessChainRValue(result);
1398
1399 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001400 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001401 // "imageStore" is a special case, which has no result
1402 return false;
1403 }
John Kessenichfc51d282015-08-19 13:34:18 -06001404
John Kessenich140f3df2015-06-26 16:58:36 -06001405 glslang::TOperator binOp = glslang::EOpNull;
1406 bool reduceComparison = true;
1407 bool isMatrix = false;
1408 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001409 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001410
1411 assert(node->getOp());
1412
John Kessenichf6640762016-08-01 19:44:00 -06001413 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001414
1415 switch (node->getOp()) {
1416 case glslang::EOpSequence:
1417 {
1418 if (preVisit)
1419 ++sequenceDepth;
1420 else
1421 --sequenceDepth;
1422
1423 if (sequenceDepth == 1) {
1424 // If this is the parent node of all the functions, we want to see them
1425 // early, so all call points have actual SPIR-V functions to reference.
1426 // In all cases, still let the traverser visit the children for us.
1427 makeFunctions(node->getAsAggregate()->getSequence());
1428
John Kessenich6fccb3c2016-09-19 16:01:41 -06001429 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001430 // anything else gets there, so visit out of order, doing them all now.
1431 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1432
John Kessenich6a60c2f2016-12-08 21:01:59 -07001433 // 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 -06001434 // so do them manually.
1435 visitFunctions(node->getAsAggregate()->getSequence());
1436
1437 return false;
1438 }
1439
1440 return true;
1441 }
1442 case glslang::EOpLinkerObjects:
1443 {
1444 if (visit == glslang::EvPreVisit)
1445 linkageOnly = true;
1446 else
1447 linkageOnly = false;
1448
1449 return true;
1450 }
1451 case glslang::EOpComma:
1452 {
1453 // processing from left to right naturally leaves the right-most
1454 // lying around in the access chain
1455 glslang::TIntermSequence& glslangOperands = node->getSequence();
1456 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1457 glslangOperands[i]->traverse(this);
1458
1459 return false;
1460 }
1461 case glslang::EOpFunction:
1462 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001463 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001464 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001465 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001466 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001467 } else {
1468 handleFunctionEntry(node);
1469 }
1470 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001471 if (inEntryPoint)
1472 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001473 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001474 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001475 }
1476
1477 return true;
1478 case glslang::EOpParameters:
1479 // Parameters will have been consumed by EOpFunction processing, but not
1480 // the body, so we still visited the function node's children, making this
1481 // child redundant.
1482 return false;
1483 case glslang::EOpFunctionCall:
1484 {
1485 if (node->isUserDefined())
1486 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001487 // 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 -07001488 if (result) {
1489 builder.clearAccessChain();
1490 builder.setAccessChainRValue(result);
1491 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001492 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001493
1494 return false;
1495 }
1496 case glslang::EOpConstructMat2x2:
1497 case glslang::EOpConstructMat2x3:
1498 case glslang::EOpConstructMat2x4:
1499 case glslang::EOpConstructMat3x2:
1500 case glslang::EOpConstructMat3x3:
1501 case glslang::EOpConstructMat3x4:
1502 case glslang::EOpConstructMat4x2:
1503 case glslang::EOpConstructMat4x3:
1504 case glslang::EOpConstructMat4x4:
1505 case glslang::EOpConstructDMat2x2:
1506 case glslang::EOpConstructDMat2x3:
1507 case glslang::EOpConstructDMat2x4:
1508 case glslang::EOpConstructDMat3x2:
1509 case glslang::EOpConstructDMat3x3:
1510 case glslang::EOpConstructDMat3x4:
1511 case glslang::EOpConstructDMat4x2:
1512 case glslang::EOpConstructDMat4x3:
1513 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001514#ifdef AMD_EXTENSIONS
1515 case glslang::EOpConstructF16Mat2x2:
1516 case glslang::EOpConstructF16Mat2x3:
1517 case glslang::EOpConstructF16Mat2x4:
1518 case glslang::EOpConstructF16Mat3x2:
1519 case glslang::EOpConstructF16Mat3x3:
1520 case glslang::EOpConstructF16Mat3x4:
1521 case glslang::EOpConstructF16Mat4x2:
1522 case glslang::EOpConstructF16Mat4x3:
1523 case glslang::EOpConstructF16Mat4x4:
1524#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001525 isMatrix = true;
1526 // fall through
1527 case glslang::EOpConstructFloat:
1528 case glslang::EOpConstructVec2:
1529 case glslang::EOpConstructVec3:
1530 case glslang::EOpConstructVec4:
1531 case glslang::EOpConstructDouble:
1532 case glslang::EOpConstructDVec2:
1533 case glslang::EOpConstructDVec3:
1534 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001535#ifdef AMD_EXTENSIONS
1536 case glslang::EOpConstructFloat16:
1537 case glslang::EOpConstructF16Vec2:
1538 case glslang::EOpConstructF16Vec3:
1539 case glslang::EOpConstructF16Vec4:
1540#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001541 case glslang::EOpConstructBool:
1542 case glslang::EOpConstructBVec2:
1543 case glslang::EOpConstructBVec3:
1544 case glslang::EOpConstructBVec4:
1545 case glslang::EOpConstructInt:
1546 case glslang::EOpConstructIVec2:
1547 case glslang::EOpConstructIVec3:
1548 case glslang::EOpConstructIVec4:
1549 case glslang::EOpConstructUint:
1550 case glslang::EOpConstructUVec2:
1551 case glslang::EOpConstructUVec3:
1552 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001553 case glslang::EOpConstructInt64:
1554 case glslang::EOpConstructI64Vec2:
1555 case glslang::EOpConstructI64Vec3:
1556 case glslang::EOpConstructI64Vec4:
1557 case glslang::EOpConstructUint64:
1558 case glslang::EOpConstructU64Vec2:
1559 case glslang::EOpConstructU64Vec3:
1560 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001561 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001562 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001563 {
1564 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001565 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001566 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001567 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001568 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001569 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001570 std::vector<spv::Id> constituents;
1571 for (int c = 0; c < (int)arguments.size(); ++c)
1572 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001573 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001574 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001575 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001576 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001577 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001578
1579 builder.clearAccessChain();
1580 builder.setAccessChainRValue(constructed);
1581
1582 return false;
1583 }
1584
1585 // These six are component-wise compares with component-wise results.
1586 // Forward on to createBinaryOperation(), requesting a vector result.
1587 case glslang::EOpLessThan:
1588 case glslang::EOpGreaterThan:
1589 case glslang::EOpLessThanEqual:
1590 case glslang::EOpGreaterThanEqual:
1591 case glslang::EOpVectorEqual:
1592 case glslang::EOpVectorNotEqual:
1593 {
1594 // Map the operation to a binary
1595 binOp = node->getOp();
1596 reduceComparison = false;
1597 switch (node->getOp()) {
1598 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1599 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1600 default: binOp = node->getOp(); break;
1601 }
1602
1603 break;
1604 }
1605 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001606 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001607 binOp = glslang::EOpMul;
1608 break;
1609 case glslang::EOpOuterProduct:
1610 // two vectors multiplied to make a matrix
1611 binOp = glslang::EOpOuterProduct;
1612 break;
1613 case glslang::EOpDot:
1614 {
qining25262b32016-05-06 17:25:16 -04001615 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001616 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001617 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001618 binOp = glslang::EOpMul;
1619 break;
1620 }
1621 case glslang::EOpMod:
1622 // when an aggregate, this is the floating-point mod built-in function,
1623 // which can be emitted by the one in createBinaryOperation()
1624 binOp = glslang::EOpMod;
1625 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001626 case glslang::EOpEmitVertex:
1627 case glslang::EOpEndPrimitive:
1628 case glslang::EOpBarrier:
1629 case glslang::EOpMemoryBarrier:
1630 case glslang::EOpMemoryBarrierAtomicCounter:
1631 case glslang::EOpMemoryBarrierBuffer:
1632 case glslang::EOpMemoryBarrierImage:
1633 case glslang::EOpMemoryBarrierShared:
1634 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001635 case glslang::EOpAllMemoryBarrierWithGroupSync:
1636 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1637 case glslang::EOpWorkgroupMemoryBarrier:
1638 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001639 noReturnValue = true;
1640 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1641 break;
1642
John Kessenich426394d2015-07-23 10:22:48 -06001643 case glslang::EOpAtomicAdd:
1644 case glslang::EOpAtomicMin:
1645 case glslang::EOpAtomicMax:
1646 case glslang::EOpAtomicAnd:
1647 case glslang::EOpAtomicOr:
1648 case glslang::EOpAtomicXor:
1649 case glslang::EOpAtomicExchange:
1650 case glslang::EOpAtomicCompSwap:
1651 atomic = true;
1652 break;
1653
John Kessenich140f3df2015-06-26 16:58:36 -06001654 default:
1655 break;
1656 }
1657
1658 //
1659 // See if it maps to a regular operation.
1660 //
John Kessenich140f3df2015-06-26 16:58:36 -06001661 if (binOp != glslang::EOpNull) {
1662 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1663 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1664 assert(left && right);
1665
1666 builder.clearAccessChain();
1667 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001668 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001669
1670 builder.clearAccessChain();
1671 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001672 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001673
qining25262b32016-05-06 17:25:16 -04001674 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001675 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001676 left->getType().getBasicType(), reduceComparison);
1677
1678 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001679 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001680 builder.clearAccessChain();
1681 builder.setAccessChainRValue(result);
1682
1683 return false;
1684 }
1685
John Kessenich426394d2015-07-23 10:22:48 -06001686 //
1687 // Create the list of operands.
1688 //
John Kessenich140f3df2015-06-26 16:58:36 -06001689 glslang::TIntermSequence& glslangOperands = node->getSequence();
1690 std::vector<spv::Id> operands;
1691 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001692 // special case l-value operands; there are just a few
1693 bool lvalue = false;
1694 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001695 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001696 case glslang::EOpModf:
1697 if (arg == 1)
1698 lvalue = true;
1699 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001700 case glslang::EOpInterpolateAtSample:
1701 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001702#ifdef AMD_EXTENSIONS
1703 case glslang::EOpInterpolateAtVertex:
1704#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001705 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001706 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001707
1708 // Does it need a swizzle inversion? If so, evaluation is inverted;
1709 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001710 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001711 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1712 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1713 }
Rex Xu7a26c172015-12-08 17:12:09 +08001714 break;
Rex Xud4782c12015-09-06 16:30:11 +08001715 case glslang::EOpAtomicAdd:
1716 case glslang::EOpAtomicMin:
1717 case glslang::EOpAtomicMax:
1718 case glslang::EOpAtomicAnd:
1719 case glslang::EOpAtomicOr:
1720 case glslang::EOpAtomicXor:
1721 case glslang::EOpAtomicExchange:
1722 case glslang::EOpAtomicCompSwap:
1723 if (arg == 0)
1724 lvalue = true;
1725 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001726 case glslang::EOpAddCarry:
1727 case glslang::EOpSubBorrow:
1728 if (arg == 2)
1729 lvalue = true;
1730 break;
1731 case glslang::EOpUMulExtended:
1732 case glslang::EOpIMulExtended:
1733 if (arg >= 2)
1734 lvalue = true;
1735 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001736 default:
1737 break;
1738 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001739 builder.clearAccessChain();
1740 if (invertedType != spv::NoType && arg == 0)
1741 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1742 else
1743 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001744 if (lvalue)
1745 operands.push_back(builder.accessChainGetLValue());
1746 else
John Kessenich32cfd492016-02-02 12:37:46 -07001747 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001748 }
John Kessenich426394d2015-07-23 10:22:48 -06001749
1750 if (atomic) {
1751 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001752 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001753 } else {
1754 // Pass through to generic operations.
1755 switch (glslangOperands.size()) {
1756 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001757 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001758 break;
1759 case 1:
qining25262b32016-05-06 17:25:16 -04001760 result = createUnaryOperation(
1761 node->getOp(), precision,
1762 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001763 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001764 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001765 break;
1766 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001767 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001768 break;
1769 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001770 if (invertedType)
1771 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001772 }
1773
1774 if (noReturnValue)
1775 return false;
1776
1777 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001778 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001779 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001780 } else {
1781 builder.clearAccessChain();
1782 builder.setAccessChainRValue(result);
1783 return false;
1784 }
1785}
1786
John Kessenich433e9ff2017-01-26 20:31:11 -07001787// This path handles both if-then-else and ?:
1788// The if-then-else has a node type of void, while
1789// ?: has either a void or a non-void node type
1790//
1791// Leaving the result, when not void:
1792// GLSL only has r-values as the result of a :?, but
1793// if we have an l-value, that can be more efficient if it will
1794// become the base of a complex r-value expression, because the
1795// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001796bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1797{
John Kessenich433e9ff2017-01-26 20:31:11 -07001798 // See if it simple and safe to generate OpSelect instead of using control flow.
1799 // Crucially, side effects must be avoided, and there are performance trade-offs.
1800 // Return true if good idea (and safe) for OpSelect, false otherwise.
1801 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001802 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1803 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001804 return false;
1805
1806 if (node->getTrueBlock() == nullptr ||
1807 node->getFalseBlock() == nullptr)
1808 return false;
1809
1810 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1811 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1812
1813 // return true if a single operand to ? : is okay for OpSelect
1814 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001815 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001816 };
1817
1818 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1819 operandOkay(node->getFalseBlock()->getAsTyped());
1820 };
1821
1822 // Emit OpSelect for this selection.
1823 const auto handleAsOpSelect = [&]() {
1824 node->getCondition()->traverse(this);
1825 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1826 node->getTrueBlock()->traverse(this);
1827 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1828 node->getFalseBlock()->traverse(this);
1829 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1830
John Kesseniche434ad92017-03-30 10:09:28 -06001831 // smear condition to vector, if necessary (AST is always scalar)
1832 if (builder.isVector(trueValue))
1833 condition = builder.smearScalar(spv::NoPrecision, condition,
1834 builder.makeVectorType(builder.makeBoolType(),
1835 builder.getNumComponents(trueValue)));
1836
1837 spv::Id select = builder.createTriOp(spv::OpSelect,
1838 convertGlslangToSpvType(node->getType()), condition,
1839 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001840 builder.clearAccessChain();
1841 builder.setAccessChainRValue(select);
1842 };
1843
1844 // Try for OpSelect
1845
1846 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001847 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1848 if (node->getType().getQualifier().isSpecConstant())
1849 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1850
John Kessenich433e9ff2017-01-26 20:31:11 -07001851 handleAsOpSelect();
1852 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001853 }
1854
John Kessenich433e9ff2017-01-26 20:31:11 -07001855 // Instead, emit control flow...
1856
1857 // Don't handle results as temporaries, because there will be two names
1858 // and better to leave SSA to later passes.
1859 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1860 ? spv::NoResult
1861 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1862
John Kessenich140f3df2015-06-26 16:58:36 -06001863 // emit the condition before doing anything with selection
1864 node->getCondition()->traverse(this);
1865
1866 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001867 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001868
John Kessenich433e9ff2017-01-26 20:31:11 -07001869 // emit the "then" statement
1870 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001871 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001872 if (result != spv::NoResult)
1873 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001874 }
1875
John Kessenich433e9ff2017-01-26 20:31:11 -07001876 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001877 ifBuilder.makeBeginElse();
1878 // emit the "else" statement
1879 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001880 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001881 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001882 }
1883
John Kessenich433e9ff2017-01-26 20:31:11 -07001884 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001885 ifBuilder.makeEndIf();
1886
John Kessenich433e9ff2017-01-26 20:31:11 -07001887 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001888 // GLSL only has r-values as the result of a :?, but
1889 // if we have an l-value, that can be more efficient if it will
1890 // become the base of a complex r-value expression, because the
1891 // next layer copies r-values into memory to use the access-chain mechanism
1892 builder.clearAccessChain();
1893 builder.setAccessChainLValue(result);
1894 }
1895
1896 return false;
1897}
1898
1899bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1900{
1901 // emit and get the condition before doing anything with switch
1902 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001903 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001904
1905 // browse the children to sort out code segments
1906 int defaultSegment = -1;
1907 std::vector<TIntermNode*> codeSegments;
1908 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1909 std::vector<int> caseValues;
1910 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1911 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1912 TIntermNode* child = *c;
1913 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001914 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001915 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001916 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001917 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1918 } else
1919 codeSegments.push_back(child);
1920 }
1921
qining25262b32016-05-06 17:25:16 -04001922 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001923 // statements between the last case and the end of the switch statement
1924 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1925 (int)codeSegments.size() == defaultSegment)
1926 codeSegments.push_back(nullptr);
1927
1928 // make the switch statement
1929 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001930 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001931
1932 // emit all the code in the segments
1933 breakForLoop.push(false);
1934 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1935 builder.nextSwitchSegment(segmentBlocks, s);
1936 if (codeSegments[s])
1937 codeSegments[s]->traverse(this);
1938 else
1939 builder.addSwitchBreak();
1940 }
1941 breakForLoop.pop();
1942
1943 builder.endSwitch(segmentBlocks);
1944
1945 return false;
1946}
1947
1948void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1949{
1950 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001951 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001952
1953 builder.clearAccessChain();
1954 builder.setAccessChainRValue(constant);
1955}
1956
1957bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1958{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001959 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001960 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001961 // Spec requires back edges to target header blocks, and every header block
1962 // must dominate its merge block. Make a header block first to ensure these
1963 // conditions are met. By definition, it will contain OpLoopMerge, followed
1964 // by a block-ending branch. But we don't want to put any other body/test
1965 // instructions in it, since the body/test may have arbitrary instructions,
1966 // including merges of its own.
1967 builder.setBuildPoint(&blocks.head);
1968 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001969 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001970 spv::Block& test = builder.makeNewBlock();
1971 builder.createBranch(&test);
1972
1973 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001974 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001975 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001976 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001977 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1978
1979 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001980 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001981 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001982 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001983 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001984 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001985
1986 builder.setBuildPoint(&blocks.continue_target);
1987 if (node->getTerminal())
1988 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001989 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001990 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001991 builder.createBranch(&blocks.body);
1992
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001993 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001994 builder.setBuildPoint(&blocks.body);
1995 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001996 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001997 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001998 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001999
2000 builder.setBuildPoint(&blocks.continue_target);
2001 if (node->getTerminal())
2002 node->getTerminal()->traverse(this);
2003 if (node->getTest()) {
2004 node->getTest()->traverse(this);
2005 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002006 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002007 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002008 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002009 // TODO: unless there was a break/return/discard instruction
2010 // somewhere in the body, this is an infinite loop, so we should
2011 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002012 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002013 }
John Kessenich140f3df2015-06-26 16:58:36 -06002014 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002015 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002016 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002017 return false;
2018}
2019
2020bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2021{
2022 if (node->getExpression())
2023 node->getExpression()->traverse(this);
2024
2025 switch (node->getFlowOp()) {
2026 case glslang::EOpKill:
2027 builder.makeDiscard();
2028 break;
2029 case glslang::EOpBreak:
2030 if (breakForLoop.top())
2031 builder.createLoopExit();
2032 else
2033 builder.addSwitchBreak();
2034 break;
2035 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002036 builder.createLoopContinue();
2037 break;
2038 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002039 if (node->getExpression()) {
2040 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2041 spv::Id returnId = accessChainLoad(glslangReturnType);
2042 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2043 builder.clearAccessChain();
2044 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2045 builder.setAccessChainLValue(copyId);
2046 multiTypeStore(glslangReturnType, returnId);
2047 returnId = builder.createLoad(copyId);
2048 }
2049 builder.makeReturn(false, returnId);
2050 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002051 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002052
2053 builder.clearAccessChain();
2054 break;
2055
2056 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002057 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002058 break;
2059 }
2060
2061 return false;
2062}
2063
2064spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2065{
qining25262b32016-05-06 17:25:16 -04002066 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002067 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002068 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002069 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002070 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002071 }
2072
2073 // Now, handle actual variables
2074 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
2075 spv::Id spvType = convertGlslangToSpvType(node->getType());
2076
Rex Xuf89ad982017-04-07 23:22:33 +08002077#ifdef AMD_EXTENSIONS
2078 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16);
2079 if (contains16BitType) {
2080 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2081 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2082 builder.addCapability(spv::CapabilityStorageInputOutput16);
2083 } else if (storageClass == spv::StorageClassPushConstant) {
2084 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2085 builder.addCapability(spv::CapabilityStoragePushConstant16);
2086 } else if (storageClass == spv::StorageClassUniform) {
2087 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2088 builder.addCapability(spv::CapabilityStorageUniform16);
2089 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2090 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2091 }
2092 }
2093#endif
2094
John Kessenich140f3df2015-06-26 16:58:36 -06002095 const char* name = node->getName().c_str();
2096 if (glslang::IsAnonymous(name))
2097 name = "";
2098
2099 return builder.createVariable(storageClass, spvType, name);
2100}
2101
2102// Return type Id of the sampled type.
2103spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2104{
2105 switch (sampler.type) {
2106 case glslang::EbtFloat: return builder.makeFloatType(32);
2107 case glslang::EbtInt: return builder.makeIntType(32);
2108 case glslang::EbtUint: return builder.makeUintType(32);
2109 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002110 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002111 return builder.makeFloatType(32);
2112 }
2113}
2114
John Kessenich8c8505c2016-07-26 12:50:38 -06002115// If node is a swizzle operation, return the type that should be used if
2116// the swizzle base is first consumed by another operation, before the swizzle
2117// is applied.
2118spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2119{
John Kessenichecba76f2017-01-06 00:34:48 -07002120 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002121 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2122 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2123 else
2124 return spv::NoType;
2125}
2126
2127// When inverting a swizzle with a parent op, this function
2128// will apply the swizzle operation to a completed parent operation.
2129spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2130{
2131 std::vector<unsigned> swizzle;
2132 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2133 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2134}
2135
John Kessenich8c8505c2016-07-26 12:50:38 -06002136// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2137void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2138{
2139 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2140 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2141 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2142}
2143
John Kessenich3ac051e2015-12-20 11:29:16 -07002144// Convert from a glslang type to an SPV type, by calling into a
2145// recursive version of this function. This establishes the inherited
2146// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002147spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2148{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002149 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002150}
2151
2152// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002153// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002154// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002155spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002156{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002157 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002158
2159 switch (type.getBasicType()) {
2160 case glslang::EbtVoid:
2161 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002162 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002163 break;
2164 case glslang::EbtFloat:
2165 spvType = builder.makeFloatType(32);
2166 break;
2167 case glslang::EbtDouble:
2168 spvType = builder.makeFloatType(64);
2169 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002170#ifdef AMD_EXTENSIONS
2171 case glslang::EbtFloat16:
2172 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002173 spvType = builder.makeFloatType(16);
2174 break;
2175#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002176 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002177 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2178 // a 32-bit int where non-0 means true.
2179 if (explicitLayout != glslang::ElpNone)
2180 spvType = builder.makeUintType(32);
2181 else
2182 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002183 break;
2184 case glslang::EbtInt:
2185 spvType = builder.makeIntType(32);
2186 break;
2187 case glslang::EbtUint:
2188 spvType = builder.makeUintType(32);
2189 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002190 case glslang::EbtInt64:
2191 builder.addCapability(spv::CapabilityInt64);
2192 spvType = builder.makeIntType(64);
2193 break;
2194 case glslang::EbtUint64:
2195 builder.addCapability(spv::CapabilityInt64);
2196 spvType = builder.makeUintType(64);
2197 break;
John Kessenich426394d2015-07-23 10:22:48 -06002198 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002199 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002200 spvType = builder.makeUintType(32);
2201 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002202 case glslang::EbtSampler:
2203 {
2204 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002205 if (sampler.sampler) {
2206 // pure sampler
2207 spvType = builder.makeSamplerType();
2208 } else {
2209 // an image is present, make its type
2210 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2211 sampler.image ? 2 : 1, TranslateImageFormat(type));
2212 if (sampler.combined) {
2213 // already has both image and sampler, make the combined type
2214 spvType = builder.makeSampledImageType(spvType);
2215 }
John Kessenich55e7d112015-11-15 21:33:39 -07002216 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002217 }
John Kessenich140f3df2015-06-26 16:58:36 -06002218 break;
2219 case glslang::EbtStruct:
2220 case glslang::EbtBlock:
2221 {
2222 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002223 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002224
2225 // Try to share structs for different layouts, but not yet for other
2226 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002227 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002228 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002229 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002230 break;
2231
2232 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002233 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002234 memberRemapper[glslangMembers].resize(glslangMembers->size());
2235 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002236 }
2237 break;
2238 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002239 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002240 break;
2241 }
2242
2243 if (type.isMatrix())
2244 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2245 else {
2246 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2247 if (type.getVectorSize() > 1)
2248 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2249 }
2250
2251 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002252 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2253
John Kessenichc9a80832015-09-12 12:17:44 -06002254 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002255 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002256 // We need to decorate array strides for types needing explicit layout, except blocks.
2257 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002258 // Use a dummy glslang type for querying internal strides of
2259 // arrays of arrays, but using just a one-dimensional array.
2260 glslang::TType simpleArrayType(type, 0); // deference type of the array
2261 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2262 simpleArrayType.getArraySizes().dereference();
2263
2264 // Will compute the higher-order strides here, rather than making a whole
2265 // pile of types and doing repetitive recursion on their contents.
2266 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2267 }
John Kessenichf8842e52016-01-04 19:22:56 -07002268
2269 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002270 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002271 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002272 if (stride > 0)
2273 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002274 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002275 }
2276 } else {
2277 // single-dimensional array, and don't yet have stride
2278
John Kessenichf8842e52016-01-04 19:22:56 -07002279 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002280 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2281 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002282 }
John Kessenich31ed4832015-09-09 17:51:38 -06002283
John Kessenichc9a80832015-09-12 12:17:44 -06002284 // Do the outer dimension, which might not be known for a runtime-sized array
2285 if (type.isRuntimeSizedArray()) {
2286 spvType = builder.makeRuntimeArray(spvType);
2287 } else {
2288 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002289 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002290 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002291 if (stride > 0)
2292 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002293 }
2294
2295 return spvType;
2296}
2297
John Kessenich0e737842017-03-24 18:38:16 -06002298// TODO: this functionality should exist at a higher level, in creating the AST
2299//
2300// Identify interface members that don't have their required extension turned on.
2301//
2302bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2303{
2304 auto& extensions = glslangIntermediate->getRequestedExtensions();
2305
Rex Xubcf291a2017-03-29 23:01:36 +08002306 if (member.getFieldName() == "gl_ViewportMask" &&
2307 extensions.find("GL_NV_viewport_array2") == extensions.end())
2308 return true;
2309 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2310 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2311 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002312 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2313 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2314 return true;
2315 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2316 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2317 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002318 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2319 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2320 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002321
2322 return false;
2323};
2324
John Kessenich6090df02016-06-30 21:18:02 -06002325// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2326// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2327// Mutually recursive with convertGlslangToSpvType().
2328spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2329 const glslang::TTypeList* glslangMembers,
2330 glslang::TLayoutPacking explicitLayout,
2331 const glslang::TQualifier& qualifier)
2332{
2333 // Create a vector of struct types for SPIR-V to consume
2334 std::vector<spv::Id> spvMembers;
2335 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2336 int locationOffset = 0; // for use across struct members, when they are called recursively
2337 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2338 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2339 if (glslangMember.hiddenMember()) {
2340 ++memberDelta;
2341 if (type.getBasicType() == glslang::EbtBlock)
2342 memberRemapper[glslangMembers][i] = -1;
2343 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002344 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002345 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002346 if (filterMember(glslangMember))
2347 continue;
2348 }
John Kessenich6090df02016-06-30 21:18:02 -06002349 // modify just this child's view of the qualifier
2350 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2351 InheritQualifiers(memberQualifier, qualifier);
2352
2353 // manually inherit location; it's more complex
2354 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2355 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2356 if (qualifier.hasLocation())
2357 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2358
2359 // recurse
2360 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2361 }
2362 }
2363
2364 // Make the SPIR-V type
2365 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002366 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002367 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2368
2369 // Decorate it
2370 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2371
2372 return spvType;
2373}
2374
2375void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2376 const glslang::TTypeList* glslangMembers,
2377 glslang::TLayoutPacking explicitLayout,
2378 const glslang::TQualifier& qualifier,
2379 spv::Id spvType)
2380{
2381 // Name and decorate the non-hidden members
2382 int offset = -1;
2383 int locationOffset = 0; // for use within the members of this struct
2384 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2385 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2386 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002387 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002388 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002389 if (filterMember(glslangMember))
2390 continue;
2391 }
John Kessenich6090df02016-06-30 21:18:02 -06002392
2393 // modify just this child's view of the qualifier
2394 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2395 InheritQualifiers(memberQualifier, qualifier);
2396
2397 // using -1 above to indicate a hidden member
2398 if (member >= 0) {
2399 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2400 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2401 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2402 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002403 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2404 type.getQualifier().storage == glslang::EvqVaryingOut) {
2405 if (type.getBasicType() == glslang::EbtBlock ||
2406 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002407 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2408 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2409 }
2410 }
2411 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2412
2413 if (qualifier.storage == glslang::EvqBuffer) {
2414 std::vector<spv::Decoration> memory;
2415 TranslateMemoryDecoration(memberQualifier, memory);
2416 for (unsigned int i = 0; i < memory.size(); ++i)
2417 addMemberDecoration(spvType, member, memory[i]);
2418 }
2419
John Kessenich2f47bc92016-06-30 21:47:35 -06002420 // Compute location decoration; tricky based on whether inheritance is at play and
2421 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002422 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2423 // probably move to the linker stage of the front end proper, and just have the
2424 // answer sitting already distributed throughout the individual member locations.
2425 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002426 // Ignore member locations if the container is an array, as that's
2427 // ill-specified and decisions have been made to not allow this anyway.
2428 // The object itself must have a location, and that comes out from decorating the object,
2429 // not the type (this code decorates types).
2430 if (! type.isArray()) {
2431 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2432 // struct members should not have explicit locations
2433 assert(type.getBasicType() != glslang::EbtStruct);
2434 location = memberQualifier.layoutLocation;
2435 } else if (type.getBasicType() != glslang::EbtBlock) {
2436 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2437 // The members, and their nested types, must not themselves have Location decorations.
2438 } else if (qualifier.hasLocation()) // inheritance
2439 location = qualifier.layoutLocation + locationOffset;
2440 }
John Kessenich6090df02016-06-30 21:18:02 -06002441 if (location >= 0)
2442 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2443
John Kessenich2f47bc92016-06-30 21:47:35 -06002444 if (qualifier.hasLocation()) // track for upcoming inheritance
2445 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2446
John Kessenich6090df02016-06-30 21:18:02 -06002447 // component, XFB, others
2448 if (glslangMember.getQualifier().hasComponent())
2449 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2450 if (glslangMember.getQualifier().hasXfbOffset())
2451 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2452 else if (explicitLayout != glslang::ElpNone) {
2453 // figure out what to do with offset, which is accumulating
2454 int nextOffset;
2455 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2456 if (offset >= 0)
2457 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2458 offset = nextOffset;
2459 }
2460
2461 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2462 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2463
2464 // built-in variable decorations
2465 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002466 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002467 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002468
2469#ifdef NV_EXTENSIONS
2470 if (builtIn == spv::BuiltInLayer) {
2471 // SPV_NV_viewport_array2 extension
2472 if (glslangMember.getQualifier().layoutViewportRelative){
2473 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2474 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2475 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2476 }
2477 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2478 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2479 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2480 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2481 }
2482 }
chaocdf3956c2017-02-14 14:52:34 -08002483 if (glslangMember.getQualifier().layoutPassthrough) {
2484 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2485 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2486 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2487 }
chaoc771d89f2017-01-13 01:10:53 -08002488#endif
John Kessenich6090df02016-06-30 21:18:02 -06002489 }
2490 }
2491
2492 // Decorate the structure
2493 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2494 addDecoration(spvType, TranslateBlockDecoration(type));
2495 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2496 builder.addCapability(spv::CapabilityGeometryStreams);
2497 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2498 }
2499 if (glslangIntermediate->getXfbMode()) {
2500 builder.addCapability(spv::CapabilityTransformFeedback);
2501 if (type.getQualifier().hasXfbStride())
2502 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2503 if (type.getQualifier().hasXfbBuffer())
2504 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2505 }
2506}
2507
John Kessenich6c292d32016-02-15 20:58:50 -07002508// Turn the expression forming the array size into an id.
2509// This is not quite trivial, because of specialization constants.
2510// Sometimes, a raw constant is turned into an Id, and sometimes
2511// a specialization constant expression is.
2512spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2513{
2514 // First, see if this is sized with a node, meaning a specialization constant:
2515 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2516 if (specNode != nullptr) {
2517 builder.clearAccessChain();
2518 specNode->traverse(this);
2519 return accessChainLoad(specNode->getAsTyped()->getType());
2520 }
qining25262b32016-05-06 17:25:16 -04002521
John Kessenich6c292d32016-02-15 20:58:50 -07002522 // Otherwise, need a compile-time (front end) size, get it:
2523 int size = arraySizes.getDimSize(dim);
2524 assert(size > 0);
2525 return builder.makeUintConstant(size);
2526}
2527
John Kessenich103bef92016-02-08 21:38:15 -07002528// Wrap the builder's accessChainLoad to:
2529// - localize handling of RelaxedPrecision
2530// - use the SPIR-V inferred type instead of another conversion of the glslang type
2531// (avoids unnecessary work and possible type punning for structures)
2532// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002533spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2534{
John Kessenich103bef92016-02-08 21:38:15 -07002535 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2536 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2537
2538 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002539 if (type.getBasicType() == glslang::EbtBool) {
2540 if (builder.isScalarType(nominalTypeId)) {
2541 // Conversion for bool
2542 spv::Id boolType = builder.makeBoolType();
2543 if (nominalTypeId != boolType)
2544 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2545 } else if (builder.isVectorType(nominalTypeId)) {
2546 // Conversion for bvec
2547 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2548 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2549 if (nominalTypeId != bvecType)
2550 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2551 }
2552 }
John Kessenich103bef92016-02-08 21:38:15 -07002553
2554 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002555}
2556
Rex Xu27253232016-02-23 17:51:09 +08002557// Wrap the builder's accessChainStore to:
2558// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002559//
2560// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002561void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2562{
2563 // Need to convert to abstract types when necessary
2564 if (type.getBasicType() == glslang::EbtBool) {
2565 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2566
2567 if (builder.isScalarType(nominalTypeId)) {
2568 // Conversion for bool
2569 spv::Id boolType = builder.makeBoolType();
2570 if (nominalTypeId != boolType) {
2571 spv::Id zero = builder.makeUintConstant(0);
2572 spv::Id one = builder.makeUintConstant(1);
2573 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2574 }
2575 } else if (builder.isVectorType(nominalTypeId)) {
2576 // Conversion for bvec
2577 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2578 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2579 if (nominalTypeId != bvecType) {
2580 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2581 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2582 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2583 }
2584 }
2585 }
2586
2587 builder.accessChainStore(rvalue);
2588}
2589
John Kessenich4bf71552016-09-02 11:20:21 -06002590// For storing when types match at the glslang level, but not might match at the
2591// SPIR-V level.
2592//
2593// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002594// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002595// as in a member-decorated way.
2596//
2597// NOTE: This function can handle any store request; if it's not special it
2598// simplifies to a simple OpStore.
2599//
2600// Implicitly uses the existing builder.accessChain as the storage target.
2601void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2602{
John Kessenichb3e24e42016-09-11 12:33:43 -06002603 // we only do the complex path here if it's an aggregate
2604 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002605 accessChainStore(type, rValue);
2606 return;
2607 }
2608
John Kessenichb3e24e42016-09-11 12:33:43 -06002609 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002610 spv::Id rType = builder.getTypeId(rValue);
2611 spv::Id lValue = builder.accessChainGetLValue();
2612 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2613 if (lType == rType) {
2614 accessChainStore(type, rValue);
2615 return;
2616 }
2617
John Kessenichb3e24e42016-09-11 12:33:43 -06002618 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002619 // where the two types were the same type in GLSL. This requires member
2620 // by member copy, recursively.
2621
John Kessenichb3e24e42016-09-11 12:33:43 -06002622 // If an array, copy element by element.
2623 if (type.isArray()) {
2624 glslang::TType glslangElementType(type, 0);
2625 spv::Id elementRType = builder.getContainedTypeId(rType);
2626 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2627 // get the source member
2628 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002629
John Kessenichb3e24e42016-09-11 12:33:43 -06002630 // set up the target storage
2631 builder.clearAccessChain();
2632 builder.setAccessChainLValue(lValue);
2633 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002634
John Kessenichb3e24e42016-09-11 12:33:43 -06002635 // store the member
2636 multiTypeStore(glslangElementType, elementRValue);
2637 }
2638 } else {
2639 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002640
John Kessenichb3e24e42016-09-11 12:33:43 -06002641 // loop over structure members
2642 const glslang::TTypeList& members = *type.getStruct();
2643 for (int m = 0; m < (int)members.size(); ++m) {
2644 const glslang::TType& glslangMemberType = *members[m].type;
2645
2646 // get the source member
2647 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2648 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2649
2650 // set up the target storage
2651 builder.clearAccessChain();
2652 builder.setAccessChainLValue(lValue);
2653 builder.accessChainPush(builder.makeIntConstant(m));
2654
2655 // store the member
2656 multiTypeStore(glslangMemberType, memberRValue);
2657 }
John Kessenich4bf71552016-09-02 11:20:21 -06002658 }
2659}
2660
John Kessenichf85e8062015-12-19 13:57:10 -07002661// Decide whether or not this type should be
2662// decorated with offsets and strides, and if so
2663// whether std140 or std430 rules should be applied.
2664glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002665{
John Kessenichf85e8062015-12-19 13:57:10 -07002666 // has to be a block
2667 if (type.getBasicType() != glslang::EbtBlock)
2668 return glslang::ElpNone;
2669
2670 // has to be a uniform or buffer block
2671 if (type.getQualifier().storage != glslang::EvqUniform &&
2672 type.getQualifier().storage != glslang::EvqBuffer)
2673 return glslang::ElpNone;
2674
2675 // return the layout to use
2676 switch (type.getQualifier().layoutPacking) {
2677 case glslang::ElpStd140:
2678 case glslang::ElpStd430:
2679 return type.getQualifier().layoutPacking;
2680 default:
2681 return glslang::ElpNone;
2682 }
John Kessenich31ed4832015-09-09 17:51:38 -06002683}
2684
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002685// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002686int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002687{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002688 int size;
John Kessenich49987892015-12-29 17:11:44 -07002689 int stride;
2690 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002691
2692 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002693}
2694
John Kessenich49987892015-12-29 17:11:44 -07002695// 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 -07002696// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002697int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002698{
John Kessenich49987892015-12-29 17:11:44 -07002699 glslang::TType elementType;
2700 elementType.shallowCopy(matrixType);
2701 elementType.clearArraySizes();
2702
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002703 int size;
John Kessenich49987892015-12-29 17:11:44 -07002704 int stride;
2705 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2706
2707 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002708}
2709
John Kessenich5e4b1242015-08-06 22:53:06 -06002710// Given a member type of a struct, realign the current offset for it, and compute
2711// the next (not yet aligned) offset for the next member, which will get aligned
2712// on the next call.
2713// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2714// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2715// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002716void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002717 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002718{
2719 // this will get a positive value when deemed necessary
2720 nextOffset = -1;
2721
John Kessenich5e4b1242015-08-06 22:53:06 -06002722 // override anything in currentOffset with user-set offset
2723 if (memberType.getQualifier().hasOffset())
2724 currentOffset = memberType.getQualifier().layoutOffset;
2725
2726 // It could be that current linker usage in glslang updated all the layoutOffset,
2727 // in which case the following code does not matter. But, that's not quite right
2728 // once cross-compilation unit GLSL validation is done, as the original user
2729 // settings are needed in layoutOffset, and then the following will come into play.
2730
John Kessenichf85e8062015-12-19 13:57:10 -07002731 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002732 if (! memberType.getQualifier().hasOffset())
2733 currentOffset = -1;
2734
2735 return;
2736 }
2737
John Kessenichf85e8062015-12-19 13:57:10 -07002738 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002739 if (currentOffset < 0)
2740 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002741
John Kessenich5e4b1242015-08-06 22:53:06 -06002742 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2743 // but possibly not yet correctly aligned.
2744
2745 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002746 int dummyStride;
2747 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002748
2749 // Adjust alignment for HLSL rules
2750 if (glslangIntermediate->usingHlslOFfsets() &&
2751 ! memberType.isArray() && memberType.isVector()) {
2752 int dummySize;
2753 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2754 if (componentAlignment <= 4)
2755 memberAlignment = componentAlignment;
2756 }
2757
2758 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002759 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002760
2761 // Bump up to vec4 if there is a bad straddle
2762 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2763 glslang::RoundToPow2(currentOffset, 16);
2764
John Kessenich5e4b1242015-08-06 22:53:06 -06002765 nextOffset = currentOffset + memberSize;
2766}
2767
David Netoa901ffe2016-06-08 14:11:40 +01002768void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002769{
David Netoa901ffe2016-06-08 14:11:40 +01002770 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2771 switch (glslangBuiltIn)
2772 {
2773 case glslang::EbvClipDistance:
2774 case glslang::EbvCullDistance:
2775 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002776#ifdef NV_EXTENSIONS
2777 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002778 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002779 case glslang::EbvViewportMaskNV:
2780 case glslang::EbvSecondaryPositionNV:
2781 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002782 case glslang::EbvPositionPerViewNV:
2783 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002784#endif
David Netoa901ffe2016-06-08 14:11:40 +01002785 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2786 // Alternately, we could just call this for any glslang built-in, since the
2787 // capability already guards against duplicates.
2788 TranslateBuiltInDecoration(glslangBuiltIn, false);
2789 break;
2790 default:
2791 // Capabilities were already generated when the struct was declared.
2792 break;
2793 }
John Kessenichebb50532016-05-16 19:22:05 -06002794}
2795
John Kessenich6fccb3c2016-09-19 16:01:41 -06002796bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002797{
John Kessenicheee9d532016-09-19 18:09:30 -06002798 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002799}
2800
2801// Make all the functions, skeletally, without actually visiting their bodies.
2802void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2803{
2804 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2805 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002806 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002807 continue;
2808
2809 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002810 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002811 //
qining25262b32016-05-06 17:25:16 -04002812 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002813 // function. What it is an address of varies:
2814 //
John Kessenich4bf71552016-09-02 11:20:21 -06002815 // - "in" parameters not marked as "const" can be written to without modifying the calling
2816 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002817 //
2818 // - "const in" parameters can just be the r-value, as no writes need occur.
2819 //
John Kessenich4bf71552016-09-02 11:20:21 -06002820 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2821 // 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 -06002822
2823 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002824 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002825 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2826
John Kessenich37789792017-03-21 23:56:40 -06002827 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() == glslangIntermediate->implicitThisName;
2828
John Kessenich140f3df2015-06-26 16:58:36 -06002829 for (int p = 0; p < (int)parameters.size(); ++p) {
2830 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2831 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002832 // can we pass by reference?
2833 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002834 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002835 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002836 (p == 0 && implicitThis)) // implicit 'this'
Jason Ekstranded15ef12016-06-08 13:54:48 -07002837 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2838 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002839 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2840 else
John Kessenich4bf71552016-09-02 11:20:21 -06002841 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002842 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002843 paramTypes.push_back(typeId);
2844 }
2845
2846 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002847 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2848 convertGlslangToSpvType(glslFunction->getType()),
2849 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06002850 if (implicitThis)
2851 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06002852
2853 // Track function to emit/call later
2854 functionMap[glslFunction->getName().c_str()] = function;
2855
2856 // Set the parameter id's
2857 for (int p = 0; p < (int)parameters.size(); ++p) {
2858 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2859 // give a name too
2860 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2861 }
2862 }
2863}
2864
2865// Process all the initializers, while skipping the functions and link objects
2866void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2867{
2868 builder.setBuildPoint(shaderEntry->getLastBlock());
2869 for (int i = 0; i < (int)initializers.size(); ++i) {
2870 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2871 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2872
2873 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002874 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002875 initializer->traverse(this);
2876 }
2877 }
2878}
2879
2880// Process all the functions, while skipping initializers.
2881void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2882{
2883 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2884 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002885 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002886 node->traverse(this);
2887 }
2888}
2889
2890void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2891{
qining25262b32016-05-06 17:25:16 -04002892 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002893 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002894 currentFunction = functionMap[node->getName().c_str()];
2895 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002896 builder.setBuildPoint(functionBlock);
2897}
2898
Rex Xu04db3f52015-09-16 11:44:02 +08002899void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002900{
Rex Xufc618912015-09-09 16:42:49 +08002901 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002902
2903 glslang::TSampler sampler = {};
2904 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002905 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002906 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2907 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2908 }
2909
John Kessenich140f3df2015-06-26 16:58:36 -06002910 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2911 builder.clearAccessChain();
2912 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002913
2914 // Special case l-value operands
2915 bool lvalue = false;
2916 switch (node.getOp()) {
2917 case glslang::EOpImageAtomicAdd:
2918 case glslang::EOpImageAtomicMin:
2919 case glslang::EOpImageAtomicMax:
2920 case glslang::EOpImageAtomicAnd:
2921 case glslang::EOpImageAtomicOr:
2922 case glslang::EOpImageAtomicXor:
2923 case glslang::EOpImageAtomicExchange:
2924 case glslang::EOpImageAtomicCompSwap:
2925 if (i == 0)
2926 lvalue = true;
2927 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002928 case glslang::EOpSparseImageLoad:
2929 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2930 lvalue = true;
2931 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002932 case glslang::EOpSparseTexture:
2933 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2934 lvalue = true;
2935 break;
2936 case glslang::EOpSparseTextureClamp:
2937 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2938 lvalue = true;
2939 break;
2940 case glslang::EOpSparseTextureLod:
2941 case glslang::EOpSparseTextureOffset:
2942 if (i == 3)
2943 lvalue = true;
2944 break;
2945 case glslang::EOpSparseTextureFetch:
2946 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2947 lvalue = true;
2948 break;
2949 case glslang::EOpSparseTextureFetchOffset:
2950 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2951 lvalue = true;
2952 break;
2953 case glslang::EOpSparseTextureLodOffset:
2954 case glslang::EOpSparseTextureGrad:
2955 case glslang::EOpSparseTextureOffsetClamp:
2956 if (i == 4)
2957 lvalue = true;
2958 break;
2959 case glslang::EOpSparseTextureGradOffset:
2960 case glslang::EOpSparseTextureGradClamp:
2961 if (i == 5)
2962 lvalue = true;
2963 break;
2964 case glslang::EOpSparseTextureGradOffsetClamp:
2965 if (i == 6)
2966 lvalue = true;
2967 break;
2968 case glslang::EOpSparseTextureGather:
2969 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2970 lvalue = true;
2971 break;
2972 case glslang::EOpSparseTextureGatherOffset:
2973 case glslang::EOpSparseTextureGatherOffsets:
2974 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2975 lvalue = true;
2976 break;
Rex Xufc618912015-09-09 16:42:49 +08002977 default:
2978 break;
2979 }
2980
Rex Xu6b86d492015-09-16 17:48:22 +08002981 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002982 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002983 else
John Kessenich32cfd492016-02-02 12:37:46 -07002984 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002985 }
2986}
2987
John Kessenichfc51d282015-08-19 13:34:18 -06002988void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002989{
John Kessenichfc51d282015-08-19 13:34:18 -06002990 builder.clearAccessChain();
2991 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002992 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002993}
John Kessenich140f3df2015-06-26 16:58:36 -06002994
John Kessenichfc51d282015-08-19 13:34:18 -06002995spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2996{
Rex Xufc618912015-09-09 16:42:49 +08002997 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002998 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002999 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003000 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003001
John Kessenichfc51d282015-08-19 13:34:18 -06003002 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003003 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3004 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3005 std::vector<spv::Id> arguments;
3006 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003007 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003008 else
3009 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003010 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003011
3012 spv::Builder::TextureParameters params = { };
3013 params.sampler = arguments[0];
3014
Rex Xu04db3f52015-09-16 11:44:02 +08003015 glslang::TCrackedTextureOp cracked;
3016 node->crackTexture(sampler, cracked);
3017
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003018 const bool isUnsignedResult =
3019 node->getType().getBasicType() == glslang::EbtUint64 ||
3020 node->getType().getBasicType() == glslang::EbtUint;
3021
John Kessenichfc51d282015-08-19 13:34:18 -06003022 // Check for queries
3023 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003024 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3025 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003026 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003027
John Kessenichfc51d282015-08-19 13:34:18 -06003028 switch (node->getOp()) {
3029 case glslang::EOpImageQuerySize:
3030 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003031 if (arguments.size() > 1) {
3032 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003033 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003034 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003035 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003036 case glslang::EOpImageQuerySamples:
3037 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003038 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003039 case glslang::EOpTextureQueryLod:
3040 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003041 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003042 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003043 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003044 case glslang::EOpSparseTexelsResident:
3045 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003046 default:
3047 assert(0);
3048 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003049 }
John Kessenich140f3df2015-06-26 16:58:36 -06003050 }
3051
Rex Xufc618912015-09-09 16:42:49 +08003052 // Check for image functions other than queries
3053 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003054 std::vector<spv::Id> operands;
3055 auto opIt = arguments.begin();
3056 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003057
3058 // Handle subpass operations
3059 // TODO: GLSL should change to have the "MS" only on the type rather than the
3060 // built-in function.
3061 if (cracked.subpass) {
3062 // add on the (0,0) coordinate
3063 spv::Id zero = builder.makeIntConstant(0);
3064 std::vector<spv::Id> comps;
3065 comps.push_back(zero);
3066 comps.push_back(zero);
3067 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3068 if (sampler.ms) {
3069 operands.push_back(spv::ImageOperandsSampleMask);
3070 operands.push_back(*(opIt++));
3071 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003072 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003073 }
3074
John Kessenich56bab042015-09-16 10:54:31 -06003075 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003076 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003077 if (sampler.ms) {
3078 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003079 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003080 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003081 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3082 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003083 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003084 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003085 if (sampler.ms) {
3086 operands.push_back(*(opIt + 1));
3087 operands.push_back(spv::ImageOperandsSampleMask);
3088 operands.push_back(*opIt);
3089 } else
3090 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003091 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003092 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3093 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003094 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003095 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3096 builder.addCapability(spv::CapabilitySparseResidency);
3097 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3098 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3099
3100 if (sampler.ms) {
3101 operands.push_back(spv::ImageOperandsSampleMask);
3102 operands.push_back(*opIt++);
3103 }
3104
3105 // Create the return type that was a special structure
3106 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003107 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003108 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3109 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3110
3111 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3112
3113 // Decode the return type
3114 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3115 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003116 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003117 // Process image atomic operations
3118
3119 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3120 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003121 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003122
John Kessenich8c8505c2016-07-26 12:50:38 -06003123 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003124 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003125
3126 std::vector<spv::Id> operands;
3127 operands.push_back(pointer);
3128 for (; opIt != arguments.end(); ++opIt)
3129 operands.push_back(*opIt);
3130
John Kessenich8c8505c2016-07-26 12:50:38 -06003131 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003132 }
3133 }
3134
3135 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003136 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003137 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3138
John Kessenichfc51d282015-08-19 13:34:18 -06003139 // check for bias argument
3140 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003141 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003142 int nonBiasArgCount = 2;
3143 if (cracked.offset)
3144 ++nonBiasArgCount;
3145 if (cracked.grad)
3146 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003147 if (cracked.lodClamp)
3148 ++nonBiasArgCount;
3149 if (sparse)
3150 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003151
3152 if ((int)arguments.size() > nonBiasArgCount)
3153 bias = true;
3154 }
3155
John Kessenicha5c33d62016-06-02 23:45:21 -06003156 // See if the sampler param should really be just the SPV image part
3157 if (cracked.fetch) {
3158 // a fetch needs to have the image extracted first
3159 if (builder.isSampledImage(params.sampler))
3160 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3161 }
3162
John Kessenichfc51d282015-08-19 13:34:18 -06003163 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003164
John Kessenichfc51d282015-08-19 13:34:18 -06003165 params.coords = arguments[1];
3166 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003167 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003168
3169 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003170 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003171 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003172 ++extraArgs;
3173 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003174 params.Dref = arguments[2];
3175 ++extraArgs;
3176 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003177 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003178 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003179 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003180 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003181 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003182 dRefComp = builder.getNumComponents(params.coords) - 1;
3183 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003184 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3185 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003186
3187 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003188 if (cracked.lod) {
3189 params.lod = arguments[2];
3190 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003191 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3192 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3193 noImplicitLod = true;
3194 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003195
3196 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003197 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003198 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003199 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003200 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003201
3202 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003203 if (cracked.grad) {
3204 params.gradX = arguments[2 + extraArgs];
3205 params.gradY = arguments[3 + extraArgs];
3206 extraArgs += 2;
3207 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003208
3209 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003210 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003211 params.offset = arguments[2 + extraArgs];
3212 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003213 } else if (cracked.offsets) {
3214 params.offsets = arguments[2 + extraArgs];
3215 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003216 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003217
3218 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003219 if (cracked.lodClamp) {
3220 params.lodClamp = arguments[2 + extraArgs];
3221 ++extraArgs;
3222 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003223
3224 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003225 if (sparse) {
3226 params.texelOut = arguments[2 + extraArgs];
3227 ++extraArgs;
3228 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003229
3230 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003231 if (bias) {
3232 params.bias = arguments[2 + extraArgs];
3233 ++extraArgs;
3234 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003235
3236 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003237 if (cracked.gather && ! sampler.shadow) {
3238 // default component is 0, if missing, otherwise an argument
3239 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003240 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003241 ++extraArgs;
3242 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003243 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003244 }
3245 }
John Kessenichfc51d282015-08-19 13:34:18 -06003246
John Kessenich65336482016-06-16 14:06:26 -06003247 // projective component (might not to move)
3248 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3249 // are divided by the last component of P."
3250 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3251 // unused components will appear after all used components."
3252 if (cracked.proj) {
3253 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3254 int projTargetComp;
3255 switch (sampler.dim) {
3256 case glslang::Esd1D: projTargetComp = 1; break;
3257 case glslang::Esd2D: projTargetComp = 2; break;
3258 case glslang::EsdRect: projTargetComp = 2; break;
3259 default: projTargetComp = projSourceComp; break;
3260 }
3261 // copy the projective coordinate if we have to
3262 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003263 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003264 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3265 projSourceComp);
3266 params.coords = builder.createCompositeInsert(projComp, params.coords,
3267 builder.getTypeId(params.coords), projTargetComp);
3268 }
3269 }
3270
John Kessenich8c8505c2016-07-26 12:50:38 -06003271 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003272}
3273
3274spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3275{
3276 // Grab the function's pointer from the previously created function
3277 spv::Function* function = functionMap[node->getName().c_str()];
3278 if (! function)
3279 return 0;
3280
3281 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3282 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3283
3284 // See comments in makeFunctions() for details about the semantics for parameter passing.
3285 //
3286 // These imply we need a four step process:
3287 // 1. Evaluate the arguments
3288 // 2. Allocate and make copies of in, out, and inout arguments
3289 // 3. Make the call
3290 // 4. Copy back the results
3291
3292 // 1. Evaluate the arguments
3293 std::vector<spv::Builder::AccessChain> lValues;
3294 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003295 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003296 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003297 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003298 // build l-value
3299 builder.clearAccessChain();
3300 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003301 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003302 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003303 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003304 // save l-value
3305 lValues.push_back(builder.getAccessChain());
3306 } else {
3307 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003308 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003309 }
3310 }
3311
3312 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3313 // copy the original into that space.
3314 //
3315 // Also, build up the list of actual arguments to pass in for the call
3316 int lValueCount = 0;
3317 int rValueCount = 0;
3318 std::vector<spv::Id> spvArgs;
3319 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003320 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003321 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003322 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003323 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3324 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003325 builder.setAccessChain(lValues[lValueCount]);
3326 arg = builder.accessChainGetLValue();
3327 ++lValueCount;
3328 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003329 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003330 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3331 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3332 // need to copy the input into output space
3333 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003334 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003335 builder.clearAccessChain();
3336 builder.setAccessChainLValue(arg);
3337 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003338 }
3339 ++lValueCount;
3340 } else {
3341 arg = rValues[rValueCount];
3342 ++rValueCount;
3343 }
3344 spvArgs.push_back(arg);
3345 }
3346
3347 // 3. Make the call.
3348 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003349 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003350
3351 // 4. Copy back out an "out" arguments.
3352 lValueCount = 0;
3353 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003354 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003355 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3356 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3357 spv::Id copy = builder.createLoad(spvArgs[a]);
3358 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003359 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003360 }
3361 ++lValueCount;
3362 }
3363 }
3364
3365 return result;
3366}
3367
3368// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003369spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3370 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003371 spv::Id typeId, spv::Id left, spv::Id right,
3372 glslang::TBasicType typeProxy, bool reduceComparison)
3373{
Rex Xu8ff43de2016-04-22 16:51:45 +08003374 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003375#ifdef AMD_EXTENSIONS
3376 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3377#else
John Kessenich140f3df2015-06-26 16:58:36 -06003378 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003379#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003380 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003381
3382 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003383 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003384 bool comparison = false;
3385
3386 switch (op) {
3387 case glslang::EOpAdd:
3388 case glslang::EOpAddAssign:
3389 if (isFloat)
3390 binOp = spv::OpFAdd;
3391 else
3392 binOp = spv::OpIAdd;
3393 break;
3394 case glslang::EOpSub:
3395 case glslang::EOpSubAssign:
3396 if (isFloat)
3397 binOp = spv::OpFSub;
3398 else
3399 binOp = spv::OpISub;
3400 break;
3401 case glslang::EOpMul:
3402 case glslang::EOpMulAssign:
3403 if (isFloat)
3404 binOp = spv::OpFMul;
3405 else
3406 binOp = spv::OpIMul;
3407 break;
3408 case glslang::EOpVectorTimesScalar:
3409 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003410 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003411 if (builder.isVector(right))
3412 std::swap(left, right);
3413 assert(builder.isScalar(right));
3414 needMatchingVectors = false;
3415 binOp = spv::OpVectorTimesScalar;
3416 } else
3417 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003418 break;
3419 case glslang::EOpVectorTimesMatrix:
3420 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003421 binOp = spv::OpVectorTimesMatrix;
3422 break;
3423 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003424 binOp = spv::OpMatrixTimesVector;
3425 break;
3426 case glslang::EOpMatrixTimesScalar:
3427 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003428 binOp = spv::OpMatrixTimesScalar;
3429 break;
3430 case glslang::EOpMatrixTimesMatrix:
3431 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003432 binOp = spv::OpMatrixTimesMatrix;
3433 break;
3434 case glslang::EOpOuterProduct:
3435 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003436 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003437 break;
3438
3439 case glslang::EOpDiv:
3440 case glslang::EOpDivAssign:
3441 if (isFloat)
3442 binOp = spv::OpFDiv;
3443 else if (isUnsigned)
3444 binOp = spv::OpUDiv;
3445 else
3446 binOp = spv::OpSDiv;
3447 break;
3448 case glslang::EOpMod:
3449 case glslang::EOpModAssign:
3450 if (isFloat)
3451 binOp = spv::OpFMod;
3452 else if (isUnsigned)
3453 binOp = spv::OpUMod;
3454 else
3455 binOp = spv::OpSMod;
3456 break;
3457 case glslang::EOpRightShift:
3458 case glslang::EOpRightShiftAssign:
3459 if (isUnsigned)
3460 binOp = spv::OpShiftRightLogical;
3461 else
3462 binOp = spv::OpShiftRightArithmetic;
3463 break;
3464 case glslang::EOpLeftShift:
3465 case glslang::EOpLeftShiftAssign:
3466 binOp = spv::OpShiftLeftLogical;
3467 break;
3468 case glslang::EOpAnd:
3469 case glslang::EOpAndAssign:
3470 binOp = spv::OpBitwiseAnd;
3471 break;
3472 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003473 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003474 binOp = spv::OpLogicalAnd;
3475 break;
3476 case glslang::EOpInclusiveOr:
3477 case glslang::EOpInclusiveOrAssign:
3478 binOp = spv::OpBitwiseOr;
3479 break;
3480 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003481 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003482 binOp = spv::OpLogicalOr;
3483 break;
3484 case glslang::EOpExclusiveOr:
3485 case glslang::EOpExclusiveOrAssign:
3486 binOp = spv::OpBitwiseXor;
3487 break;
3488 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003489 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003490 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003491 break;
3492
3493 case glslang::EOpLessThan:
3494 case glslang::EOpGreaterThan:
3495 case glslang::EOpLessThanEqual:
3496 case glslang::EOpGreaterThanEqual:
3497 case glslang::EOpEqual:
3498 case glslang::EOpNotEqual:
3499 case glslang::EOpVectorEqual:
3500 case glslang::EOpVectorNotEqual:
3501 comparison = true;
3502 break;
3503 default:
3504 break;
3505 }
3506
John Kessenich7c1aa102015-10-15 13:29:11 -06003507 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003508 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003509 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003510 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003511 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003512
3513 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003514 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003515 builder.promoteScalar(precision, left, right);
3516
qining25262b32016-05-06 17:25:16 -04003517 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3518 addDecoration(result, noContraction);
3519 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003520 }
3521
3522 if (! comparison)
3523 return 0;
3524
John Kessenich7c1aa102015-10-15 13:29:11 -06003525 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003526
John Kessenich4583b612016-08-07 19:14:22 -06003527 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3528 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003529 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003530
3531 switch (op) {
3532 case glslang::EOpLessThan:
3533 if (isFloat)
3534 binOp = spv::OpFOrdLessThan;
3535 else if (isUnsigned)
3536 binOp = spv::OpULessThan;
3537 else
3538 binOp = spv::OpSLessThan;
3539 break;
3540 case glslang::EOpGreaterThan:
3541 if (isFloat)
3542 binOp = spv::OpFOrdGreaterThan;
3543 else if (isUnsigned)
3544 binOp = spv::OpUGreaterThan;
3545 else
3546 binOp = spv::OpSGreaterThan;
3547 break;
3548 case glslang::EOpLessThanEqual:
3549 if (isFloat)
3550 binOp = spv::OpFOrdLessThanEqual;
3551 else if (isUnsigned)
3552 binOp = spv::OpULessThanEqual;
3553 else
3554 binOp = spv::OpSLessThanEqual;
3555 break;
3556 case glslang::EOpGreaterThanEqual:
3557 if (isFloat)
3558 binOp = spv::OpFOrdGreaterThanEqual;
3559 else if (isUnsigned)
3560 binOp = spv::OpUGreaterThanEqual;
3561 else
3562 binOp = spv::OpSGreaterThanEqual;
3563 break;
3564 case glslang::EOpEqual:
3565 case glslang::EOpVectorEqual:
3566 if (isFloat)
3567 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003568 else if (isBool)
3569 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003570 else
3571 binOp = spv::OpIEqual;
3572 break;
3573 case glslang::EOpNotEqual:
3574 case glslang::EOpVectorNotEqual:
3575 if (isFloat)
3576 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003577 else if (isBool)
3578 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003579 else
3580 binOp = spv::OpINotEqual;
3581 break;
3582 default:
3583 break;
3584 }
3585
qining25262b32016-05-06 17:25:16 -04003586 if (binOp != spv::OpNop) {
3587 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3588 addDecoration(result, noContraction);
3589 return builder.setPrecision(result, precision);
3590 }
John Kessenich140f3df2015-06-26 16:58:36 -06003591
3592 return 0;
3593}
3594
John Kessenich04bb8a02015-12-12 12:28:14 -07003595//
3596// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3597// These can be any of:
3598//
3599// matrix * scalar
3600// scalar * matrix
3601// matrix * matrix linear algebraic
3602// matrix * vector
3603// vector * matrix
3604// matrix * matrix componentwise
3605// matrix op matrix op in {+, -, /}
3606// matrix op scalar op in {+, -, /}
3607// scalar op matrix op in {+, -, /}
3608//
qining25262b32016-05-06 17:25:16 -04003609spv::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 -07003610{
3611 bool firstClass = true;
3612
3613 // First, handle first-class matrix operations (* and matrix/scalar)
3614 switch (op) {
3615 case spv::OpFDiv:
3616 if (builder.isMatrix(left) && builder.isScalar(right)) {
3617 // turn matrix / scalar into a multiply...
3618 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3619 op = spv::OpMatrixTimesScalar;
3620 } else
3621 firstClass = false;
3622 break;
3623 case spv::OpMatrixTimesScalar:
3624 if (builder.isMatrix(right))
3625 std::swap(left, right);
3626 assert(builder.isScalar(right));
3627 break;
3628 case spv::OpVectorTimesMatrix:
3629 assert(builder.isVector(left));
3630 assert(builder.isMatrix(right));
3631 break;
3632 case spv::OpMatrixTimesVector:
3633 assert(builder.isMatrix(left));
3634 assert(builder.isVector(right));
3635 break;
3636 case spv::OpMatrixTimesMatrix:
3637 assert(builder.isMatrix(left));
3638 assert(builder.isMatrix(right));
3639 break;
3640 default:
3641 firstClass = false;
3642 break;
3643 }
3644
qining25262b32016-05-06 17:25:16 -04003645 if (firstClass) {
3646 spv::Id result = builder.createBinOp(op, typeId, left, right);
3647 addDecoration(result, noContraction);
3648 return builder.setPrecision(result, precision);
3649 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003650
LoopDawg592860c2016-06-09 08:57:35 -06003651 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003652 // The result type of all of them is the same type as the (a) matrix operand.
3653 // The algorithm is to:
3654 // - break the matrix(es) into vectors
3655 // - smear any scalar to a vector
3656 // - do vector operations
3657 // - make a matrix out the vector results
3658 switch (op) {
3659 case spv::OpFAdd:
3660 case spv::OpFSub:
3661 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003662 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003663 case spv::OpFMul:
3664 {
3665 // one time set up...
3666 bool leftMat = builder.isMatrix(left);
3667 bool rightMat = builder.isMatrix(right);
3668 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3669 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3670 spv::Id scalarType = builder.getScalarTypeId(typeId);
3671 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3672 std::vector<spv::Id> results;
3673 spv::Id smearVec = spv::NoResult;
3674 if (builder.isScalar(left))
3675 smearVec = builder.smearScalar(precision, left, vecType);
3676 else if (builder.isScalar(right))
3677 smearVec = builder.smearScalar(precision, right, vecType);
3678
3679 // do each vector op
3680 for (unsigned int c = 0; c < numCols; ++c) {
3681 std::vector<unsigned int> indexes;
3682 indexes.push_back(c);
3683 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3684 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003685 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3686 addDecoration(result, noContraction);
3687 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003688 }
3689
3690 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003691 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003692 }
3693 default:
3694 assert(0);
3695 return spv::NoResult;
3696 }
3697}
3698
qining25262b32016-05-06 17:25:16 -04003699spv::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 -06003700{
3701 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003702 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003703 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003704 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003705#ifdef AMD_EXTENSIONS
3706 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3707#else
Rex Xu04db3f52015-09-16 11:44:02 +08003708 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003709#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003710
3711 switch (op) {
3712 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003713 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003714 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003715 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003716 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003717 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003718 unaryOp = spv::OpSNegate;
3719 break;
3720
3721 case glslang::EOpLogicalNot:
3722 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003723 unaryOp = spv::OpLogicalNot;
3724 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003725 case glslang::EOpBitwiseNot:
3726 unaryOp = spv::OpNot;
3727 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003728
John Kessenich140f3df2015-06-26 16:58:36 -06003729 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003730 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003731 break;
3732 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003733 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003734 break;
3735 case glslang::EOpTranspose:
3736 unaryOp = spv::OpTranspose;
3737 break;
3738
3739 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003740 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003741 break;
3742 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003743 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003744 break;
3745 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003746 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003747 break;
3748 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003749 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003750 break;
3751 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003752 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003753 break;
3754 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003755 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003756 break;
3757 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003758 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003759 break;
3760 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003761 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003762 break;
3763
3764 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003765 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003766 break;
3767 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003768 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003769 break;
3770 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003771 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003772 break;
3773 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003774 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003775 break;
3776 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003777 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003778 break;
3779 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003780 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003781 break;
3782
3783 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003784 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003785 break;
3786 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003787 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003788 break;
3789
3790 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003791 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003792 break;
3793 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003794 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003795 break;
3796 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003797 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003798 break;
3799 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003800 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003801 break;
3802 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003803 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003804 break;
3805 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003806 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003807 break;
3808
3809 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003810 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003811 break;
3812 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003813 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003814 break;
3815 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003816 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003817 break;
3818 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003819 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003820 break;
3821 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003822 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003823 break;
3824 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003825 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003826 break;
3827
3828 case glslang::EOpIsNan:
3829 unaryOp = spv::OpIsNan;
3830 break;
3831 case glslang::EOpIsInf:
3832 unaryOp = spv::OpIsInf;
3833 break;
LoopDawg592860c2016-06-09 08:57:35 -06003834 case glslang::EOpIsFinite:
3835 unaryOp = spv::OpIsFinite;
3836 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003837
Rex Xucbc426e2015-12-15 16:03:10 +08003838 case glslang::EOpFloatBitsToInt:
3839 case glslang::EOpFloatBitsToUint:
3840 case glslang::EOpIntBitsToFloat:
3841 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003842 case glslang::EOpDoubleBitsToInt64:
3843 case glslang::EOpDoubleBitsToUint64:
3844 case glslang::EOpInt64BitsToDouble:
3845 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003846 unaryOp = spv::OpBitcast;
3847 break;
3848
John Kessenich140f3df2015-06-26 16:58:36 -06003849 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003850 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003851 break;
3852 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003853 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003854 break;
3855 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003856 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003857 break;
3858 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003859 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003860 break;
3861 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003862 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003863 break;
3864 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003865 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003866 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003867 case glslang::EOpPackSnorm4x8:
3868 libCall = spv::GLSLstd450PackSnorm4x8;
3869 break;
3870 case glslang::EOpUnpackSnorm4x8:
3871 libCall = spv::GLSLstd450UnpackSnorm4x8;
3872 break;
3873 case glslang::EOpPackUnorm4x8:
3874 libCall = spv::GLSLstd450PackUnorm4x8;
3875 break;
3876 case glslang::EOpUnpackUnorm4x8:
3877 libCall = spv::GLSLstd450UnpackUnorm4x8;
3878 break;
3879 case glslang::EOpPackDouble2x32:
3880 libCall = spv::GLSLstd450PackDouble2x32;
3881 break;
3882 case glslang::EOpUnpackDouble2x32:
3883 libCall = spv::GLSLstd450UnpackDouble2x32;
3884 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003885
Rex Xu8ff43de2016-04-22 16:51:45 +08003886 case glslang::EOpPackInt2x32:
3887 case glslang::EOpUnpackInt2x32:
3888 case glslang::EOpPackUint2x32:
3889 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003890 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003891 break;
3892
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003893#ifdef AMD_EXTENSIONS
3894 case glslang::EOpPackFloat2x16:
3895 case glslang::EOpUnpackFloat2x16:
3896 unaryOp = spv::OpBitcast;
3897 break;
3898#endif
3899
John Kessenich140f3df2015-06-26 16:58:36 -06003900 case glslang::EOpDPdx:
3901 unaryOp = spv::OpDPdx;
3902 break;
3903 case glslang::EOpDPdy:
3904 unaryOp = spv::OpDPdy;
3905 break;
3906 case glslang::EOpFwidth:
3907 unaryOp = spv::OpFwidth;
3908 break;
3909 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003910 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003911 unaryOp = spv::OpDPdxFine;
3912 break;
3913 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003914 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003915 unaryOp = spv::OpDPdyFine;
3916 break;
3917 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003918 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003919 unaryOp = spv::OpFwidthFine;
3920 break;
3921 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003922 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003923 unaryOp = spv::OpDPdxCoarse;
3924 break;
3925 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003926 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003927 unaryOp = spv::OpDPdyCoarse;
3928 break;
3929 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003930 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003931 unaryOp = spv::OpFwidthCoarse;
3932 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003933 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003934 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003935 libCall = spv::GLSLstd450InterpolateAtCentroid;
3936 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003937 case glslang::EOpAny:
3938 unaryOp = spv::OpAny;
3939 break;
3940 case glslang::EOpAll:
3941 unaryOp = spv::OpAll;
3942 break;
3943
3944 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003945 if (isFloat)
3946 libCall = spv::GLSLstd450FAbs;
3947 else
3948 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003949 break;
3950 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003951 if (isFloat)
3952 libCall = spv::GLSLstd450FSign;
3953 else
3954 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003955 break;
3956
John Kessenichfc51d282015-08-19 13:34:18 -06003957 case glslang::EOpAtomicCounterIncrement:
3958 case glslang::EOpAtomicCounterDecrement:
3959 case glslang::EOpAtomicCounter:
3960 {
3961 // Handle all of the atomics in one place, in createAtomicOperation()
3962 std::vector<spv::Id> operands;
3963 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003964 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003965 }
3966
John Kessenichfc51d282015-08-19 13:34:18 -06003967 case glslang::EOpBitFieldReverse:
3968 unaryOp = spv::OpBitReverse;
3969 break;
3970 case glslang::EOpBitCount:
3971 unaryOp = spv::OpBitCount;
3972 break;
3973 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003974 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003975 break;
3976 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003977 if (isUnsigned)
3978 libCall = spv::GLSLstd450FindUMsb;
3979 else
3980 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003981 break;
3982
Rex Xu574ab042016-04-14 16:53:07 +08003983 case glslang::EOpBallot:
3984 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003985 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003986 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003987 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003988#ifdef AMD_EXTENSIONS
3989 case glslang::EOpMinInvocations:
3990 case glslang::EOpMaxInvocations:
3991 case glslang::EOpAddInvocations:
3992 case glslang::EOpMinInvocationsNonUniform:
3993 case glslang::EOpMaxInvocationsNonUniform:
3994 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08003995 case glslang::EOpMinInvocationsInclusiveScan:
3996 case glslang::EOpMaxInvocationsInclusiveScan:
3997 case glslang::EOpAddInvocationsInclusiveScan:
3998 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
3999 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4000 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4001 case glslang::EOpMinInvocationsExclusiveScan:
4002 case glslang::EOpMaxInvocationsExclusiveScan:
4003 case glslang::EOpAddInvocationsExclusiveScan:
4004 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4005 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4006 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004007#endif
Rex Xu51596642016-09-21 18:56:12 +08004008 {
4009 std::vector<spv::Id> operands;
4010 operands.push_back(operand);
4011 return createInvocationsOperation(op, typeId, operands, typeProxy);
4012 }
Rex Xu9d93a232016-05-05 12:30:44 +08004013
4014#ifdef AMD_EXTENSIONS
4015 case glslang::EOpMbcnt:
4016 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4017 libCall = spv::MbcntAMD;
4018 break;
4019
4020 case glslang::EOpCubeFaceIndex:
4021 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4022 libCall = spv::CubeFaceIndexAMD;
4023 break;
4024
4025 case glslang::EOpCubeFaceCoord:
4026 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4027 libCall = spv::CubeFaceCoordAMD;
4028 break;
4029#endif
Rex Xu338b1852016-05-05 20:38:33 +08004030
John Kessenich140f3df2015-06-26 16:58:36 -06004031 default:
4032 return 0;
4033 }
4034
4035 spv::Id id;
4036 if (libCall >= 0) {
4037 std::vector<spv::Id> args;
4038 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004039 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004040 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004041 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004042 }
John Kessenich140f3df2015-06-26 16:58:36 -06004043
qining25262b32016-05-06 17:25:16 -04004044 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004045 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004046}
4047
John Kessenich7a53f762016-01-20 11:19:27 -07004048// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004049spv::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 -07004050{
4051 // Handle unary operations vector by vector.
4052 // The result type is the same type as the original type.
4053 // The algorithm is to:
4054 // - break the matrix into vectors
4055 // - apply the operation to each vector
4056 // - make a matrix out the vector results
4057
4058 // get the types sorted out
4059 int numCols = builder.getNumColumns(operand);
4060 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004061 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4062 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004063 std::vector<spv::Id> results;
4064
4065 // do each vector op
4066 for (int c = 0; c < numCols; ++c) {
4067 std::vector<unsigned int> indexes;
4068 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004069 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4070 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4071 addDecoration(destVec, noContraction);
4072 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004073 }
4074
4075 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004076 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004077}
4078
Rex Xu73e3ce72016-04-27 18:48:17 +08004079spv::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 -06004080{
4081 spv::Op convOp = spv::OpNop;
4082 spv::Id zero = 0;
4083 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004084 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004085
4086 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4087
4088 switch (op) {
4089 case glslang::EOpConvIntToBool:
4090 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004091 case glslang::EOpConvInt64ToBool:
4092 case glslang::EOpConvUint64ToBool:
4093 zero = (op == glslang::EOpConvInt64ToBool ||
4094 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004095 zero = makeSmearedConstant(zero, vectorSize);
4096 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4097
4098 case glslang::EOpConvFloatToBool:
4099 zero = builder.makeFloatConstant(0.0F);
4100 zero = makeSmearedConstant(zero, vectorSize);
4101 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4102
4103 case glslang::EOpConvDoubleToBool:
4104 zero = builder.makeDoubleConstant(0.0);
4105 zero = makeSmearedConstant(zero, vectorSize);
4106 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4107
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004108#ifdef AMD_EXTENSIONS
4109 case glslang::EOpConvFloat16ToBool:
4110 zero = builder.makeFloat16Constant(0.0F);
4111 zero = makeSmearedConstant(zero, vectorSize);
4112 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4113#endif
4114
John Kessenich140f3df2015-06-26 16:58:36 -06004115 case glslang::EOpConvBoolToFloat:
4116 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004117 zero = builder.makeFloatConstant(0.0F);
4118 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004119 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004120
John Kessenich140f3df2015-06-26 16:58:36 -06004121 case glslang::EOpConvBoolToDouble:
4122 convOp = spv::OpSelect;
4123 zero = builder.makeDoubleConstant(0.0);
4124 one = builder.makeDoubleConstant(1.0);
4125 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004126
4127#ifdef AMD_EXTENSIONS
4128 case glslang::EOpConvBoolToFloat16:
4129 convOp = spv::OpSelect;
4130 zero = builder.makeFloat16Constant(0.0F);
4131 one = builder.makeFloat16Constant(1.0F);
4132 break;
4133#endif
4134
John Kessenich140f3df2015-06-26 16:58:36 -06004135 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004136 case glslang::EOpConvBoolToInt64:
4137 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4138 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004139 convOp = spv::OpSelect;
4140 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004141
John Kessenich140f3df2015-06-26 16:58:36 -06004142 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004143 case glslang::EOpConvBoolToUint64:
4144 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4145 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004146 convOp = spv::OpSelect;
4147 break;
4148
4149 case glslang::EOpConvIntToFloat:
4150 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004151 case glslang::EOpConvInt64ToFloat:
4152 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004153#ifdef AMD_EXTENSIONS
4154 case glslang::EOpConvIntToFloat16:
4155 case glslang::EOpConvInt64ToFloat16:
4156#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004157 convOp = spv::OpConvertSToF;
4158 break;
4159
4160 case glslang::EOpConvUintToFloat:
4161 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004162 case glslang::EOpConvUint64ToFloat:
4163 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004164#ifdef AMD_EXTENSIONS
4165 case glslang::EOpConvUintToFloat16:
4166 case glslang::EOpConvUint64ToFloat16:
4167#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004168 convOp = spv::OpConvertUToF;
4169 break;
4170
4171 case glslang::EOpConvDoubleToFloat:
4172 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004173#ifdef AMD_EXTENSIONS
4174 case glslang::EOpConvDoubleToFloat16:
4175 case glslang::EOpConvFloat16ToDouble:
4176 case glslang::EOpConvFloatToFloat16:
4177 case glslang::EOpConvFloat16ToFloat:
4178#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004179 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004180 if (builder.isMatrixType(destType))
4181 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004182 break;
4183
4184 case glslang::EOpConvFloatToInt:
4185 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004186 case glslang::EOpConvFloatToInt64:
4187 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004188#ifdef AMD_EXTENSIONS
4189 case glslang::EOpConvFloat16ToInt:
4190 case glslang::EOpConvFloat16ToInt64:
4191#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004192 convOp = spv::OpConvertFToS;
4193 break;
4194
4195 case glslang::EOpConvUintToInt:
4196 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004197 case glslang::EOpConvUint64ToInt64:
4198 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004199 if (builder.isInSpecConstCodeGenMode()) {
4200 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004201 zero = (op == glslang::EOpConvUint64ToInt64 ||
4202 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004203 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004204 // Use OpIAdd, instead of OpBitcast to do the conversion when
4205 // generating for OpSpecConstantOp instruction.
4206 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4207 }
4208 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004209 convOp = spv::OpBitcast;
4210 break;
4211
4212 case glslang::EOpConvFloatToUint:
4213 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004214 case glslang::EOpConvFloatToUint64:
4215 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004216#ifdef AMD_EXTENSIONS
4217 case glslang::EOpConvFloat16ToUint:
4218 case glslang::EOpConvFloat16ToUint64:
4219#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004220 convOp = spv::OpConvertFToU;
4221 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004222
4223 case glslang::EOpConvIntToInt64:
4224 case glslang::EOpConvInt64ToInt:
4225 convOp = spv::OpSConvert;
4226 break;
4227
4228 case glslang::EOpConvUintToUint64:
4229 case glslang::EOpConvUint64ToUint:
4230 convOp = spv::OpUConvert;
4231 break;
4232
4233 case glslang::EOpConvIntToUint64:
4234 case glslang::EOpConvInt64ToUint:
4235 case glslang::EOpConvUint64ToInt:
4236 case glslang::EOpConvUintToInt64:
4237 // OpSConvert/OpUConvert + OpBitCast
4238 switch (op) {
4239 case glslang::EOpConvIntToUint64:
4240 convOp = spv::OpSConvert;
4241 type = builder.makeIntType(64);
4242 break;
4243 case glslang::EOpConvInt64ToUint:
4244 convOp = spv::OpSConvert;
4245 type = builder.makeIntType(32);
4246 break;
4247 case glslang::EOpConvUint64ToInt:
4248 convOp = spv::OpUConvert;
4249 type = builder.makeUintType(32);
4250 break;
4251 case glslang::EOpConvUintToInt64:
4252 convOp = spv::OpUConvert;
4253 type = builder.makeUintType(64);
4254 break;
4255 default:
4256 assert(0);
4257 break;
4258 }
4259
4260 if (vectorSize > 0)
4261 type = builder.makeVectorType(type, vectorSize);
4262
4263 operand = builder.createUnaryOp(convOp, type, operand);
4264
4265 if (builder.isInSpecConstCodeGenMode()) {
4266 // Build zero scalar or vector for OpIAdd.
4267 zero = (op == glslang::EOpConvIntToUint64 ||
4268 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4269 zero = makeSmearedConstant(zero, vectorSize);
4270 // Use OpIAdd, instead of OpBitcast to do the conversion when
4271 // generating for OpSpecConstantOp instruction.
4272 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4273 }
4274 // For normal run-time conversion instruction, use OpBitcast.
4275 convOp = spv::OpBitcast;
4276 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004277 default:
4278 break;
4279 }
4280
4281 spv::Id result = 0;
4282 if (convOp == spv::OpNop)
4283 return result;
4284
4285 if (convOp == spv::OpSelect) {
4286 zero = makeSmearedConstant(zero, vectorSize);
4287 one = makeSmearedConstant(one, vectorSize);
4288 result = builder.createTriOp(convOp, destType, operand, one, zero);
4289 } else
4290 result = builder.createUnaryOp(convOp, destType, operand);
4291
John Kessenich32cfd492016-02-02 12:37:46 -07004292 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004293}
4294
4295spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4296{
4297 if (vectorSize == 0)
4298 return constant;
4299
4300 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4301 std::vector<spv::Id> components;
4302 for (int c = 0; c < vectorSize; ++c)
4303 components.push_back(constant);
4304 return builder.makeCompositeConstant(vectorTypeId, components);
4305}
4306
John Kessenich426394d2015-07-23 10:22:48 -06004307// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004308spv::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 -06004309{
4310 spv::Op opCode = spv::OpNop;
4311
4312 switch (op) {
4313 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004314 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004315 opCode = spv::OpAtomicIAdd;
4316 break;
4317 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004318 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004319 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004320 break;
4321 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004322 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004323 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004324 break;
4325 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004326 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004327 opCode = spv::OpAtomicAnd;
4328 break;
4329 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004330 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004331 opCode = spv::OpAtomicOr;
4332 break;
4333 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004334 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004335 opCode = spv::OpAtomicXor;
4336 break;
4337 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004338 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004339 opCode = spv::OpAtomicExchange;
4340 break;
4341 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004342 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004343 opCode = spv::OpAtomicCompareExchange;
4344 break;
4345 case glslang::EOpAtomicCounterIncrement:
4346 opCode = spv::OpAtomicIIncrement;
4347 break;
4348 case glslang::EOpAtomicCounterDecrement:
4349 opCode = spv::OpAtomicIDecrement;
4350 break;
4351 case glslang::EOpAtomicCounter:
4352 opCode = spv::OpAtomicLoad;
4353 break;
4354 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004355 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004356 break;
4357 }
4358
4359 // Sort out the operands
4360 // - mapping from glslang -> SPV
4361 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004362 // - compare-exchange swaps the value and comparator
4363 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004364 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4365 auto opIt = operands.begin(); // walk the glslang operands
4366 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004367 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4368 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4369 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004370 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4371 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004372 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004373 spvAtomicOperands.push_back(*(opIt + 1));
4374 spvAtomicOperands.push_back(*opIt);
4375 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004376 }
John Kessenich426394d2015-07-23 10:22:48 -06004377
John Kessenich3e60a6f2015-09-14 22:45:16 -06004378 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004379 for (; opIt != operands.end(); ++opIt)
4380 spvAtomicOperands.push_back(*opIt);
4381
4382 return builder.createOp(opCode, typeId, spvAtomicOperands);
4383}
4384
John Kessenich91cef522016-05-05 16:45:40 -06004385// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004386spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004387{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004388#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004389 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004390 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004391#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004392
Rex Xu51596642016-09-21 18:56:12 +08004393 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004394 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004395 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4396
chaocf200da82016-12-20 12:44:35 -08004397 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4398 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004399 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4400 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004401 } else if (op == glslang::EOpAnyInvocation ||
4402 op == glslang::EOpAllInvocations ||
4403 op == glslang::EOpAllInvocationsEqual) {
4404 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4405 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004406 } else {
4407 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004408#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004409 if (op == glslang::EOpMinInvocationsNonUniform ||
4410 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004411 op == glslang::EOpAddInvocationsNonUniform ||
4412 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4413 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4414 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4415 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4416 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4417 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004418 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004419#endif
Rex Xu51596642016-09-21 18:56:12 +08004420
4421 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004422#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004423 switch (op) {
4424 case glslang::EOpMinInvocations:
4425 case glslang::EOpMaxInvocations:
4426 case glslang::EOpAddInvocations:
4427 case glslang::EOpMinInvocationsNonUniform:
4428 case glslang::EOpMaxInvocationsNonUniform:
4429 case glslang::EOpAddInvocationsNonUniform:
4430 groupOperation = spv::GroupOperationReduce;
4431 spvGroupOperands.push_back(groupOperation);
4432 break;
4433 case glslang::EOpMinInvocationsInclusiveScan:
4434 case glslang::EOpMaxInvocationsInclusiveScan:
4435 case glslang::EOpAddInvocationsInclusiveScan:
4436 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4437 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4438 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4439 groupOperation = spv::GroupOperationInclusiveScan;
4440 spvGroupOperands.push_back(groupOperation);
4441 break;
4442 case glslang::EOpMinInvocationsExclusiveScan:
4443 case glslang::EOpMaxInvocationsExclusiveScan:
4444 case glslang::EOpAddInvocationsExclusiveScan:
4445 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4446 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4447 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4448 groupOperation = spv::GroupOperationExclusiveScan;
4449 spvGroupOperands.push_back(groupOperation);
4450 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004451 default:
4452 break;
Rex Xu430ef402016-10-14 17:22:23 +08004453 }
Rex Xu9d93a232016-05-05 12:30:44 +08004454#endif
Rex Xu51596642016-09-21 18:56:12 +08004455 }
4456
4457 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4458 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004459
4460 switch (op) {
4461 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004462 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004463 break;
John Kessenich91cef522016-05-05 16:45:40 -06004464 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004465 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004466 break;
John Kessenich91cef522016-05-05 16:45:40 -06004467 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004468 opCode = spv::OpSubgroupAllEqualKHR;
4469 break;
Rex Xu51596642016-09-21 18:56:12 +08004470 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004471 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004472 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004473 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004474 break;
4475 case glslang::EOpReadFirstInvocation:
4476 opCode = spv::OpSubgroupFirstInvocationKHR;
4477 break;
4478 case glslang::EOpBallot:
4479 {
4480 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4481 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4482 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4483 //
4484 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4485 //
4486 spv::Id uintType = builder.makeUintType(32);
4487 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4488 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4489
4490 std::vector<spv::Id> components;
4491 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4492 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4493
4494 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4495 return builder.createUnaryOp(spv::OpBitcast, typeId,
4496 builder.createCompositeConstruct(uvec2Type, components));
4497 }
4498
Rex Xu9d93a232016-05-05 12:30:44 +08004499#ifdef AMD_EXTENSIONS
4500 case glslang::EOpMinInvocations:
4501 case glslang::EOpMaxInvocations:
4502 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004503 case glslang::EOpMinInvocationsInclusiveScan:
4504 case glslang::EOpMaxInvocationsInclusiveScan:
4505 case glslang::EOpAddInvocationsInclusiveScan:
4506 case glslang::EOpMinInvocationsExclusiveScan:
4507 case glslang::EOpMaxInvocationsExclusiveScan:
4508 case glslang::EOpAddInvocationsExclusiveScan:
4509 if (op == glslang::EOpMinInvocations ||
4510 op == glslang::EOpMinInvocationsInclusiveScan ||
4511 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004512 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004513 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004514 else {
4515 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004516 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004517 else
Rex Xu51596642016-09-21 18:56:12 +08004518 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004519 }
Rex Xu430ef402016-10-14 17:22:23 +08004520 } else if (op == glslang::EOpMaxInvocations ||
4521 op == glslang::EOpMaxInvocationsInclusiveScan ||
4522 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004523 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004524 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004525 else {
4526 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004527 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004528 else
Rex Xu51596642016-09-21 18:56:12 +08004529 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004530 }
4531 } else {
4532 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004533 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004534 else
Rex Xu51596642016-09-21 18:56:12 +08004535 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004536 }
4537
Rex Xu2bbbe062016-08-23 15:41:05 +08004538 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004539 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004540
4541 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004542 case glslang::EOpMinInvocationsNonUniform:
4543 case glslang::EOpMaxInvocationsNonUniform:
4544 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004545 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4546 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4547 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4548 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4549 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4550 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4551 if (op == glslang::EOpMinInvocationsNonUniform ||
4552 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4553 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004554 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004555 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004556 else {
4557 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004558 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004559 else
Rex Xu51596642016-09-21 18:56:12 +08004560 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004561 }
4562 }
Rex Xu430ef402016-10-14 17:22:23 +08004563 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4564 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4565 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004566 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004567 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004568 else {
4569 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004570 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004571 else
Rex Xu51596642016-09-21 18:56:12 +08004572 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004573 }
4574 }
4575 else {
4576 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004577 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004578 else
Rex Xu51596642016-09-21 18:56:12 +08004579 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004580 }
4581
Rex Xu2bbbe062016-08-23 15:41:05 +08004582 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004583 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004584
4585 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004586#endif
John Kessenich91cef522016-05-05 16:45:40 -06004587 default:
4588 logger->missingFunctionality("invocation operation");
4589 return spv::NoResult;
4590 }
Rex Xu51596642016-09-21 18:56:12 +08004591
4592 assert(opCode != spv::OpNop);
4593 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004594}
4595
Rex Xu2bbbe062016-08-23 15:41:05 +08004596// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004597spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004598{
Rex Xub7072052016-09-26 15:53:40 +08004599#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004600 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4601 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004602 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004603 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004604 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4605 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4606 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004607#else
4608 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4609 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004610 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4611 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004612#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004613
4614 // Handle group invocation operations scalar by scalar.
4615 // The result type is the same type as the original type.
4616 // The algorithm is to:
4617 // - break the vector into scalars
4618 // - apply the operation to each scalar
4619 // - make a vector out the scalar results
4620
4621 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004622 int numComponents = builder.getNumComponents(operands[0]);
4623 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004624 std::vector<spv::Id> results;
4625
4626 // do each scalar op
4627 for (int comp = 0; comp < numComponents; ++comp) {
4628 std::vector<unsigned int> indexes;
4629 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004630 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004631 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004632 if (op == spv::OpSubgroupReadInvocationKHR) {
4633 spvGroupOperands.push_back(scalar);
4634 spvGroupOperands.push_back(operands[1]);
4635 } else if (op == spv::OpGroupBroadcast) {
4636 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004637 spvGroupOperands.push_back(scalar);
4638 spvGroupOperands.push_back(operands[1]);
4639 } else {
chaocf200da82016-12-20 12:44:35 -08004640 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004641 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004642 spvGroupOperands.push_back(scalar);
4643 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004644
Rex Xub7072052016-09-26 15:53:40 +08004645 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004646 }
4647
4648 // put the pieces together
4649 return builder.createCompositeConstruct(typeId, results);
4650}
Rex Xu2bbbe062016-08-23 15:41:05 +08004651
John Kessenich5e4b1242015-08-06 22:53:06 -06004652spv::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 -06004653{
Rex Xu8ff43de2016-04-22 16:51:45 +08004654 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004655#ifdef AMD_EXTENSIONS
4656 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4657#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004658 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004659#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004660
John Kessenich140f3df2015-06-26 16:58:36 -06004661 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004662 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004663 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004664 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004665 spv::Id typeId0 = 0;
4666 if (consumedOperands > 0)
4667 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08004668 spv::Id typeId1 = 0;
4669 if (consumedOperands > 1)
4670 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07004671 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004672
4673 switch (op) {
4674 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004675 if (isFloat)
4676 libCall = spv::GLSLstd450FMin;
4677 else if (isUnsigned)
4678 libCall = spv::GLSLstd450UMin;
4679 else
4680 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004681 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004682 break;
4683 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004684 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004685 break;
4686 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004687 if (isFloat)
4688 libCall = spv::GLSLstd450FMax;
4689 else if (isUnsigned)
4690 libCall = spv::GLSLstd450UMax;
4691 else
4692 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004693 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004694 break;
4695 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004696 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004697 break;
4698 case glslang::EOpDot:
4699 opCode = spv::OpDot;
4700 break;
4701 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004702 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004703 break;
4704
4705 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004706 if (isFloat)
4707 libCall = spv::GLSLstd450FClamp;
4708 else if (isUnsigned)
4709 libCall = spv::GLSLstd450UClamp;
4710 else
4711 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004712 builder.promoteScalar(precision, operands.front(), operands[1]);
4713 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004714 break;
4715 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004716 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4717 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004718 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004719 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004720 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004721 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004722 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004723 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004724 break;
4725 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004726 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004727 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004728 break;
4729 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004730 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004731 builder.promoteScalar(precision, operands[0], operands[2]);
4732 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004733 break;
4734
4735 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004736 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004737 break;
4738 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004739 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004740 break;
4741 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004742 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004743 break;
4744 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004745 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004746 break;
4747 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004748 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004749 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004750 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004751 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004752 libCall = spv::GLSLstd450InterpolateAtSample;
4753 break;
4754 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004755 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004756 libCall = spv::GLSLstd450InterpolateAtOffset;
4757 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004758 case glslang::EOpAddCarry:
4759 opCode = spv::OpIAddCarry;
4760 typeId = builder.makeStructResultType(typeId0, typeId0);
4761 consumedOperands = 2;
4762 break;
4763 case glslang::EOpSubBorrow:
4764 opCode = spv::OpISubBorrow;
4765 typeId = builder.makeStructResultType(typeId0, typeId0);
4766 consumedOperands = 2;
4767 break;
4768 case glslang::EOpUMulExtended:
4769 opCode = spv::OpUMulExtended;
4770 typeId = builder.makeStructResultType(typeId0, typeId0);
4771 consumedOperands = 2;
4772 break;
4773 case glslang::EOpIMulExtended:
4774 opCode = spv::OpSMulExtended;
4775 typeId = builder.makeStructResultType(typeId0, typeId0);
4776 consumedOperands = 2;
4777 break;
4778 case glslang::EOpBitfieldExtract:
4779 if (isUnsigned)
4780 opCode = spv::OpBitFieldUExtract;
4781 else
4782 opCode = spv::OpBitFieldSExtract;
4783 break;
4784 case glslang::EOpBitfieldInsert:
4785 opCode = spv::OpBitFieldInsert;
4786 break;
4787
4788 case glslang::EOpFma:
4789 libCall = spv::GLSLstd450Fma;
4790 break;
4791 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004792 {
4793 libCall = spv::GLSLstd450FrexpStruct;
4794 assert(builder.isPointerType(typeId1));
4795 typeId1 = builder.getContainedTypeId(typeId1);
4796#ifdef AMD_EXTENSIONS
4797 int width = builder.getScalarTypeWidth(typeId1);
4798#else
4799 int width = 32;
4800#endif
4801 if (builder.getNumComponents(operands[0]) == 1)
4802 frexpIntType = builder.makeIntegerType(width, true);
4803 else
4804 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
4805 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4806 consumedOperands = 1;
4807 }
John Kessenich55e7d112015-11-15 21:33:39 -07004808 break;
4809 case glslang::EOpLdexp:
4810 libCall = spv::GLSLstd450Ldexp;
4811 break;
4812
Rex Xu574ab042016-04-14 16:53:07 +08004813 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004814 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004815
Rex Xu9d93a232016-05-05 12:30:44 +08004816#ifdef AMD_EXTENSIONS
4817 case glslang::EOpSwizzleInvocations:
4818 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4819 libCall = spv::SwizzleInvocationsAMD;
4820 break;
4821 case glslang::EOpSwizzleInvocationsMasked:
4822 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4823 libCall = spv::SwizzleInvocationsMaskedAMD;
4824 break;
4825 case glslang::EOpWriteInvocation:
4826 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4827 libCall = spv::WriteInvocationAMD;
4828 break;
4829
4830 case glslang::EOpMin3:
4831 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4832 if (isFloat)
4833 libCall = spv::FMin3AMD;
4834 else {
4835 if (isUnsigned)
4836 libCall = spv::UMin3AMD;
4837 else
4838 libCall = spv::SMin3AMD;
4839 }
4840 break;
4841 case glslang::EOpMax3:
4842 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4843 if (isFloat)
4844 libCall = spv::FMax3AMD;
4845 else {
4846 if (isUnsigned)
4847 libCall = spv::UMax3AMD;
4848 else
4849 libCall = spv::SMax3AMD;
4850 }
4851 break;
4852 case glslang::EOpMid3:
4853 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4854 if (isFloat)
4855 libCall = spv::FMid3AMD;
4856 else {
4857 if (isUnsigned)
4858 libCall = spv::UMid3AMD;
4859 else
4860 libCall = spv::SMid3AMD;
4861 }
4862 break;
4863
4864 case glslang::EOpInterpolateAtVertex:
4865 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4866 libCall = spv::InterpolateAtVertexAMD;
4867 break;
4868#endif
4869
John Kessenich140f3df2015-06-26 16:58:36 -06004870 default:
4871 return 0;
4872 }
4873
4874 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004875 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004876 // Use an extended instruction from the standard library.
4877 // Construct the call arguments, without modifying the original operands vector.
4878 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4879 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004880 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004881 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004882 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004883 case 0:
4884 // should all be handled by visitAggregate and createNoArgOperation
4885 assert(0);
4886 return 0;
4887 case 1:
4888 // should all be handled by createUnaryOperation
4889 assert(0);
4890 return 0;
4891 case 2:
4892 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4893 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004894 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004895 // anything 3 or over doesn't have l-value operands, so all should be consumed
4896 assert(consumedOperands == operands.size());
4897 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004898 break;
4899 }
4900 }
4901
John Kessenich55e7d112015-11-15 21:33:39 -07004902 // Decode the return types that were structures
4903 switch (op) {
4904 case glslang::EOpAddCarry:
4905 case glslang::EOpSubBorrow:
4906 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4907 id = builder.createCompositeExtract(id, typeId0, 0);
4908 break;
4909 case glslang::EOpUMulExtended:
4910 case glslang::EOpIMulExtended:
4911 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4912 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4913 break;
4914 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004915 {
4916 assert(operands.size() == 2);
4917 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
4918 // "exp" is floating-point type (from HLSL intrinsic)
4919 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
4920 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
4921 builder.createStore(member1, operands[1]);
4922 } else
4923 // "exp" is integer type (from GLSL built-in function)
4924 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4925 id = builder.createCompositeExtract(id, typeId0, 0);
4926 }
John Kessenich55e7d112015-11-15 21:33:39 -07004927 break;
4928 default:
4929 break;
4930 }
4931
John Kessenich32cfd492016-02-02 12:37:46 -07004932 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004933}
4934
Rex Xu9d93a232016-05-05 12:30:44 +08004935// Intrinsics with no arguments (or no return value, and no precision).
4936spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004937{
4938 // TODO: get the barrier operands correct
4939
4940 switch (op) {
4941 case glslang::EOpEmitVertex:
4942 builder.createNoResultOp(spv::OpEmitVertex);
4943 return 0;
4944 case glslang::EOpEndPrimitive:
4945 builder.createNoResultOp(spv::OpEndPrimitive);
4946 return 0;
4947 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004948 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004949 return 0;
4950 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004951 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004952 return 0;
4953 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004954 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004955 return 0;
4956 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004957 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004958 return 0;
4959 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004960 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004961 return 0;
4962 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004963 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004964 return 0;
4965 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004966 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004967 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004968 case glslang::EOpAllMemoryBarrierWithGroupSync:
4969 // Control barrier with non-"None" semantic is also a memory barrier.
4970 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4971 return 0;
4972 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4973 // Control barrier with non-"None" semantic is also a memory barrier.
4974 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4975 return 0;
4976 case glslang::EOpWorkgroupMemoryBarrier:
4977 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4978 return 0;
4979 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4980 // Control barrier with non-"None" semantic is also a memory barrier.
4981 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4982 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004983#ifdef AMD_EXTENSIONS
4984 case glslang::EOpTime:
4985 {
4986 std::vector<spv::Id> args; // Dummy arguments
4987 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4988 return builder.setPrecision(id, precision);
4989 }
4990#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004991 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004992 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004993 return 0;
4994 }
4995}
4996
4997spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4998{
John Kessenich2f273362015-07-18 22:34:27 -06004999 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005000 spv::Id id;
5001 if (symbolValues.end() != iter) {
5002 id = iter->second;
5003 return id;
5004 }
5005
5006 // it was not found, create it
5007 id = createSpvVariable(symbol);
5008 symbolValues[symbol->getId()] = id;
5009
Rex Xuc884b4a2016-06-29 15:03:44 +08005010 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005011 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005012 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005013 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005014 if (symbol->getType().getQualifier().hasSpecConstantId())
5015 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005016 if (symbol->getQualifier().hasIndex())
5017 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5018 if (symbol->getQualifier().hasComponent())
5019 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5020 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005021 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005022 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005023 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005024 if (symbol->getQualifier().hasXfbBuffer())
5025 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5026 if (symbol->getQualifier().hasXfbOffset())
5027 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5028 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005029 // atomic counters use this:
5030 if (symbol->getQualifier().hasOffset())
5031 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005032 }
5033
scygan2c864272016-05-18 18:09:17 +02005034 if (symbol->getQualifier().hasLocation())
5035 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005036 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005037 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005038 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005039 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005040 }
John Kessenich140f3df2015-06-26 16:58:36 -06005041 if (symbol->getQualifier().hasSet())
5042 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005043 else if (IsDescriptorResource(symbol->getType())) {
5044 // default to 0
5045 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5046 }
John Kessenich140f3df2015-06-26 16:58:36 -06005047 if (symbol->getQualifier().hasBinding())
5048 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005049 if (symbol->getQualifier().hasAttachment())
5050 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005051 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005052 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005053 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005054 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005055 if (symbol->getQualifier().hasXfbBuffer())
5056 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5057 }
5058
Rex Xu1da878f2016-02-21 20:59:01 +08005059 if (symbol->getType().isImage()) {
5060 std::vector<spv::Decoration> memory;
5061 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5062 for (unsigned int i = 0; i < memory.size(); ++i)
5063 addDecoration(id, memory[i]);
5064 }
5065
John Kessenich140f3df2015-06-26 16:58:36 -06005066 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005067 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005068 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005069 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005070
John Kessenichecba76f2017-01-06 00:34:48 -07005071#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005072 if (builtIn == spv::BuiltInSampleMask) {
5073 spv::Decoration decoration;
5074 // GL_NV_sample_mask_override_coverage extension
5075 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005076 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005077 else
5078 decoration = (spv::Decoration)spv::DecorationMax;
5079 addDecoration(id, decoration);
5080 if (decoration != spv::DecorationMax) {
5081 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5082 }
5083 }
chaoc771d89f2017-01-13 01:10:53 -08005084 else if (builtIn == spv::BuiltInLayer) {
5085 // SPV_NV_viewport_array2 extension
5086 if (symbol->getQualifier().layoutViewportRelative)
5087 {
5088 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5089 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5090 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5091 }
5092 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5093 {
5094 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5095 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5096 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5097 }
5098 }
5099
chaoc6e5acae2016-12-20 13:28:52 -08005100 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005101 addDecoration(id, spv::DecorationPassthroughNV);
5102 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005103 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5104 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005105#endif
5106
John Kessenich140f3df2015-06-26 16:58:36 -06005107 return id;
5108}
5109
John Kessenich55e7d112015-11-15 21:33:39 -07005110// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005111void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5112{
John Kessenich4016e382016-07-15 11:53:56 -06005113 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005114 builder.addDecoration(id, dec);
5115}
5116
John Kessenich55e7d112015-11-15 21:33:39 -07005117// If 'dec' is valid, add a one-operand decoration to an object
5118void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5119{
John Kessenich4016e382016-07-15 11:53:56 -06005120 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005121 builder.addDecoration(id, dec, value);
5122}
5123
5124// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005125void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5126{
John Kessenich4016e382016-07-15 11:53:56 -06005127 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005128 builder.addMemberDecoration(id, (unsigned)member, dec);
5129}
5130
John Kessenich92187592016-02-01 13:45:25 -07005131// If 'dec' is valid, add a one-operand decoration to a struct member
5132void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5133{
John Kessenich4016e382016-07-15 11:53:56 -06005134 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005135 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5136}
5137
John Kessenich55e7d112015-11-15 21:33:39 -07005138// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005139// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005140//
5141// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5142//
5143// Recursively walk the nodes. The nodes form a tree whose leaves are
5144// regular constants, which themselves are trees that createSpvConstant()
5145// recursively walks. So, this function walks the "top" of the tree:
5146// - emit specialization constant-building instructions for specConstant
5147// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005148spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005149{
John Kessenich7cc0e282016-03-20 00:46:02 -06005150 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005151
qining4f4bb812016-04-03 23:55:17 -04005152 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005153 if (! node.getQualifier().specConstant) {
5154 // hand off to the non-spec-constant path
5155 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5156 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005157 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005158 nextConst, false);
5159 }
5160
5161 // We now know we have a specialization constant to build
5162
John Kessenichd94c0032016-05-30 19:29:40 -06005163 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005164 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5165 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5166 std::vector<spv::Id> dimConstId;
5167 for (int dim = 0; dim < 3; ++dim) {
5168 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5169 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5170 if (specConst)
5171 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5172 }
5173 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5174 }
5175
5176 // An AST node labelled as specialization constant should be a symbol node.
5177 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5178 if (auto* sn = node.getAsSymbolNode()) {
5179 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005180 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5181 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5182 // will set the builder into spec constant op instruction generating mode.
5183 sub_tree->traverse(this);
5184 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005185 } else if (auto* const_union_array = &sn->getConstArray()){
5186 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005187 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5188 builder.addName(id, sn->getName().c_str());
5189 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005190 }
5191 }
qining4f4bb812016-04-03 23:55:17 -04005192
5193 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5194 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005195 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005196 exit(1);
5197 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005198}
5199
John Kessenich140f3df2015-06-26 16:58:36 -06005200// Use 'consts' as the flattened glslang source of scalar constants to recursively
5201// build the aggregate SPIR-V constant.
5202//
5203// If there are not enough elements present in 'consts', 0 will be substituted;
5204// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5205//
qining08408382016-03-21 09:51:37 -04005206spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005207{
5208 // vector of constants for SPIR-V
5209 std::vector<spv::Id> spvConsts;
5210
5211 // Type is used for struct and array constants
5212 spv::Id typeId = convertGlslangToSpvType(glslangType);
5213
5214 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005215 glslang::TType elementType(glslangType, 0);
5216 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005217 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005218 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005219 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005220 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005221 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005222 } else if (glslangType.getStruct()) {
5223 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5224 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005225 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005226 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005227 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5228 bool zero = nextConst >= consts.size();
5229 switch (glslangType.getBasicType()) {
5230 case glslang::EbtInt:
5231 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5232 break;
5233 case glslang::EbtUint:
5234 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5235 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005236 case glslang::EbtInt64:
5237 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5238 break;
5239 case glslang::EbtUint64:
5240 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5241 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005242 case glslang::EbtFloat:
5243 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5244 break;
5245 case glslang::EbtDouble:
5246 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5247 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005248#ifdef AMD_EXTENSIONS
5249 case glslang::EbtFloat16:
5250 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5251 break;
5252#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005253 case glslang::EbtBool:
5254 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5255 break;
5256 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005257 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005258 break;
5259 }
5260 ++nextConst;
5261 }
5262 } else {
5263 // we have a non-aggregate (scalar) constant
5264 bool zero = nextConst >= consts.size();
5265 spv::Id scalar = 0;
5266 switch (glslangType.getBasicType()) {
5267 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005268 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005269 break;
5270 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005271 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005272 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005273 case glslang::EbtInt64:
5274 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5275 break;
5276 case glslang::EbtUint64:
5277 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5278 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005279 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005280 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005281 break;
5282 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005283 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005284 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005285#ifdef AMD_EXTENSIONS
5286 case glslang::EbtFloat16:
5287 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5288 break;
5289#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005290 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005291 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005292 break;
5293 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005294 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005295 break;
5296 }
5297 ++nextConst;
5298 return scalar;
5299 }
5300
5301 return builder.makeCompositeConstant(typeId, spvConsts);
5302}
5303
John Kessenich7c1aa102015-10-15 13:29:11 -06005304// Return true if the node is a constant or symbol whose reading has no
5305// non-trivial observable cost or effect.
5306bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5307{
5308 // don't know what this is
5309 if (node == nullptr)
5310 return false;
5311
5312 // a constant is safe
5313 if (node->getAsConstantUnion() != nullptr)
5314 return true;
5315
5316 // not a symbol means non-trivial
5317 if (node->getAsSymbolNode() == nullptr)
5318 return false;
5319
5320 // a symbol, depends on what's being read
5321 switch (node->getType().getQualifier().storage) {
5322 case glslang::EvqTemporary:
5323 case glslang::EvqGlobal:
5324 case glslang::EvqIn:
5325 case glslang::EvqInOut:
5326 case glslang::EvqConst:
5327 case glslang::EvqConstReadOnly:
5328 case glslang::EvqUniform:
5329 return true;
5330 default:
5331 return false;
5332 }
qining25262b32016-05-06 17:25:16 -04005333}
John Kessenich7c1aa102015-10-15 13:29:11 -06005334
5335// A node is trivial if it is a single operation with no side effects.
5336// Error on the side of saying non-trivial.
5337// Return true if trivial.
5338bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5339{
5340 if (node == nullptr)
5341 return false;
5342
5343 // symbols and constants are trivial
5344 if (isTrivialLeaf(node))
5345 return true;
5346
5347 // otherwise, it needs to be a simple operation or one or two leaf nodes
5348
5349 // not a simple operation
5350 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5351 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5352 if (binaryNode == nullptr && unaryNode == nullptr)
5353 return false;
5354
5355 // not on leaf nodes
5356 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5357 return false;
5358
5359 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5360 return false;
5361 }
5362
5363 switch (node->getAsOperator()->getOp()) {
5364 case glslang::EOpLogicalNot:
5365 case glslang::EOpConvIntToBool:
5366 case glslang::EOpConvUintToBool:
5367 case glslang::EOpConvFloatToBool:
5368 case glslang::EOpConvDoubleToBool:
5369 case glslang::EOpEqual:
5370 case glslang::EOpNotEqual:
5371 case glslang::EOpLessThan:
5372 case glslang::EOpGreaterThan:
5373 case glslang::EOpLessThanEqual:
5374 case glslang::EOpGreaterThanEqual:
5375 case glslang::EOpIndexDirect:
5376 case glslang::EOpIndexDirectStruct:
5377 case glslang::EOpLogicalXor:
5378 case glslang::EOpAny:
5379 case glslang::EOpAll:
5380 return true;
5381 default:
5382 return false;
5383 }
5384}
5385
5386// Emit short-circuiting code, where 'right' is never evaluated unless
5387// the left side is true (for &&) or false (for ||).
5388spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5389{
5390 spv::Id boolTypeId = builder.makeBoolType();
5391
5392 // emit left operand
5393 builder.clearAccessChain();
5394 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005395 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005396
5397 // Operands to accumulate OpPhi operands
5398 std::vector<spv::Id> phiOperands;
5399 // accumulate left operand's phi information
5400 phiOperands.push_back(leftId);
5401 phiOperands.push_back(builder.getBuildPoint()->getId());
5402
5403 // Make the two kinds of operation symmetric with a "!"
5404 // || => emit "if (! left) result = right"
5405 // && => emit "if ( left) result = right"
5406 //
5407 // TODO: this runtime "not" for || could be avoided by adding functionality
5408 // to 'builder' to have an "else" without an "then"
5409 if (op == glslang::EOpLogicalOr)
5410 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5411
5412 // make an "if" based on the left value
5413 spv::Builder::If ifBuilder(leftId, builder);
5414
5415 // emit right operand as the "then" part of the "if"
5416 builder.clearAccessChain();
5417 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005418 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005419
5420 // accumulate left operand's phi information
5421 phiOperands.push_back(rightId);
5422 phiOperands.push_back(builder.getBuildPoint()->getId());
5423
5424 // finish the "if"
5425 ifBuilder.makeEndIf();
5426
5427 // phi together the two results
5428 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5429}
5430
Rex Xu9d93a232016-05-05 12:30:44 +08005431// Return type Id of the imported set of extended instructions corresponds to the name.
5432// Import this set if it has not been imported yet.
5433spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5434{
5435 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5436 return extBuiltinMap[name];
5437 else {
Rex Xu51596642016-09-21 18:56:12 +08005438 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005439 spv::Id extBuiltins = builder.import(name);
5440 extBuiltinMap[name] = extBuiltins;
5441 return extBuiltins;
5442 }
5443}
5444
John Kessenich140f3df2015-06-26 16:58:36 -06005445}; // end anonymous namespace
5446
5447namespace glslang {
5448
John Kessenich68d78fd2015-07-12 19:28:10 -06005449void GetSpirvVersion(std::string& version)
5450{
John Kessenich9e55f632015-07-15 10:03:39 -06005451 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005452 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005453 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005454 version = buf;
5455}
5456
John Kessenich140f3df2015-06-26 16:58:36 -06005457// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005458void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005459{
5460 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005461 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005462 if (out.fail())
5463 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005464 for (int i = 0; i < (int)spirv.size(); ++i) {
5465 unsigned int word = spirv[i];
5466 out.write((const char*)&word, 4);
5467 }
5468 out.close();
5469}
5470
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005471// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005472void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005473{
5474 std::ofstream out;
5475 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005476 if (out.fail())
5477 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005478 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005479 if (varName != nullptr) {
5480 out << "\t #pragma once" << std::endl;
5481 out << "const uint32_t " << varName << "[] = {" << std::endl;
5482 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005483 const int WORDS_PER_LINE = 8;
5484 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5485 out << "\t";
5486 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5487 const unsigned int word = spirv[i + j];
5488 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5489 if (i + j + 1 < (int)spirv.size()) {
5490 out << ",";
5491 }
5492 }
5493 out << std::endl;
5494 }
Flavio15017db2017-02-15 14:29:33 -08005495 if (varName != nullptr) {
5496 out << "};";
5497 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005498 out.close();
5499}
5500
John Kessenich140f3df2015-06-26 16:58:36 -06005501//
5502// Set up the glslang traversal
5503//
5504void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5505{
Lei Zhang17535f72016-05-04 15:55:59 -04005506 spv::SpvBuildLogger logger;
5507 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005508}
5509
Lei Zhang17535f72016-05-04 15:55:59 -04005510void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005511{
John Kessenich140f3df2015-06-26 16:58:36 -06005512 TIntermNode* root = intermediate.getTreeRoot();
5513
5514 if (root == 0)
5515 return;
5516
5517 glslang::GetThreadPoolAllocator().push();
5518
Lei Zhang17535f72016-05-04 15:55:59 -04005519 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005520 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005521 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005522 it.dumpSpv(spirv);
5523
5524 glslang::GetThreadPoolAllocator().pop();
5525}
5526
5527}; // end namespace glslang