blob: a14b2bb1928cc8ef3ae8ad21357075725f7aacb8 [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 Kessenich927608b2017-01-06 12:34:14 -0700225 // Use SourceLanguageUnknown instead of SourceLanguageHLSL for now, until Vulkan knows what HLSL is
Dan Baker55d5f2d2016-08-15 16:05:45 -0400226 return spv::SourceLanguageUnknown;
John Kessenich140f3df2015-06-26 16:58:36 -0600227 default:
228 return spv::SourceLanguageUnknown;
229 }
230}
231
232// Translate glslang language (stage) to SPIR-V execution model.
233spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
234{
235 switch (stage) {
236 case EShLangVertex: return spv::ExecutionModelVertex;
237 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
238 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
239 case EShLangGeometry: return spv::ExecutionModelGeometry;
240 case EShLangFragment: return spv::ExecutionModelFragment;
241 case EShLangCompute: return spv::ExecutionModelGLCompute;
242 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700243 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600244 return spv::ExecutionModelFragment;
245 }
246}
247
248// Translate glslang type to SPIR-V storage class.
249spv::StorageClass TranslateStorageClass(const glslang::TType& type)
250{
251 if (type.getQualifier().isPipeInput())
252 return spv::StorageClassInput;
253 else if (type.getQualifier().isPipeOutput())
254 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700255 else if (type.getBasicType() == glslang::EbtAtomicUint)
256 return spv::StorageClassAtomicCounter;
John Kessenich4a57dce2017-02-24 19:15:46 -0700257 else if (type.containsOpaque())
258 return spv::StorageClassUniformConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600259 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700260 if (type.getQualifier().layoutPushConstant)
261 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600262 if (type.getBasicType() == glslang::EbtBlock)
263 return spv::StorageClassUniform;
264 else
265 return spv::StorageClassUniformConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600266 } else {
267 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700268 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
269 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600270 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
271 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400272 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700273 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600274 return spv::StorageClassFunction;
275 }
276 }
277}
278
279// Translate glslang sampler type to SPIR-V dimensionality.
280spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
281{
282 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700283 case glslang::Esd1D: return spv::Dim1D;
284 case glslang::Esd2D: return spv::Dim2D;
285 case glslang::Esd3D: return spv::Dim3D;
286 case glslang::EsdCube: return spv::DimCube;
287 case glslang::EsdRect: return spv::DimRect;
288 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700289 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600290 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700291 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600292 return spv::Dim2D;
293 }
294}
295
John Kessenichf6640762016-08-01 19:44:00 -0600296// Translate glslang precision to SPIR-V precision decorations.
297spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600298{
John Kessenichf6640762016-08-01 19:44:00 -0600299 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700300 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600301 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600302 default:
303 return spv::NoPrecision;
304 }
305}
306
John Kessenichf6640762016-08-01 19:44:00 -0600307// Translate glslang type to SPIR-V precision decorations.
308spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
309{
310 return TranslatePrecisionDecoration(type.getQualifier().precision);
311}
312
John Kessenich140f3df2015-06-26 16:58:36 -0600313// Translate glslang type to SPIR-V block decorations.
314spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
315{
316 if (type.getBasicType() == glslang::EbtBlock) {
317 switch (type.getQualifier().storage) {
318 case glslang::EvqUniform: return spv::DecorationBlock;
319 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
320 case glslang::EvqVaryingIn: return spv::DecorationBlock;
321 case glslang::EvqVaryingOut: return spv::DecorationBlock;
322 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700323 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600324 break;
325 }
326 }
327
John Kessenich4016e382016-07-15 11:53:56 -0600328 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600329}
330
Rex Xu1da878f2016-02-21 20:59:01 +0800331// Translate glslang type to SPIR-V memory decorations.
332void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
333{
334 if (qualifier.coherent)
335 memory.push_back(spv::DecorationCoherent);
336 if (qualifier.volatil)
337 memory.push_back(spv::DecorationVolatile);
338 if (qualifier.restrict)
339 memory.push_back(spv::DecorationRestrict);
340 if (qualifier.readonly)
341 memory.push_back(spv::DecorationNonWritable);
342 if (qualifier.writeonly)
343 memory.push_back(spv::DecorationNonReadable);
344}
345
John Kessenich140f3df2015-06-26 16:58:36 -0600346// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700347spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600348{
349 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700350 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600351 case glslang::ElmRowMajor:
352 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700353 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600354 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700355 default:
356 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600357 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600358 }
359 } else {
360 switch (type.getBasicType()) {
361 default:
John Kessenich4016e382016-07-15 11:53:56 -0600362 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600363 break;
364 case glslang::EbtBlock:
365 switch (type.getQualifier().storage) {
366 case glslang::EvqUniform:
367 case glslang::EvqBuffer:
368 switch (type.getQualifier().layoutPacking) {
369 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600370 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
371 default:
John Kessenich4016e382016-07-15 11:53:56 -0600372 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600373 }
374 case glslang::EvqVaryingIn:
375 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700376 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600378 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700379 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600380 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600381 }
382 }
383 }
384}
385
386// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600387// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700388// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800389spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600390{
Rex Xubbceed72016-05-21 09:40:44 +0800391 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700392 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600393 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800394 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700395 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700396 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600397 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800398#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800399 else if (qualifier.explicitInterp) {
400 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800401 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800402 }
Rex Xu9d93a232016-05-05 12:30:44 +0800403#endif
Rex Xubbceed72016-05-21 09:40:44 +0800404 else
John Kessenich4016e382016-07-15 11:53:56 -0600405 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800406}
407
408// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600409// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800410// should be applied.
411spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
412{
413 if (qualifier.patch)
414 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700415 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600416 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700417 else if (qualifier.sample) {
418 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600419 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700420 } else
John Kessenich4016e382016-07-15 11:53:56 -0600421 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600422}
423
John Kessenich92187592016-02-01 13:45:25 -0700424// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700425spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600426{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700427 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600428 return spv::DecorationInvariant;
429 else
John Kessenich4016e382016-07-15 11:53:56 -0600430 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600431}
432
qining9220dbb2016-05-04 17:34:38 -0400433// If glslang type is noContraction, return SPIR-V NoContraction decoration.
434spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
435{
436 if (qualifier.noContraction)
437 return spv::DecorationNoContraction;
438 else
John Kessenich4016e382016-07-15 11:53:56 -0600439 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400440}
441
David Netoa901ffe2016-06-08 14:11:40 +0100442// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
443// associated capabilities when required. For some built-in variables, a capability
444// is generated only when using the variable in an executable instruction, but not when
445// just declaring a struct member variable with it. This is true for PointSize,
446// ClipDistance, and CullDistance.
447spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600448{
449 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700450 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600451 // Defer adding the capability until the built-in is actually used.
452 if (! memberDeclaration) {
453 switch (glslangIntermediate->getStage()) {
454 case EShLangGeometry:
455 builder.addCapability(spv::CapabilityGeometryPointSize);
456 break;
457 case EShLangTessControl:
458 case EShLangTessEvaluation:
459 builder.addCapability(spv::CapabilityTessellationPointSize);
460 break;
461 default:
462 break;
463 }
John Kessenich92187592016-02-01 13:45:25 -0700464 }
465 return spv::BuiltInPointSize;
466
John Kessenichebb50532016-05-16 19:22:05 -0600467 // These *Distance capabilities logically belong here, but if the member is declared and
468 // then never used, consumers of SPIR-V prefer the capability not be declared.
469 // They are now generated when used, rather than here when declared.
470 // Potentially, the specification should be more clear what the minimum
471 // use needed is to trigger the capability.
472 //
John Kessenich92187592016-02-01 13:45:25 -0700473 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100474 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800475 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700476 return spv::BuiltInClipDistance;
477
478 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100479 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800480 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700481 return spv::BuiltInCullDistance;
482
483 case glslang::EbvViewportIndex:
Rex Xu5e317ff2017-03-16 23:02:39 +0800484 if (!memberDeclaration) {
485 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800486#ifdef NV_EXTENSIONS
Rex Xu5e317ff2017-03-16 23:02:39 +0800487 if (glslangIntermediate->getStage() == EShLangVertex ||
488 glslangIntermediate->getStage() == EShLangTessControl ||
489 glslangIntermediate->getStage() == EShLangTessEvaluation) {
490
491 builder.addExtension(spv::E_SPV_NV_viewport_array2);
492 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
493 }
chaoc771d89f2017-01-13 01:10:53 -0800494#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800495 }
John Kessenich92187592016-02-01 13:45:25 -0700496 return spv::BuiltInViewportIndex;
497
John Kessenich5e801132016-02-15 11:09:46 -0700498 case glslang::EbvSampleId:
499 builder.addCapability(spv::CapabilitySampleRateShading);
500 return spv::BuiltInSampleId;
501
502 case glslang::EbvSamplePosition:
503 builder.addCapability(spv::CapabilitySampleRateShading);
504 return spv::BuiltInSamplePosition;
505
506 case glslang::EbvSampleMask:
507 builder.addCapability(spv::CapabilitySampleRateShading);
508 return spv::BuiltInSampleMask;
509
John Kessenich78a45572016-07-08 14:05:15 -0600510 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800511 if (!memberDeclaration) {
512 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800513#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -0800514 if (glslangIntermediate->getStage() == EShLangVertex ||
515 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800516 glslangIntermediate->getStage() == EShLangTessEvaluation) {
517
chaoc771d89f2017-01-13 01:10:53 -0800518 builder.addExtension(spv::E_SPV_NV_viewport_array2);
519 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
520 }
chaoc771d89f2017-01-13 01:10:53 -0800521#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800522 }
523
John Kessenich78a45572016-07-08 14:05:15 -0600524 return spv::BuiltInLayer;
525
John Kessenich140f3df2015-06-26 16:58:36 -0600526 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600527 case glslang::EbvVertexId: return spv::BuiltInVertexId;
528 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700529 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
530 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800531
John Kessenichda581a22015-10-14 14:10:30 -0600532 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800533 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
534 builder.addCapability(spv::CapabilityDrawParameters);
535 return spv::BuiltInBaseVertex;
536
John Kessenichda581a22015-10-14 14:10:30 -0600537 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800538 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
539 builder.addCapability(spv::CapabilityDrawParameters);
540 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200541
John Kessenichda581a22015-10-14 14:10:30 -0600542 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800543 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
544 builder.addCapability(spv::CapabilityDrawParameters);
545 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200546
547 case glslang::EbvPrimitiveId:
548 if (glslangIntermediate->getStage() == EShLangFragment)
549 builder.addCapability(spv::CapabilityGeometry);
550 return spv::BuiltInPrimitiveId;
551
John Kessenich140f3df2015-06-26 16:58:36 -0600552 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600553 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
554 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
555 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
556 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
557 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
558 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
559 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600560 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
561 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
562 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
563 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
564 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
565 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
566 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
567 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800568
Rex Xu574ab042016-04-14 16:53:07 +0800569 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800570 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800571 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
572 return spv::BuiltInSubgroupSize;
573
Rex Xu574ab042016-04-14 16:53:07 +0800574 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800575 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800576 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
577 return spv::BuiltInSubgroupLocalInvocationId;
578
Rex Xu574ab042016-04-14 16:53:07 +0800579 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800580 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
581 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
582 return spv::BuiltInSubgroupEqMaskKHR;
583
Rex Xu574ab042016-04-14 16:53:07 +0800584 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800585 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
586 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
587 return spv::BuiltInSubgroupGeMaskKHR;
588
Rex Xu574ab042016-04-14 16:53:07 +0800589 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800590 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
591 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
592 return spv::BuiltInSubgroupGtMaskKHR;
593
Rex Xu574ab042016-04-14 16:53:07 +0800594 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800595 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
596 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
597 return spv::BuiltInSubgroupLeMaskKHR;
598
Rex Xu574ab042016-04-14 16:53:07 +0800599 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800600 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
601 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
602 return spv::BuiltInSubgroupLtMaskKHR;
603
Rex Xu9d93a232016-05-05 12:30:44 +0800604#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800605 case glslang::EbvBaryCoordNoPersp:
606 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
607 return spv::BuiltInBaryCoordNoPerspAMD;
608
609 case glslang::EbvBaryCoordNoPerspCentroid:
610 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
611 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
612
613 case glslang::EbvBaryCoordNoPerspSample:
614 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
615 return spv::BuiltInBaryCoordNoPerspSampleAMD;
616
617 case glslang::EbvBaryCoordSmooth:
618 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
619 return spv::BuiltInBaryCoordSmoothAMD;
620
621 case glslang::EbvBaryCoordSmoothCentroid:
622 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
623 return spv::BuiltInBaryCoordSmoothCentroidAMD;
624
625 case glslang::EbvBaryCoordSmoothSample:
626 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
627 return spv::BuiltInBaryCoordSmoothSampleAMD;
628
629 case glslang::EbvBaryCoordPullModel:
630 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
631 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800632#endif
chaoc771d89f2017-01-13 01:10:53 -0800633
John Kessenich6c8aaac2017-02-27 01:20:51 -0700634 case glslang::EbvDeviceIndex:
635 builder.addExtension(spv::E_SPV_KHR_device_group);
636 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700637 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700638
639 case glslang::EbvViewIndex:
640 builder.addExtension(spv::E_SPV_KHR_multiview);
641 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700642 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700643
chaoc771d89f2017-01-13 01:10:53 -0800644#ifdef NV_EXTENSIONS
645 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800646 if (!memberDeclaration) {
647 builder.addExtension(spv::E_SPV_NV_viewport_array2);
648 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
649 }
chaoc771d89f2017-01-13 01:10:53 -0800650 return spv::BuiltInViewportMaskNV;
651 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800652 if (!memberDeclaration) {
653 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
654 builder.addCapability(spv::CapabilityShaderStereoViewNV);
655 }
chaoc771d89f2017-01-13 01:10:53 -0800656 return spv::BuiltInSecondaryPositionNV;
657 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800658 if (!memberDeclaration) {
659 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
660 builder.addCapability(spv::CapabilityShaderStereoViewNV);
661 }
chaoc771d89f2017-01-13 01:10:53 -0800662 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800663 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800664 if (!memberDeclaration) {
665 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
666 builder.addCapability(spv::CapabilityPerViewAttributesNV);
667 }
chaocdf3956c2017-02-14 14:52:34 -0800668 return spv::BuiltInPositionPerViewNV;
669 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800670 if (!memberDeclaration) {
671 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
672 builder.addCapability(spv::CapabilityPerViewAttributesNV);
673 }
chaocdf3956c2017-02-14 14:52:34 -0800674 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800675#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800676 default:
677 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600678 }
679}
680
Rex Xufc618912015-09-09 16:42:49 +0800681// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700682spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800683{
684 assert(type.getBasicType() == glslang::EbtSampler);
685
John Kessenich5d0fa972016-02-15 11:57:00 -0700686 // Check for capabilities
687 switch (type.getQualifier().layoutFormat) {
688 case glslang::ElfRg32f:
689 case glslang::ElfRg16f:
690 case glslang::ElfR11fG11fB10f:
691 case glslang::ElfR16f:
692 case glslang::ElfRgba16:
693 case glslang::ElfRgb10A2:
694 case glslang::ElfRg16:
695 case glslang::ElfRg8:
696 case glslang::ElfR16:
697 case glslang::ElfR8:
698 case glslang::ElfRgba16Snorm:
699 case glslang::ElfRg16Snorm:
700 case glslang::ElfRg8Snorm:
701 case glslang::ElfR16Snorm:
702 case glslang::ElfR8Snorm:
703
704 case glslang::ElfRg32i:
705 case glslang::ElfRg16i:
706 case glslang::ElfRg8i:
707 case glslang::ElfR16i:
708 case glslang::ElfR8i:
709
710 case glslang::ElfRgb10a2ui:
711 case glslang::ElfRg32ui:
712 case glslang::ElfRg16ui:
713 case glslang::ElfRg8ui:
714 case glslang::ElfR16ui:
715 case glslang::ElfR8ui:
716 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
717 break;
718
719 default:
720 break;
721 }
722
723 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800724 switch (type.getQualifier().layoutFormat) {
725 case glslang::ElfNone: return spv::ImageFormatUnknown;
726 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
727 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
728 case glslang::ElfR32f: return spv::ImageFormatR32f;
729 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
730 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
731 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
732 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
733 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
734 case glslang::ElfR16f: return spv::ImageFormatR16f;
735 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
736 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
737 case glslang::ElfRg16: return spv::ImageFormatRg16;
738 case glslang::ElfRg8: return spv::ImageFormatRg8;
739 case glslang::ElfR16: return spv::ImageFormatR16;
740 case glslang::ElfR8: return spv::ImageFormatR8;
741 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
742 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
743 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
744 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
745 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
746 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
747 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
748 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
749 case glslang::ElfR32i: return spv::ImageFormatR32i;
750 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
751 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
752 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
753 case glslang::ElfR16i: return spv::ImageFormatR16i;
754 case glslang::ElfR8i: return spv::ImageFormatR8i;
755 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
756 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
757 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
758 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
759 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
760 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
761 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
762 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
763 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
764 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600765 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800766 }
767}
768
qining25262b32016-05-06 17:25:16 -0400769// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700770// descriptor set.
771bool IsDescriptorResource(const glslang::TType& type)
772{
John Kessenichf7497e22016-03-08 21:36:22 -0700773 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700774 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700775 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700776
777 // non block...
778 // basically samplerXXX/subpass/sampler/texture are all included
779 // if they are the global-scope-class, not the function parameter
780 // (or local, if they ever exist) class.
781 if (type.getBasicType() == glslang::EbtSampler)
782 return type.getQualifier().isUniformOrBuffer();
783
784 // None of the above.
785 return false;
786}
787
John Kesseniche0b6cad2015-12-24 10:30:13 -0700788void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
789{
790 if (child.layoutMatrix == glslang::ElmNone)
791 child.layoutMatrix = parent.layoutMatrix;
792
793 if (parent.invariant)
794 child.invariant = true;
795 if (parent.nopersp)
796 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800797#ifdef AMD_EXTENSIONS
798 if (parent.explicitInterp)
799 child.explicitInterp = true;
800#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700801 if (parent.flat)
802 child.flat = true;
803 if (parent.centroid)
804 child.centroid = true;
805 if (parent.patch)
806 child.patch = true;
807 if (parent.sample)
808 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800809 if (parent.coherent)
810 child.coherent = true;
811 if (parent.volatil)
812 child.volatil = true;
813 if (parent.restrict)
814 child.restrict = true;
815 if (parent.readonly)
816 child.readonly = true;
817 if (parent.writeonly)
818 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700819}
820
John Kessenichf2b7f332016-09-01 17:05:23 -0600821bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700822{
John Kessenich7b9fa252016-01-21 18:56:57 -0700823 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600824 // - struct members might inherit from a struct declaration
825 // (note that non-block structs don't explicitly inherit,
826 // only implicitly, meaning no decoration involved)
827 // - affect decorations on the struct members
828 // (note smooth does not, and expecting something like volatile
829 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700830 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600831 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700832}
833
John Kessenich140f3df2015-06-26 16:58:36 -0600834//
835// Implement the TGlslangToSpvTraverser class.
836//
837
Lei Zhang17535f72016-05-04 15:55:59 -0400838TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600839 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
840 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400841 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700842 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600843 glslangIntermediate(glslangIntermediate)
844{
845 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
846
847 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700848 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600849 stdBuiltins = builder.import("GLSL.std.450");
850 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600851 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
852 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600853
854 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600855 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
856 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600857 builder.addSourceExtension(it->c_str());
858
859 // Add the top-level modes for this shader.
860
John Kessenich92187592016-02-01 13:45:25 -0700861 if (glslangIntermediate->getXfbMode()) {
862 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600863 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700864 }
John Kessenich140f3df2015-06-26 16:58:36 -0600865
866 unsigned int mode;
867 switch (glslangIntermediate->getStage()) {
868 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600869 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600870 break;
871
872 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600873 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600874 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
875 break;
876
877 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600878 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600879 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700880 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
881 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
882 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600883 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600884 }
John Kessenich4016e382016-07-15 11:53:56 -0600885 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600886 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
887
John Kesseniche6903322015-10-13 16:29:02 -0600888 switch (glslangIntermediate->getVertexSpacing()) {
889 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
890 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
891 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600892 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600893 }
John Kessenich4016e382016-07-15 11:53:56 -0600894 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600895 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
896
897 switch (glslangIntermediate->getVertexOrder()) {
898 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
899 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600900 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600901 }
John Kessenich4016e382016-07-15 11:53:56 -0600902 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600903 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
904
905 if (glslangIntermediate->getPointMode())
906 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600907 break;
908
909 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600910 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600911 switch (glslangIntermediate->getInputPrimitive()) {
912 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
913 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
914 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700915 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600916 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600917 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600918 }
John Kessenich4016e382016-07-15 11:53:56 -0600919 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600920 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600921
John Kessenich140f3df2015-06-26 16:58:36 -0600922 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
923
924 switch (glslangIntermediate->getOutputPrimitive()) {
925 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
926 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
927 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600928 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600929 }
John Kessenich4016e382016-07-15 11:53:56 -0600930 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600931 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
932 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
933 break;
934
935 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600936 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600937 if (glslangIntermediate->getPixelCenterInteger())
938 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600939
John Kessenich140f3df2015-06-26 16:58:36 -0600940 if (glslangIntermediate->getOriginUpperLeft())
941 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600942 else
943 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600944
945 if (glslangIntermediate->getEarlyFragmentTests())
946 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
947
948 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600949 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
950 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600951 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600952 }
John Kessenich4016e382016-07-15 11:53:56 -0600953 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600954 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
955
956 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
957 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600958 break;
959
960 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600961 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600962 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
963 glslangIntermediate->getLocalSize(1),
964 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600965 break;
966
967 default:
968 break;
969 }
John Kessenich140f3df2015-06-26 16:58:36 -0600970}
971
John Kessenichfca82622016-11-26 13:23:20 -0700972// Finish creating SPV, after the traversal is complete.
973void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700974{
John Kessenich517fe7a2016-11-26 13:31:47 -0700975 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700976 builder.setBuildPoint(shaderEntry->getLastBlock());
977 builder.leaveFunction();
978 }
979
John Kessenich7ba63412015-12-20 17:37:07 -0700980 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100981 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
982 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700983
qiningda397332016-03-09 19:54:03 -0500984 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700985}
986
John Kessenichfca82622016-11-26 13:23:20 -0700987// Write the SPV into 'out'.
988void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -0600989{
John Kessenichfca82622016-11-26 13:23:20 -0700990 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -0600991}
992
993//
994// Implement the traversal functions.
995//
996// Return true from interior nodes to have the external traversal
997// continue on to children. Return false if children were
998// already processed.
999//
1000
1001//
qining25262b32016-05-06 17:25:16 -04001002// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001003// - uniform/input reads
1004// - output writes
1005// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1006// - something simple that degenerates into the last bullet
1007//
1008void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1009{
qining75d1d802016-04-06 14:42:01 -04001010 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1011 if (symbol->getType().getQualifier().isSpecConstant())
1012 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1013
John Kessenich140f3df2015-06-26 16:58:36 -06001014 // getSymbolId() will set up all the IO decorations on the first call.
1015 // Formal function parameters were mapped during makeFunctions().
1016 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001017
1018 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1019 if (builder.isPointer(id)) {
1020 spv::StorageClass sc = builder.getStorageClass(id);
1021 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1022 iOSet.insert(id);
1023 }
1024
1025 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001026 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001027 // Prepare to generate code for the access
1028
1029 // L-value chains will be computed left to right. We're on the symbol now,
1030 // which is the left-most part of the access chain, so now is "clear" time,
1031 // followed by setting the base.
1032 builder.clearAccessChain();
1033
1034 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001035 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001036 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001037 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001038 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001039 // These are also pure R-values.
1040 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001041 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001042 builder.setAccessChainRValue(id);
1043 else
1044 builder.setAccessChainLValue(id);
1045 }
1046}
1047
1048bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1049{
qining40887662016-04-03 22:20:42 -04001050 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1051 if (node->getType().getQualifier().isSpecConstant())
1052 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1053
John Kessenich140f3df2015-06-26 16:58:36 -06001054 // First, handle special cases
1055 switch (node->getOp()) {
1056 case glslang::EOpAssign:
1057 case glslang::EOpAddAssign:
1058 case glslang::EOpSubAssign:
1059 case glslang::EOpMulAssign:
1060 case glslang::EOpVectorTimesMatrixAssign:
1061 case glslang::EOpVectorTimesScalarAssign:
1062 case glslang::EOpMatrixTimesScalarAssign:
1063 case glslang::EOpMatrixTimesMatrixAssign:
1064 case glslang::EOpDivAssign:
1065 case glslang::EOpModAssign:
1066 case glslang::EOpAndAssign:
1067 case glslang::EOpInclusiveOrAssign:
1068 case glslang::EOpExclusiveOrAssign:
1069 case glslang::EOpLeftShiftAssign:
1070 case glslang::EOpRightShiftAssign:
1071 // A bin-op assign "a += b" means the same thing as "a = a + b"
1072 // where a is evaluated before b. For a simple assignment, GLSL
1073 // says to evaluate the left before the right. So, always, left
1074 // node then right node.
1075 {
1076 // get the left l-value, save it away
1077 builder.clearAccessChain();
1078 node->getLeft()->traverse(this);
1079 spv::Builder::AccessChain lValue = builder.getAccessChain();
1080
1081 // evaluate the right
1082 builder.clearAccessChain();
1083 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001084 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001085
1086 if (node->getOp() != glslang::EOpAssign) {
1087 // the left is also an r-value
1088 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001089 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001090
1091 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001092 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001093 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001094 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1095 node->getType().getBasicType());
1096
1097 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001098 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001099 }
1100
1101 // store the result
1102 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001103 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001104
1105 // assignments are expressions having an rValue after they are evaluated...
1106 builder.clearAccessChain();
1107 builder.setAccessChainRValue(rValue);
1108 }
1109 return false;
1110 case glslang::EOpIndexDirect:
1111 case glslang::EOpIndexDirectStruct:
1112 {
1113 // Get the left part of the access chain.
1114 node->getLeft()->traverse(this);
1115
1116 // Add the next element in the chain
1117
David Netoa901ffe2016-06-08 14:11:40 +01001118 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001119 if (! node->getLeft()->getType().isArray() &&
1120 node->getLeft()->getType().isVector() &&
1121 node->getOp() == glslang::EOpIndexDirect) {
1122 // This is essentially a hard-coded vector swizzle of size 1,
1123 // so short circuit the access-chain stuff with a swizzle.
1124 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001125 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001126 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001127 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001128 int spvIndex = glslangIndex;
1129 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1130 node->getOp() == glslang::EOpIndexDirectStruct)
1131 {
1132 // This may be, e.g., an anonymous block-member selection, which generally need
1133 // index remapping due to hidden members in anonymous blocks.
1134 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1135 assert(remapper.size() > 0);
1136 spvIndex = remapper[glslangIndex];
1137 }
John Kessenichebb50532016-05-16 19:22:05 -06001138
David Netoa901ffe2016-06-08 14:11:40 +01001139 // normal case for indexing array or structure or block
1140 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1141
1142 // Add capabilities here for accessing PointSize and clip/cull distance.
1143 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001144 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001145 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001146 }
1147 }
1148 return false;
1149 case glslang::EOpIndexIndirect:
1150 {
1151 // Structure or array or vector indirection.
1152 // Will use native SPIR-V access-chain for struct and array indirection;
1153 // matrices are arrays of vectors, so will also work for a matrix.
1154 // Will use the access chain's 'component' for variable index into a vector.
1155
1156 // This adapter is building access chains left to right.
1157 // Set up the access chain to the left.
1158 node->getLeft()->traverse(this);
1159
1160 // save it so that computing the right side doesn't trash it
1161 spv::Builder::AccessChain partial = builder.getAccessChain();
1162
1163 // compute the next index in the chain
1164 builder.clearAccessChain();
1165 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001166 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001167
1168 // restore the saved access chain
1169 builder.setAccessChain(partial);
1170
1171 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001172 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001173 else
John Kessenichfa668da2015-09-13 14:46:30 -06001174 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001175 }
1176 return false;
1177 case glslang::EOpVectorSwizzle:
1178 {
1179 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001180 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001181 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001182 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001183 }
1184 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001185 case glslang::EOpMatrixSwizzle:
1186 logger->missingFunctionality("matrix swizzle");
1187 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001188 case glslang::EOpLogicalOr:
1189 case glslang::EOpLogicalAnd:
1190 {
1191
1192 // These may require short circuiting, but can sometimes be done as straight
1193 // binary operations. The right operand must be short circuited if it has
1194 // side effects, and should probably be if it is complex.
1195 if (isTrivial(node->getRight()->getAsTyped()))
1196 break; // handle below as a normal binary operation
1197 // otherwise, we need to do dynamic short circuiting on the right operand
1198 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1199 builder.clearAccessChain();
1200 builder.setAccessChainRValue(result);
1201 }
1202 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001203 default:
1204 break;
1205 }
1206
1207 // Assume generic binary op...
1208
John Kessenich32cfd492016-02-02 12:37:46 -07001209 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001210 builder.clearAccessChain();
1211 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001212 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001213
John Kessenich32cfd492016-02-02 12:37:46 -07001214 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001215 builder.clearAccessChain();
1216 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001217 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001218
John Kessenich32cfd492016-02-02 12:37:46 -07001219 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001220 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001221 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001222 convertGlslangToSpvType(node->getType()), left, right,
1223 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001224
John Kessenich50e57562015-12-21 21:21:11 -07001225 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001226 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001227 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001228 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001229 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001230 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001231 return false;
1232 }
John Kessenich140f3df2015-06-26 16:58:36 -06001233}
1234
1235bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1236{
qining40887662016-04-03 22:20:42 -04001237 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1238 if (node->getType().getQualifier().isSpecConstant())
1239 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1240
John Kessenichfc51d282015-08-19 13:34:18 -06001241 spv::Id result = spv::NoResult;
1242
1243 // try texturing first
1244 result = createImageTextureFunctionCall(node);
1245 if (result != spv::NoResult) {
1246 builder.clearAccessChain();
1247 builder.setAccessChainRValue(result);
1248
1249 return false; // done with this node
1250 }
1251
1252 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001253
1254 if (node->getOp() == glslang::EOpArrayLength) {
1255 // Quite special; won't want to evaluate the operand.
1256
1257 // Normal .length() would have been constant folded by the front-end.
1258 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001259 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001260 assert(node->getOperand()->getType().isRuntimeSizedArray());
1261 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1262 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001263 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1264 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001265
1266 builder.clearAccessChain();
1267 builder.setAccessChainRValue(length);
1268
1269 return false;
1270 }
1271
John Kessenichfc51d282015-08-19 13:34:18 -06001272 // Start by evaluating the operand
1273
John Kessenich8c8505c2016-07-26 12:50:38 -06001274 // Does it need a swizzle inversion? If so, evaluation is inverted;
1275 // operate first on the swizzle base, then apply the swizzle.
1276 spv::Id invertedType = spv::NoType;
1277 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1278 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1279 invertedType = getInvertedSwizzleType(*node->getOperand());
1280
John Kessenich140f3df2015-06-26 16:58:36 -06001281 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001282 if (invertedType != spv::NoType)
1283 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1284 else
1285 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001286
Rex Xufc618912015-09-09 16:42:49 +08001287 spv::Id operand = spv::NoResult;
1288
1289 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1290 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001291 node->getOp() == glslang::EOpAtomicCounter ||
1292 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001293 operand = builder.accessChainGetLValue(); // Special case l-value operands
1294 else
John Kessenich32cfd492016-02-02 12:37:46 -07001295 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001296
John Kessenichf6640762016-08-01 19:44:00 -06001297 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001298 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001299
1300 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001301 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001302 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001303
1304 // if not, then possibly an operation
1305 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001306 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001307
1308 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001309 if (invertedType)
1310 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1311
John Kessenich140f3df2015-06-26 16:58:36 -06001312 builder.clearAccessChain();
1313 builder.setAccessChainRValue(result);
1314
1315 return false; // done with this node
1316 }
1317
1318 // it must be a special case, check...
1319 switch (node->getOp()) {
1320 case glslang::EOpPostIncrement:
1321 case glslang::EOpPostDecrement:
1322 case glslang::EOpPreIncrement:
1323 case glslang::EOpPreDecrement:
1324 {
1325 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001326 spv::Id one = 0;
1327 if (node->getBasicType() == glslang::EbtFloat)
1328 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001329 else if (node->getBasicType() == glslang::EbtDouble)
1330 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001331#ifdef AMD_EXTENSIONS
1332 else if (node->getBasicType() == glslang::EbtFloat16)
1333 one = builder.makeFloat16Constant(1.0F);
1334#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001335 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1336 one = builder.makeInt64Constant(1);
1337 else
1338 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001339 glslang::TOperator op;
1340 if (node->getOp() == glslang::EOpPreIncrement ||
1341 node->getOp() == glslang::EOpPostIncrement)
1342 op = glslang::EOpAdd;
1343 else
1344 op = glslang::EOpSub;
1345
John Kessenichf6640762016-08-01 19:44:00 -06001346 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001347 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001348 convertGlslangToSpvType(node->getType()), operand, one,
1349 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001350 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001351
1352 // The result of operation is always stored, but conditionally the
1353 // consumed result. The consumed result is always an r-value.
1354 builder.accessChainStore(result);
1355 builder.clearAccessChain();
1356 if (node->getOp() == glslang::EOpPreIncrement ||
1357 node->getOp() == glslang::EOpPreDecrement)
1358 builder.setAccessChainRValue(result);
1359 else
1360 builder.setAccessChainRValue(operand);
1361 }
1362
1363 return false;
1364
1365 case glslang::EOpEmitStreamVertex:
1366 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1367 return false;
1368 case glslang::EOpEndStreamPrimitive:
1369 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1370 return false;
1371
1372 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001373 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001374 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001375 }
John Kessenich140f3df2015-06-26 16:58:36 -06001376}
1377
1378bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1379{
qining27e04a02016-04-14 16:40:20 -04001380 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1381 if (node->getType().getQualifier().isSpecConstant())
1382 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1383
John Kessenichfc51d282015-08-19 13:34:18 -06001384 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001385 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1386 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001387
1388 // try texturing
1389 result = createImageTextureFunctionCall(node);
1390 if (result != spv::NoResult) {
1391 builder.clearAccessChain();
1392 builder.setAccessChainRValue(result);
1393
1394 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001395 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001396 // "imageStore" is a special case, which has no result
1397 return false;
1398 }
John Kessenichfc51d282015-08-19 13:34:18 -06001399
John Kessenich140f3df2015-06-26 16:58:36 -06001400 glslang::TOperator binOp = glslang::EOpNull;
1401 bool reduceComparison = true;
1402 bool isMatrix = false;
1403 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001404 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001405
1406 assert(node->getOp());
1407
John Kessenichf6640762016-08-01 19:44:00 -06001408 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001409
1410 switch (node->getOp()) {
1411 case glslang::EOpSequence:
1412 {
1413 if (preVisit)
1414 ++sequenceDepth;
1415 else
1416 --sequenceDepth;
1417
1418 if (sequenceDepth == 1) {
1419 // If this is the parent node of all the functions, we want to see them
1420 // early, so all call points have actual SPIR-V functions to reference.
1421 // In all cases, still let the traverser visit the children for us.
1422 makeFunctions(node->getAsAggregate()->getSequence());
1423
John Kessenich6fccb3c2016-09-19 16:01:41 -06001424 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001425 // anything else gets there, so visit out of order, doing them all now.
1426 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1427
John Kessenich6a60c2f2016-12-08 21:01:59 -07001428 // 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 -06001429 // so do them manually.
1430 visitFunctions(node->getAsAggregate()->getSequence());
1431
1432 return false;
1433 }
1434
1435 return true;
1436 }
1437 case glslang::EOpLinkerObjects:
1438 {
1439 if (visit == glslang::EvPreVisit)
1440 linkageOnly = true;
1441 else
1442 linkageOnly = false;
1443
1444 return true;
1445 }
1446 case glslang::EOpComma:
1447 {
1448 // processing from left to right naturally leaves the right-most
1449 // lying around in the access chain
1450 glslang::TIntermSequence& glslangOperands = node->getSequence();
1451 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1452 glslangOperands[i]->traverse(this);
1453
1454 return false;
1455 }
1456 case glslang::EOpFunction:
1457 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001458 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001459 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001460 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001461 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001462 } else {
1463 handleFunctionEntry(node);
1464 }
1465 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001466 if (inEntryPoint)
1467 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001468 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001469 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001470 }
1471
1472 return true;
1473 case glslang::EOpParameters:
1474 // Parameters will have been consumed by EOpFunction processing, but not
1475 // the body, so we still visited the function node's children, making this
1476 // child redundant.
1477 return false;
1478 case glslang::EOpFunctionCall:
1479 {
1480 if (node->isUserDefined())
1481 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001482 // 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 -07001483 if (result) {
1484 builder.clearAccessChain();
1485 builder.setAccessChainRValue(result);
1486 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001487 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001488
1489 return false;
1490 }
1491 case glslang::EOpConstructMat2x2:
1492 case glslang::EOpConstructMat2x3:
1493 case glslang::EOpConstructMat2x4:
1494 case glslang::EOpConstructMat3x2:
1495 case glslang::EOpConstructMat3x3:
1496 case glslang::EOpConstructMat3x4:
1497 case glslang::EOpConstructMat4x2:
1498 case glslang::EOpConstructMat4x3:
1499 case glslang::EOpConstructMat4x4:
1500 case glslang::EOpConstructDMat2x2:
1501 case glslang::EOpConstructDMat2x3:
1502 case glslang::EOpConstructDMat2x4:
1503 case glslang::EOpConstructDMat3x2:
1504 case glslang::EOpConstructDMat3x3:
1505 case glslang::EOpConstructDMat3x4:
1506 case glslang::EOpConstructDMat4x2:
1507 case glslang::EOpConstructDMat4x3:
1508 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001509#ifdef AMD_EXTENSIONS
1510 case glslang::EOpConstructF16Mat2x2:
1511 case glslang::EOpConstructF16Mat2x3:
1512 case glslang::EOpConstructF16Mat2x4:
1513 case glslang::EOpConstructF16Mat3x2:
1514 case glslang::EOpConstructF16Mat3x3:
1515 case glslang::EOpConstructF16Mat3x4:
1516 case glslang::EOpConstructF16Mat4x2:
1517 case glslang::EOpConstructF16Mat4x3:
1518 case glslang::EOpConstructF16Mat4x4:
1519#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001520 isMatrix = true;
1521 // fall through
1522 case glslang::EOpConstructFloat:
1523 case glslang::EOpConstructVec2:
1524 case glslang::EOpConstructVec3:
1525 case glslang::EOpConstructVec4:
1526 case glslang::EOpConstructDouble:
1527 case glslang::EOpConstructDVec2:
1528 case glslang::EOpConstructDVec3:
1529 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001530#ifdef AMD_EXTENSIONS
1531 case glslang::EOpConstructFloat16:
1532 case glslang::EOpConstructF16Vec2:
1533 case glslang::EOpConstructF16Vec3:
1534 case glslang::EOpConstructF16Vec4:
1535#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001536 case glslang::EOpConstructBool:
1537 case glslang::EOpConstructBVec2:
1538 case glslang::EOpConstructBVec3:
1539 case glslang::EOpConstructBVec4:
1540 case glslang::EOpConstructInt:
1541 case glslang::EOpConstructIVec2:
1542 case glslang::EOpConstructIVec3:
1543 case glslang::EOpConstructIVec4:
1544 case glslang::EOpConstructUint:
1545 case glslang::EOpConstructUVec2:
1546 case glslang::EOpConstructUVec3:
1547 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001548 case glslang::EOpConstructInt64:
1549 case glslang::EOpConstructI64Vec2:
1550 case glslang::EOpConstructI64Vec3:
1551 case glslang::EOpConstructI64Vec4:
1552 case glslang::EOpConstructUint64:
1553 case glslang::EOpConstructU64Vec2:
1554 case glslang::EOpConstructU64Vec3:
1555 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001556 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001557 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001558 {
1559 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001560 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001561 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001562 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001563 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001564 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001565 std::vector<spv::Id> constituents;
1566 for (int c = 0; c < (int)arguments.size(); ++c)
1567 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001568 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001569 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001570 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001571 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001572 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001573
1574 builder.clearAccessChain();
1575 builder.setAccessChainRValue(constructed);
1576
1577 return false;
1578 }
1579
1580 // These six are component-wise compares with component-wise results.
1581 // Forward on to createBinaryOperation(), requesting a vector result.
1582 case glslang::EOpLessThan:
1583 case glslang::EOpGreaterThan:
1584 case glslang::EOpLessThanEqual:
1585 case glslang::EOpGreaterThanEqual:
1586 case glslang::EOpVectorEqual:
1587 case glslang::EOpVectorNotEqual:
1588 {
1589 // Map the operation to a binary
1590 binOp = node->getOp();
1591 reduceComparison = false;
1592 switch (node->getOp()) {
1593 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1594 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1595 default: binOp = node->getOp(); break;
1596 }
1597
1598 break;
1599 }
1600 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001601 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001602 binOp = glslang::EOpMul;
1603 break;
1604 case glslang::EOpOuterProduct:
1605 // two vectors multiplied to make a matrix
1606 binOp = glslang::EOpOuterProduct;
1607 break;
1608 case glslang::EOpDot:
1609 {
qining25262b32016-05-06 17:25:16 -04001610 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001611 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001612 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001613 binOp = glslang::EOpMul;
1614 break;
1615 }
1616 case glslang::EOpMod:
1617 // when an aggregate, this is the floating-point mod built-in function,
1618 // which can be emitted by the one in createBinaryOperation()
1619 binOp = glslang::EOpMod;
1620 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001621 case glslang::EOpEmitVertex:
1622 case glslang::EOpEndPrimitive:
1623 case glslang::EOpBarrier:
1624 case glslang::EOpMemoryBarrier:
1625 case glslang::EOpMemoryBarrierAtomicCounter:
1626 case glslang::EOpMemoryBarrierBuffer:
1627 case glslang::EOpMemoryBarrierImage:
1628 case glslang::EOpMemoryBarrierShared:
1629 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001630 case glslang::EOpAllMemoryBarrierWithGroupSync:
1631 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1632 case glslang::EOpWorkgroupMemoryBarrier:
1633 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001634 noReturnValue = true;
1635 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1636 break;
1637
John Kessenich426394d2015-07-23 10:22:48 -06001638 case glslang::EOpAtomicAdd:
1639 case glslang::EOpAtomicMin:
1640 case glslang::EOpAtomicMax:
1641 case glslang::EOpAtomicAnd:
1642 case glslang::EOpAtomicOr:
1643 case glslang::EOpAtomicXor:
1644 case glslang::EOpAtomicExchange:
1645 case glslang::EOpAtomicCompSwap:
1646 atomic = true;
1647 break;
1648
John Kessenich140f3df2015-06-26 16:58:36 -06001649 default:
1650 break;
1651 }
1652
1653 //
1654 // See if it maps to a regular operation.
1655 //
John Kessenich140f3df2015-06-26 16:58:36 -06001656 if (binOp != glslang::EOpNull) {
1657 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1658 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1659 assert(left && right);
1660
1661 builder.clearAccessChain();
1662 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001663 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001664
1665 builder.clearAccessChain();
1666 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001667 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001668
qining25262b32016-05-06 17:25:16 -04001669 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001670 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001671 left->getType().getBasicType(), reduceComparison);
1672
1673 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001674 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001675 builder.clearAccessChain();
1676 builder.setAccessChainRValue(result);
1677
1678 return false;
1679 }
1680
John Kessenich426394d2015-07-23 10:22:48 -06001681 //
1682 // Create the list of operands.
1683 //
John Kessenich140f3df2015-06-26 16:58:36 -06001684 glslang::TIntermSequence& glslangOperands = node->getSequence();
1685 std::vector<spv::Id> operands;
1686 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001687 // special case l-value operands; there are just a few
1688 bool lvalue = false;
1689 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001690 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001691 case glslang::EOpModf:
1692 if (arg == 1)
1693 lvalue = true;
1694 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001695 case glslang::EOpInterpolateAtSample:
1696 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001697#ifdef AMD_EXTENSIONS
1698 case glslang::EOpInterpolateAtVertex:
1699#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001700 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001701 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001702
1703 // Does it need a swizzle inversion? If so, evaluation is inverted;
1704 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001705 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001706 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1707 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1708 }
Rex Xu7a26c172015-12-08 17:12:09 +08001709 break;
Rex Xud4782c12015-09-06 16:30:11 +08001710 case glslang::EOpAtomicAdd:
1711 case glslang::EOpAtomicMin:
1712 case glslang::EOpAtomicMax:
1713 case glslang::EOpAtomicAnd:
1714 case glslang::EOpAtomicOr:
1715 case glslang::EOpAtomicXor:
1716 case glslang::EOpAtomicExchange:
1717 case glslang::EOpAtomicCompSwap:
1718 if (arg == 0)
1719 lvalue = true;
1720 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001721 case glslang::EOpAddCarry:
1722 case glslang::EOpSubBorrow:
1723 if (arg == 2)
1724 lvalue = true;
1725 break;
1726 case glslang::EOpUMulExtended:
1727 case glslang::EOpIMulExtended:
1728 if (arg >= 2)
1729 lvalue = true;
1730 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001731 default:
1732 break;
1733 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001734 builder.clearAccessChain();
1735 if (invertedType != spv::NoType && arg == 0)
1736 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1737 else
1738 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001739 if (lvalue)
1740 operands.push_back(builder.accessChainGetLValue());
1741 else
John Kessenich32cfd492016-02-02 12:37:46 -07001742 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001743 }
John Kessenich426394d2015-07-23 10:22:48 -06001744
1745 if (atomic) {
1746 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001747 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001748 } else {
1749 // Pass through to generic operations.
1750 switch (glslangOperands.size()) {
1751 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001752 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001753 break;
1754 case 1:
qining25262b32016-05-06 17:25:16 -04001755 result = createUnaryOperation(
1756 node->getOp(), precision,
1757 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001758 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001759 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001760 break;
1761 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001762 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001763 break;
1764 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001765 if (invertedType)
1766 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001767 }
1768
1769 if (noReturnValue)
1770 return false;
1771
1772 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001773 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001774 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001775 } else {
1776 builder.clearAccessChain();
1777 builder.setAccessChainRValue(result);
1778 return false;
1779 }
1780}
1781
John Kessenich433e9ff2017-01-26 20:31:11 -07001782// This path handles both if-then-else and ?:
1783// The if-then-else has a node type of void, while
1784// ?: has either a void or a non-void node type
1785//
1786// Leaving the result, when not void:
1787// GLSL only has r-values as the result of a :?, but
1788// if we have an l-value, that can be more efficient if it will
1789// become the base of a complex r-value expression, because the
1790// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001791bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1792{
John Kessenich433e9ff2017-01-26 20:31:11 -07001793 // See if it simple and safe to generate OpSelect instead of using control flow.
1794 // Crucially, side effects must be avoided, and there are performance trade-offs.
1795 // Return true if good idea (and safe) for OpSelect, false otherwise.
1796 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001797 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1798 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001799 return false;
1800
1801 if (node->getTrueBlock() == nullptr ||
1802 node->getFalseBlock() == nullptr)
1803 return false;
1804
1805 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1806 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1807
1808 // return true if a single operand to ? : is okay for OpSelect
1809 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001810 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001811 };
1812
1813 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1814 operandOkay(node->getFalseBlock()->getAsTyped());
1815 };
1816
1817 // Emit OpSelect for this selection.
1818 const auto handleAsOpSelect = [&]() {
1819 node->getCondition()->traverse(this);
1820 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1821 node->getTrueBlock()->traverse(this);
1822 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1823 node->getFalseBlock()->traverse(this);
1824 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1825
1826 spv::Id select = builder.createTriOp(spv::OpSelect, convertGlslangToSpvType(node->getType()), condition, trueValue, falseValue);
1827 builder.clearAccessChain();
1828 builder.setAccessChainRValue(select);
1829 };
1830
1831 // Try for OpSelect
1832
1833 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001834 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1835 if (node->getType().getQualifier().isSpecConstant())
1836 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1837
John Kessenich433e9ff2017-01-26 20:31:11 -07001838 handleAsOpSelect();
1839 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001840 }
1841
John Kessenich433e9ff2017-01-26 20:31:11 -07001842 // Instead, emit control flow...
1843
1844 // Don't handle results as temporaries, because there will be two names
1845 // and better to leave SSA to later passes.
1846 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1847 ? spv::NoResult
1848 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1849
John Kessenich140f3df2015-06-26 16:58:36 -06001850 // emit the condition before doing anything with selection
1851 node->getCondition()->traverse(this);
1852
1853 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001854 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001855
John Kessenich433e9ff2017-01-26 20:31:11 -07001856 // emit the "then" statement
1857 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001858 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001859 if (result != spv::NoResult)
1860 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001861 }
1862
John Kessenich433e9ff2017-01-26 20:31:11 -07001863 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001864 ifBuilder.makeBeginElse();
1865 // emit the "else" statement
1866 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001867 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001868 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001869 }
1870
John Kessenich433e9ff2017-01-26 20:31:11 -07001871 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001872 ifBuilder.makeEndIf();
1873
John Kessenich433e9ff2017-01-26 20:31:11 -07001874 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001875 // GLSL only has r-values as the result of a :?, but
1876 // if we have an l-value, that can be more efficient if it will
1877 // become the base of a complex r-value expression, because the
1878 // next layer copies r-values into memory to use the access-chain mechanism
1879 builder.clearAccessChain();
1880 builder.setAccessChainLValue(result);
1881 }
1882
1883 return false;
1884}
1885
1886bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1887{
1888 // emit and get the condition before doing anything with switch
1889 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001890 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001891
1892 // browse the children to sort out code segments
1893 int defaultSegment = -1;
1894 std::vector<TIntermNode*> codeSegments;
1895 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1896 std::vector<int> caseValues;
1897 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1898 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1899 TIntermNode* child = *c;
1900 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001901 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001902 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001903 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001904 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1905 } else
1906 codeSegments.push_back(child);
1907 }
1908
qining25262b32016-05-06 17:25:16 -04001909 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001910 // statements between the last case and the end of the switch statement
1911 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1912 (int)codeSegments.size() == defaultSegment)
1913 codeSegments.push_back(nullptr);
1914
1915 // make the switch statement
1916 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001917 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001918
1919 // emit all the code in the segments
1920 breakForLoop.push(false);
1921 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1922 builder.nextSwitchSegment(segmentBlocks, s);
1923 if (codeSegments[s])
1924 codeSegments[s]->traverse(this);
1925 else
1926 builder.addSwitchBreak();
1927 }
1928 breakForLoop.pop();
1929
1930 builder.endSwitch(segmentBlocks);
1931
1932 return false;
1933}
1934
1935void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1936{
1937 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001938 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001939
1940 builder.clearAccessChain();
1941 builder.setAccessChainRValue(constant);
1942}
1943
1944bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1945{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001946 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001947 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001948 // Spec requires back edges to target header blocks, and every header block
1949 // must dominate its merge block. Make a header block first to ensure these
1950 // conditions are met. By definition, it will contain OpLoopMerge, followed
1951 // by a block-ending branch. But we don't want to put any other body/test
1952 // instructions in it, since the body/test may have arbitrary instructions,
1953 // including merges of its own.
1954 builder.setBuildPoint(&blocks.head);
1955 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001956 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001957 spv::Block& test = builder.makeNewBlock();
1958 builder.createBranch(&test);
1959
1960 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001961 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001962 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001963 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001964 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1965
1966 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001967 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001968 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001969 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001970 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001971 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001972
1973 builder.setBuildPoint(&blocks.continue_target);
1974 if (node->getTerminal())
1975 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001976 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001977 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001978 builder.createBranch(&blocks.body);
1979
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001980 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001981 builder.setBuildPoint(&blocks.body);
1982 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001983 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001984 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001985 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001986
1987 builder.setBuildPoint(&blocks.continue_target);
1988 if (node->getTerminal())
1989 node->getTerminal()->traverse(this);
1990 if (node->getTest()) {
1991 node->getTest()->traverse(this);
1992 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001993 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001994 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001995 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001996 // TODO: unless there was a break/return/discard instruction
1997 // somewhere in the body, this is an infinite loop, so we should
1998 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001999 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002000 }
John Kessenich140f3df2015-06-26 16:58:36 -06002001 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002002 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002003 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002004 return false;
2005}
2006
2007bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2008{
2009 if (node->getExpression())
2010 node->getExpression()->traverse(this);
2011
2012 switch (node->getFlowOp()) {
2013 case glslang::EOpKill:
2014 builder.makeDiscard();
2015 break;
2016 case glslang::EOpBreak:
2017 if (breakForLoop.top())
2018 builder.createLoopExit();
2019 else
2020 builder.addSwitchBreak();
2021 break;
2022 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002023 builder.createLoopContinue();
2024 break;
2025 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002026 if (node->getExpression()) {
2027 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2028 spv::Id returnId = accessChainLoad(glslangReturnType);
2029 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2030 builder.clearAccessChain();
2031 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2032 builder.setAccessChainLValue(copyId);
2033 multiTypeStore(glslangReturnType, returnId);
2034 returnId = builder.createLoad(copyId);
2035 }
2036 builder.makeReturn(false, returnId);
2037 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002038 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002039
2040 builder.clearAccessChain();
2041 break;
2042
2043 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002044 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002045 break;
2046 }
2047
2048 return false;
2049}
2050
2051spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2052{
qining25262b32016-05-06 17:25:16 -04002053 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002054 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002055 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002056 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002057 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002058 }
2059
2060 // Now, handle actual variables
2061 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
2062 spv::Id spvType = convertGlslangToSpvType(node->getType());
2063
2064 const char* name = node->getName().c_str();
2065 if (glslang::IsAnonymous(name))
2066 name = "";
2067
2068 return builder.createVariable(storageClass, spvType, name);
2069}
2070
2071// Return type Id of the sampled type.
2072spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2073{
2074 switch (sampler.type) {
2075 case glslang::EbtFloat: return builder.makeFloatType(32);
2076 case glslang::EbtInt: return builder.makeIntType(32);
2077 case glslang::EbtUint: return builder.makeUintType(32);
2078 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002079 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002080 return builder.makeFloatType(32);
2081 }
2082}
2083
John Kessenich8c8505c2016-07-26 12:50:38 -06002084// If node is a swizzle operation, return the type that should be used if
2085// the swizzle base is first consumed by another operation, before the swizzle
2086// is applied.
2087spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2088{
John Kessenichecba76f2017-01-06 00:34:48 -07002089 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002090 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2091 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2092 else
2093 return spv::NoType;
2094}
2095
2096// When inverting a swizzle with a parent op, this function
2097// will apply the swizzle operation to a completed parent operation.
2098spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2099{
2100 std::vector<unsigned> swizzle;
2101 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2102 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2103}
2104
John Kessenich8c8505c2016-07-26 12:50:38 -06002105// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2106void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2107{
2108 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2109 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2110 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2111}
2112
John Kessenich3ac051e2015-12-20 11:29:16 -07002113// Convert from a glslang type to an SPV type, by calling into a
2114// recursive version of this function. This establishes the inherited
2115// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002116spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2117{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002118 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002119}
2120
2121// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002122// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002123// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002124spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002125{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002126 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002127
2128 switch (type.getBasicType()) {
2129 case glslang::EbtVoid:
2130 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002131 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002132 break;
2133 case glslang::EbtFloat:
2134 spvType = builder.makeFloatType(32);
2135 break;
2136 case glslang::EbtDouble:
2137 spvType = builder.makeFloatType(64);
2138 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002139#ifdef AMD_EXTENSIONS
2140 case glslang::EbtFloat16:
2141 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002142 spvType = builder.makeFloatType(16);
2143 break;
2144#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002145 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002146 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2147 // a 32-bit int where non-0 means true.
2148 if (explicitLayout != glslang::ElpNone)
2149 spvType = builder.makeUintType(32);
2150 else
2151 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002152 break;
2153 case glslang::EbtInt:
2154 spvType = builder.makeIntType(32);
2155 break;
2156 case glslang::EbtUint:
2157 spvType = builder.makeUintType(32);
2158 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002159 case glslang::EbtInt64:
2160 builder.addCapability(spv::CapabilityInt64);
2161 spvType = builder.makeIntType(64);
2162 break;
2163 case glslang::EbtUint64:
2164 builder.addCapability(spv::CapabilityInt64);
2165 spvType = builder.makeUintType(64);
2166 break;
John Kessenich426394d2015-07-23 10:22:48 -06002167 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002168 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002169 spvType = builder.makeUintType(32);
2170 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002171 case glslang::EbtSampler:
2172 {
2173 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002174 if (sampler.sampler) {
2175 // pure sampler
2176 spvType = builder.makeSamplerType();
2177 } else {
2178 // an image is present, make its type
2179 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2180 sampler.image ? 2 : 1, TranslateImageFormat(type));
2181 if (sampler.combined) {
2182 // already has both image and sampler, make the combined type
2183 spvType = builder.makeSampledImageType(spvType);
2184 }
John Kessenich55e7d112015-11-15 21:33:39 -07002185 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002186 }
John Kessenich140f3df2015-06-26 16:58:36 -06002187 break;
2188 case glslang::EbtStruct:
2189 case glslang::EbtBlock:
2190 {
2191 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002192 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002193
2194 // Try to share structs for different layouts, but not yet for other
2195 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002196 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002197 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002198 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002199 break;
2200
2201 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002202 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002203 memberRemapper[glslangMembers].resize(glslangMembers->size());
2204 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002205 }
2206 break;
2207 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002208 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002209 break;
2210 }
2211
2212 if (type.isMatrix())
2213 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2214 else {
2215 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2216 if (type.getVectorSize() > 1)
2217 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2218 }
2219
2220 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002221 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2222
John Kessenichc9a80832015-09-12 12:17:44 -06002223 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002224 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002225 // We need to decorate array strides for types needing explicit layout, except blocks.
2226 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002227 // Use a dummy glslang type for querying internal strides of
2228 // arrays of arrays, but using just a one-dimensional array.
2229 glslang::TType simpleArrayType(type, 0); // deference type of the array
2230 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2231 simpleArrayType.getArraySizes().dereference();
2232
2233 // Will compute the higher-order strides here, rather than making a whole
2234 // pile of types and doing repetitive recursion on their contents.
2235 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2236 }
John Kessenichf8842e52016-01-04 19:22:56 -07002237
2238 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002239 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002240 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002241 if (stride > 0)
2242 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002243 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002244 }
2245 } else {
2246 // single-dimensional array, and don't yet have stride
2247
John Kessenichf8842e52016-01-04 19:22:56 -07002248 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002249 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2250 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002251 }
John Kessenich31ed4832015-09-09 17:51:38 -06002252
John Kessenichc9a80832015-09-12 12:17:44 -06002253 // Do the outer dimension, which might not be known for a runtime-sized array
2254 if (type.isRuntimeSizedArray()) {
2255 spvType = builder.makeRuntimeArray(spvType);
2256 } else {
2257 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002258 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002259 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002260 if (stride > 0)
2261 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002262 }
2263
2264 return spvType;
2265}
2266
John Kessenich0e737842017-03-24 18:38:16 -06002267// TODO: this functionality should exist at a higher level, in creating the AST
2268//
2269// Identify interface members that don't have their required extension turned on.
2270//
2271bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2272{
2273 auto& extensions = glslangIntermediate->getRequestedExtensions();
2274
2275 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2276 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2277 return true;
2278 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2279 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2280 return true;
2281
2282 return false;
2283};
2284
John Kessenich6090df02016-06-30 21:18:02 -06002285// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2286// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2287// Mutually recursive with convertGlslangToSpvType().
2288spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2289 const glslang::TTypeList* glslangMembers,
2290 glslang::TLayoutPacking explicitLayout,
2291 const glslang::TQualifier& qualifier)
2292{
2293 // Create a vector of struct types for SPIR-V to consume
2294 std::vector<spv::Id> spvMembers;
2295 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2296 int locationOffset = 0; // for use across struct members, when they are called recursively
2297 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2298 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2299 if (glslangMember.hiddenMember()) {
2300 ++memberDelta;
2301 if (type.getBasicType() == glslang::EbtBlock)
2302 memberRemapper[glslangMembers][i] = -1;
2303 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002304 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002305 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002306 if (filterMember(glslangMember))
2307 continue;
2308 }
John Kessenich6090df02016-06-30 21:18:02 -06002309 // modify just this child's view of the qualifier
2310 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2311 InheritQualifiers(memberQualifier, qualifier);
2312
2313 // manually inherit location; it's more complex
2314 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2315 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2316 if (qualifier.hasLocation())
2317 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2318
2319 // recurse
2320 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2321 }
2322 }
2323
2324 // Make the SPIR-V type
2325 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002326 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002327 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2328
2329 // Decorate it
2330 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2331
2332 return spvType;
2333}
2334
2335void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2336 const glslang::TTypeList* glslangMembers,
2337 glslang::TLayoutPacking explicitLayout,
2338 const glslang::TQualifier& qualifier,
2339 spv::Id spvType)
2340{
2341 // Name and decorate the non-hidden members
2342 int offset = -1;
2343 int locationOffset = 0; // for use within the members of this struct
2344 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2345 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2346 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002347 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002348 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002349 if (filterMember(glslangMember))
2350 continue;
2351 }
John Kessenich6090df02016-06-30 21:18:02 -06002352
2353 // modify just this child's view of the qualifier
2354 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2355 InheritQualifiers(memberQualifier, qualifier);
2356
2357 // using -1 above to indicate a hidden member
2358 if (member >= 0) {
2359 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2360 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2361 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2362 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002363 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2364 type.getQualifier().storage == glslang::EvqVaryingOut) {
2365 if (type.getBasicType() == glslang::EbtBlock ||
2366 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002367 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2368 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2369 }
2370 }
2371 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2372
2373 if (qualifier.storage == glslang::EvqBuffer) {
2374 std::vector<spv::Decoration> memory;
2375 TranslateMemoryDecoration(memberQualifier, memory);
2376 for (unsigned int i = 0; i < memory.size(); ++i)
2377 addMemberDecoration(spvType, member, memory[i]);
2378 }
2379
John Kessenich2f47bc92016-06-30 21:47:35 -06002380 // Compute location decoration; tricky based on whether inheritance is at play and
2381 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002382 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2383 // probably move to the linker stage of the front end proper, and just have the
2384 // answer sitting already distributed throughout the individual member locations.
2385 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002386 // Ignore member locations if the container is an array, as that's
2387 // ill-specified and decisions have been made to not allow this anyway.
2388 // The object itself must have a location, and that comes out from decorating the object,
2389 // not the type (this code decorates types).
2390 if (! type.isArray()) {
2391 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2392 // struct members should not have explicit locations
2393 assert(type.getBasicType() != glslang::EbtStruct);
2394 location = memberQualifier.layoutLocation;
2395 } else if (type.getBasicType() != glslang::EbtBlock) {
2396 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2397 // The members, and their nested types, must not themselves have Location decorations.
2398 } else if (qualifier.hasLocation()) // inheritance
2399 location = qualifier.layoutLocation + locationOffset;
2400 }
John Kessenich6090df02016-06-30 21:18:02 -06002401 if (location >= 0)
2402 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2403
John Kessenich2f47bc92016-06-30 21:47:35 -06002404 if (qualifier.hasLocation()) // track for upcoming inheritance
2405 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2406
John Kessenich6090df02016-06-30 21:18:02 -06002407 // component, XFB, others
2408 if (glslangMember.getQualifier().hasComponent())
2409 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2410 if (glslangMember.getQualifier().hasXfbOffset())
2411 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2412 else if (explicitLayout != glslang::ElpNone) {
2413 // figure out what to do with offset, which is accumulating
2414 int nextOffset;
2415 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2416 if (offset >= 0)
2417 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2418 offset = nextOffset;
2419 }
2420
2421 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2422 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2423
2424 // built-in variable decorations
2425 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002426 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002427 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002428
2429#ifdef NV_EXTENSIONS
2430 if (builtIn == spv::BuiltInLayer) {
2431 // SPV_NV_viewport_array2 extension
2432 if (glslangMember.getQualifier().layoutViewportRelative){
2433 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2434 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2435 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2436 }
2437 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2438 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2439 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2440 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2441 }
2442 }
chaocdf3956c2017-02-14 14:52:34 -08002443 if (glslangMember.getQualifier().layoutPassthrough) {
2444 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2445 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2446 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2447 }
chaoc771d89f2017-01-13 01:10:53 -08002448#endif
John Kessenich6090df02016-06-30 21:18:02 -06002449 }
2450 }
2451
2452 // Decorate the structure
2453 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2454 addDecoration(spvType, TranslateBlockDecoration(type));
2455 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2456 builder.addCapability(spv::CapabilityGeometryStreams);
2457 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2458 }
2459 if (glslangIntermediate->getXfbMode()) {
2460 builder.addCapability(spv::CapabilityTransformFeedback);
2461 if (type.getQualifier().hasXfbStride())
2462 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2463 if (type.getQualifier().hasXfbBuffer())
2464 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2465 }
2466}
2467
John Kessenich6c292d32016-02-15 20:58:50 -07002468// Turn the expression forming the array size into an id.
2469// This is not quite trivial, because of specialization constants.
2470// Sometimes, a raw constant is turned into an Id, and sometimes
2471// a specialization constant expression is.
2472spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2473{
2474 // First, see if this is sized with a node, meaning a specialization constant:
2475 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2476 if (specNode != nullptr) {
2477 builder.clearAccessChain();
2478 specNode->traverse(this);
2479 return accessChainLoad(specNode->getAsTyped()->getType());
2480 }
qining25262b32016-05-06 17:25:16 -04002481
John Kessenich6c292d32016-02-15 20:58:50 -07002482 // Otherwise, need a compile-time (front end) size, get it:
2483 int size = arraySizes.getDimSize(dim);
2484 assert(size > 0);
2485 return builder.makeUintConstant(size);
2486}
2487
John Kessenich103bef92016-02-08 21:38:15 -07002488// Wrap the builder's accessChainLoad to:
2489// - localize handling of RelaxedPrecision
2490// - use the SPIR-V inferred type instead of another conversion of the glslang type
2491// (avoids unnecessary work and possible type punning for structures)
2492// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002493spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2494{
John Kessenich103bef92016-02-08 21:38:15 -07002495 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2496 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2497
2498 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002499 if (type.getBasicType() == glslang::EbtBool) {
2500 if (builder.isScalarType(nominalTypeId)) {
2501 // Conversion for bool
2502 spv::Id boolType = builder.makeBoolType();
2503 if (nominalTypeId != boolType)
2504 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2505 } else if (builder.isVectorType(nominalTypeId)) {
2506 // Conversion for bvec
2507 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2508 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2509 if (nominalTypeId != bvecType)
2510 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2511 }
2512 }
John Kessenich103bef92016-02-08 21:38:15 -07002513
2514 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002515}
2516
Rex Xu27253232016-02-23 17:51:09 +08002517// Wrap the builder's accessChainStore to:
2518// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002519//
2520// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002521void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2522{
2523 // Need to convert to abstract types when necessary
2524 if (type.getBasicType() == glslang::EbtBool) {
2525 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2526
2527 if (builder.isScalarType(nominalTypeId)) {
2528 // Conversion for bool
2529 spv::Id boolType = builder.makeBoolType();
2530 if (nominalTypeId != boolType) {
2531 spv::Id zero = builder.makeUintConstant(0);
2532 spv::Id one = builder.makeUintConstant(1);
2533 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2534 }
2535 } else if (builder.isVectorType(nominalTypeId)) {
2536 // Conversion for bvec
2537 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2538 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2539 if (nominalTypeId != bvecType) {
2540 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2541 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2542 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2543 }
2544 }
2545 }
2546
2547 builder.accessChainStore(rvalue);
2548}
2549
John Kessenich4bf71552016-09-02 11:20:21 -06002550// For storing when types match at the glslang level, but not might match at the
2551// SPIR-V level.
2552//
2553// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002554// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002555// as in a member-decorated way.
2556//
2557// NOTE: This function can handle any store request; if it's not special it
2558// simplifies to a simple OpStore.
2559//
2560// Implicitly uses the existing builder.accessChain as the storage target.
2561void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2562{
John Kessenichb3e24e42016-09-11 12:33:43 -06002563 // we only do the complex path here if it's an aggregate
2564 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002565 accessChainStore(type, rValue);
2566 return;
2567 }
2568
John Kessenichb3e24e42016-09-11 12:33:43 -06002569 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002570 spv::Id rType = builder.getTypeId(rValue);
2571 spv::Id lValue = builder.accessChainGetLValue();
2572 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2573 if (lType == rType) {
2574 accessChainStore(type, rValue);
2575 return;
2576 }
2577
John Kessenichb3e24e42016-09-11 12:33:43 -06002578 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002579 // where the two types were the same type in GLSL. This requires member
2580 // by member copy, recursively.
2581
John Kessenichb3e24e42016-09-11 12:33:43 -06002582 // If an array, copy element by element.
2583 if (type.isArray()) {
2584 glslang::TType glslangElementType(type, 0);
2585 spv::Id elementRType = builder.getContainedTypeId(rType);
2586 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2587 // get the source member
2588 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002589
John Kessenichb3e24e42016-09-11 12:33:43 -06002590 // set up the target storage
2591 builder.clearAccessChain();
2592 builder.setAccessChainLValue(lValue);
2593 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002594
John Kessenichb3e24e42016-09-11 12:33:43 -06002595 // store the member
2596 multiTypeStore(glslangElementType, elementRValue);
2597 }
2598 } else {
2599 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002600
John Kessenichb3e24e42016-09-11 12:33:43 -06002601 // loop over structure members
2602 const glslang::TTypeList& members = *type.getStruct();
2603 for (int m = 0; m < (int)members.size(); ++m) {
2604 const glslang::TType& glslangMemberType = *members[m].type;
2605
2606 // get the source member
2607 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2608 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2609
2610 // set up the target storage
2611 builder.clearAccessChain();
2612 builder.setAccessChainLValue(lValue);
2613 builder.accessChainPush(builder.makeIntConstant(m));
2614
2615 // store the member
2616 multiTypeStore(glslangMemberType, memberRValue);
2617 }
John Kessenich4bf71552016-09-02 11:20:21 -06002618 }
2619}
2620
John Kessenichf85e8062015-12-19 13:57:10 -07002621// Decide whether or not this type should be
2622// decorated with offsets and strides, and if so
2623// whether std140 or std430 rules should be applied.
2624glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002625{
John Kessenichf85e8062015-12-19 13:57:10 -07002626 // has to be a block
2627 if (type.getBasicType() != glslang::EbtBlock)
2628 return glslang::ElpNone;
2629
2630 // has to be a uniform or buffer block
2631 if (type.getQualifier().storage != glslang::EvqUniform &&
2632 type.getQualifier().storage != glslang::EvqBuffer)
2633 return glslang::ElpNone;
2634
2635 // return the layout to use
2636 switch (type.getQualifier().layoutPacking) {
2637 case glslang::ElpStd140:
2638 case glslang::ElpStd430:
2639 return type.getQualifier().layoutPacking;
2640 default:
2641 return glslang::ElpNone;
2642 }
John Kessenich31ed4832015-09-09 17:51:38 -06002643}
2644
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002645// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002646int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002647{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002648 int size;
John Kessenich49987892015-12-29 17:11:44 -07002649 int stride;
2650 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002651
2652 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002653}
2654
John Kessenich49987892015-12-29 17:11:44 -07002655// 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 -07002656// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002657int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002658{
John Kessenich49987892015-12-29 17:11:44 -07002659 glslang::TType elementType;
2660 elementType.shallowCopy(matrixType);
2661 elementType.clearArraySizes();
2662
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002663 int size;
John Kessenich49987892015-12-29 17:11:44 -07002664 int stride;
2665 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2666
2667 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002668}
2669
John Kessenich5e4b1242015-08-06 22:53:06 -06002670// Given a member type of a struct, realign the current offset for it, and compute
2671// the next (not yet aligned) offset for the next member, which will get aligned
2672// on the next call.
2673// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2674// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2675// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002676void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002677 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002678{
2679 // this will get a positive value when deemed necessary
2680 nextOffset = -1;
2681
John Kessenich5e4b1242015-08-06 22:53:06 -06002682 // override anything in currentOffset with user-set offset
2683 if (memberType.getQualifier().hasOffset())
2684 currentOffset = memberType.getQualifier().layoutOffset;
2685
2686 // It could be that current linker usage in glslang updated all the layoutOffset,
2687 // in which case the following code does not matter. But, that's not quite right
2688 // once cross-compilation unit GLSL validation is done, as the original user
2689 // settings are needed in layoutOffset, and then the following will come into play.
2690
John Kessenichf85e8062015-12-19 13:57:10 -07002691 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002692 if (! memberType.getQualifier().hasOffset())
2693 currentOffset = -1;
2694
2695 return;
2696 }
2697
John Kessenichf85e8062015-12-19 13:57:10 -07002698 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002699 if (currentOffset < 0)
2700 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002701
John Kessenich5e4b1242015-08-06 22:53:06 -06002702 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2703 // but possibly not yet correctly aligned.
2704
2705 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002706 int dummyStride;
2707 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002708 glslang::RoundToPow2(currentOffset, memberAlignment);
2709 nextOffset = currentOffset + memberSize;
2710}
2711
David Netoa901ffe2016-06-08 14:11:40 +01002712void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002713{
David Netoa901ffe2016-06-08 14:11:40 +01002714 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2715 switch (glslangBuiltIn)
2716 {
2717 case glslang::EbvClipDistance:
2718 case glslang::EbvCullDistance:
2719 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002720#ifdef NV_EXTENSIONS
2721 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002722 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002723 case glslang::EbvViewportMaskNV:
2724 case glslang::EbvSecondaryPositionNV:
2725 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002726 case glslang::EbvPositionPerViewNV:
2727 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002728#endif
David Netoa901ffe2016-06-08 14:11:40 +01002729 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2730 // Alternately, we could just call this for any glslang built-in, since the
2731 // capability already guards against duplicates.
2732 TranslateBuiltInDecoration(glslangBuiltIn, false);
2733 break;
2734 default:
2735 // Capabilities were already generated when the struct was declared.
2736 break;
2737 }
John Kessenichebb50532016-05-16 19:22:05 -06002738}
2739
John Kessenich6fccb3c2016-09-19 16:01:41 -06002740bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002741{
John Kessenicheee9d532016-09-19 18:09:30 -06002742 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002743}
2744
2745// Make all the functions, skeletally, without actually visiting their bodies.
2746void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2747{
2748 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2749 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002750 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002751 continue;
2752
2753 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002754 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002755 //
qining25262b32016-05-06 17:25:16 -04002756 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002757 // function. What it is an address of varies:
2758 //
John Kessenich4bf71552016-09-02 11:20:21 -06002759 // - "in" parameters not marked as "const" can be written to without modifying the calling
2760 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002761 //
2762 // - "const in" parameters can just be the r-value, as no writes need occur.
2763 //
John Kessenich4bf71552016-09-02 11:20:21 -06002764 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2765 // 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 -06002766
2767 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002768 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002769 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2770
John Kessenich37789792017-03-21 23:56:40 -06002771 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() == glslangIntermediate->implicitThisName;
2772
John Kessenich140f3df2015-06-26 16:58:36 -06002773 for (int p = 0; p < (int)parameters.size(); ++p) {
2774 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2775 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002776 // can we pass by reference?
2777 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002778 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002779 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002780 (p == 0 && implicitThis)) // implicit 'this'
Jason Ekstranded15ef12016-06-08 13:54:48 -07002781 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2782 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002783 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2784 else
John Kessenich4bf71552016-09-02 11:20:21 -06002785 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002786 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002787 paramTypes.push_back(typeId);
2788 }
2789
2790 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002791 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2792 convertGlslangToSpvType(glslFunction->getType()),
2793 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06002794 if (implicitThis)
2795 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06002796
2797 // Track function to emit/call later
2798 functionMap[glslFunction->getName().c_str()] = function;
2799
2800 // Set the parameter id's
2801 for (int p = 0; p < (int)parameters.size(); ++p) {
2802 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2803 // give a name too
2804 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2805 }
2806 }
2807}
2808
2809// Process all the initializers, while skipping the functions and link objects
2810void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2811{
2812 builder.setBuildPoint(shaderEntry->getLastBlock());
2813 for (int i = 0; i < (int)initializers.size(); ++i) {
2814 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2815 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2816
2817 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002818 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002819 initializer->traverse(this);
2820 }
2821 }
2822}
2823
2824// Process all the functions, while skipping initializers.
2825void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2826{
2827 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2828 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002829 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002830 node->traverse(this);
2831 }
2832}
2833
2834void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2835{
qining25262b32016-05-06 17:25:16 -04002836 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002837 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002838 currentFunction = functionMap[node->getName().c_str()];
2839 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002840 builder.setBuildPoint(functionBlock);
2841}
2842
Rex Xu04db3f52015-09-16 11:44:02 +08002843void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002844{
Rex Xufc618912015-09-09 16:42:49 +08002845 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002846
2847 glslang::TSampler sampler = {};
2848 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002849 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002850 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2851 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2852 }
2853
John Kessenich140f3df2015-06-26 16:58:36 -06002854 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2855 builder.clearAccessChain();
2856 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002857
2858 // Special case l-value operands
2859 bool lvalue = false;
2860 switch (node.getOp()) {
2861 case glslang::EOpImageAtomicAdd:
2862 case glslang::EOpImageAtomicMin:
2863 case glslang::EOpImageAtomicMax:
2864 case glslang::EOpImageAtomicAnd:
2865 case glslang::EOpImageAtomicOr:
2866 case glslang::EOpImageAtomicXor:
2867 case glslang::EOpImageAtomicExchange:
2868 case glslang::EOpImageAtomicCompSwap:
2869 if (i == 0)
2870 lvalue = true;
2871 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002872 case glslang::EOpSparseImageLoad:
2873 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2874 lvalue = true;
2875 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002876 case glslang::EOpSparseTexture:
2877 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2878 lvalue = true;
2879 break;
2880 case glslang::EOpSparseTextureClamp:
2881 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2882 lvalue = true;
2883 break;
2884 case glslang::EOpSparseTextureLod:
2885 case glslang::EOpSparseTextureOffset:
2886 if (i == 3)
2887 lvalue = true;
2888 break;
2889 case glslang::EOpSparseTextureFetch:
2890 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2891 lvalue = true;
2892 break;
2893 case glslang::EOpSparseTextureFetchOffset:
2894 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2895 lvalue = true;
2896 break;
2897 case glslang::EOpSparseTextureLodOffset:
2898 case glslang::EOpSparseTextureGrad:
2899 case glslang::EOpSparseTextureOffsetClamp:
2900 if (i == 4)
2901 lvalue = true;
2902 break;
2903 case glslang::EOpSparseTextureGradOffset:
2904 case glslang::EOpSparseTextureGradClamp:
2905 if (i == 5)
2906 lvalue = true;
2907 break;
2908 case glslang::EOpSparseTextureGradOffsetClamp:
2909 if (i == 6)
2910 lvalue = true;
2911 break;
2912 case glslang::EOpSparseTextureGather:
2913 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2914 lvalue = true;
2915 break;
2916 case glslang::EOpSparseTextureGatherOffset:
2917 case glslang::EOpSparseTextureGatherOffsets:
2918 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2919 lvalue = true;
2920 break;
Rex Xufc618912015-09-09 16:42:49 +08002921 default:
2922 break;
2923 }
2924
Rex Xu6b86d492015-09-16 17:48:22 +08002925 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002926 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002927 else
John Kessenich32cfd492016-02-02 12:37:46 -07002928 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002929 }
2930}
2931
John Kessenichfc51d282015-08-19 13:34:18 -06002932void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002933{
John Kessenichfc51d282015-08-19 13:34:18 -06002934 builder.clearAccessChain();
2935 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002936 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002937}
John Kessenich140f3df2015-06-26 16:58:36 -06002938
John Kessenichfc51d282015-08-19 13:34:18 -06002939spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2940{
Rex Xufc618912015-09-09 16:42:49 +08002941 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002942 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002943 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002944 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002945
John Kessenichfc51d282015-08-19 13:34:18 -06002946 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002947 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2948 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2949 std::vector<spv::Id> arguments;
2950 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002951 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002952 else
2953 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002954 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002955
2956 spv::Builder::TextureParameters params = { };
2957 params.sampler = arguments[0];
2958
Rex Xu04db3f52015-09-16 11:44:02 +08002959 glslang::TCrackedTextureOp cracked;
2960 node->crackTexture(sampler, cracked);
2961
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002962 const bool isUnsignedResult =
2963 node->getType().getBasicType() == glslang::EbtUint64 ||
2964 node->getType().getBasicType() == glslang::EbtUint;
2965
John Kessenichfc51d282015-08-19 13:34:18 -06002966 // Check for queries
2967 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002968 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
2969 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07002970 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002971
John Kessenichfc51d282015-08-19 13:34:18 -06002972 switch (node->getOp()) {
2973 case glslang::EOpImageQuerySize:
2974 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002975 if (arguments.size() > 1) {
2976 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002977 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002978 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002979 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06002980 case glslang::EOpImageQuerySamples:
2981 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002982 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06002983 case glslang::EOpTextureQueryLod:
2984 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002985 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06002986 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002987 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08002988 case glslang::EOpSparseTexelsResident:
2989 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002990 default:
2991 assert(0);
2992 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002993 }
John Kessenich140f3df2015-06-26 16:58:36 -06002994 }
2995
Rex Xufc618912015-09-09 16:42:49 +08002996 // Check for image functions other than queries
2997 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002998 std::vector<spv::Id> operands;
2999 auto opIt = arguments.begin();
3000 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003001
3002 // Handle subpass operations
3003 // TODO: GLSL should change to have the "MS" only on the type rather than the
3004 // built-in function.
3005 if (cracked.subpass) {
3006 // add on the (0,0) coordinate
3007 spv::Id zero = builder.makeIntConstant(0);
3008 std::vector<spv::Id> comps;
3009 comps.push_back(zero);
3010 comps.push_back(zero);
3011 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3012 if (sampler.ms) {
3013 operands.push_back(spv::ImageOperandsSampleMask);
3014 operands.push_back(*(opIt++));
3015 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003016 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003017 }
3018
John Kessenich56bab042015-09-16 10:54:31 -06003019 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003020 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003021 if (sampler.ms) {
3022 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003023 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003024 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003025 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3026 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003027 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003028 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003029 if (sampler.ms) {
3030 operands.push_back(*(opIt + 1));
3031 operands.push_back(spv::ImageOperandsSampleMask);
3032 operands.push_back(*opIt);
3033 } else
3034 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003035 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003036 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3037 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003038 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003039 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3040 builder.addCapability(spv::CapabilitySparseResidency);
3041 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3042 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3043
3044 if (sampler.ms) {
3045 operands.push_back(spv::ImageOperandsSampleMask);
3046 operands.push_back(*opIt++);
3047 }
3048
3049 // Create the return type that was a special structure
3050 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003051 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003052 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3053 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3054
3055 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3056
3057 // Decode the return type
3058 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3059 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003060 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003061 // Process image atomic operations
3062
3063 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3064 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003065 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003066
John Kessenich8c8505c2016-07-26 12:50:38 -06003067 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003068 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003069
3070 std::vector<spv::Id> operands;
3071 operands.push_back(pointer);
3072 for (; opIt != arguments.end(); ++opIt)
3073 operands.push_back(*opIt);
3074
John Kessenich8c8505c2016-07-26 12:50:38 -06003075 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003076 }
3077 }
3078
3079 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003080 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003081 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3082
John Kessenichfc51d282015-08-19 13:34:18 -06003083 // check for bias argument
3084 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003085 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003086 int nonBiasArgCount = 2;
3087 if (cracked.offset)
3088 ++nonBiasArgCount;
3089 if (cracked.grad)
3090 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003091 if (cracked.lodClamp)
3092 ++nonBiasArgCount;
3093 if (sparse)
3094 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003095
3096 if ((int)arguments.size() > nonBiasArgCount)
3097 bias = true;
3098 }
3099
John Kessenicha5c33d62016-06-02 23:45:21 -06003100 // See if the sampler param should really be just the SPV image part
3101 if (cracked.fetch) {
3102 // a fetch needs to have the image extracted first
3103 if (builder.isSampledImage(params.sampler))
3104 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3105 }
3106
John Kessenichfc51d282015-08-19 13:34:18 -06003107 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003108
John Kessenichfc51d282015-08-19 13:34:18 -06003109 params.coords = arguments[1];
3110 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003111 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003112
3113 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003114 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003115 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003116 ++extraArgs;
3117 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003118 params.Dref = arguments[2];
3119 ++extraArgs;
3120 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003121 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003122 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003123 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003124 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003125 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003126 dRefComp = builder.getNumComponents(params.coords) - 1;
3127 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003128 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3129 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003130
3131 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003132 if (cracked.lod) {
3133 params.lod = arguments[2];
3134 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003135 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3136 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3137 noImplicitLod = true;
3138 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003139
3140 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003141 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003142 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003143 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003144 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003145
3146 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003147 if (cracked.grad) {
3148 params.gradX = arguments[2 + extraArgs];
3149 params.gradY = arguments[3 + extraArgs];
3150 extraArgs += 2;
3151 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003152
3153 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003154 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003155 params.offset = arguments[2 + extraArgs];
3156 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003157 } else if (cracked.offsets) {
3158 params.offsets = arguments[2 + extraArgs];
3159 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003160 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003161
3162 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003163 if (cracked.lodClamp) {
3164 params.lodClamp = arguments[2 + extraArgs];
3165 ++extraArgs;
3166 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003167
3168 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003169 if (sparse) {
3170 params.texelOut = arguments[2 + extraArgs];
3171 ++extraArgs;
3172 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003173
3174 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003175 if (bias) {
3176 params.bias = arguments[2 + extraArgs];
3177 ++extraArgs;
3178 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003179
3180 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003181 if (cracked.gather && ! sampler.shadow) {
3182 // default component is 0, if missing, otherwise an argument
3183 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003184 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003185 ++extraArgs;
3186 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003187 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003188 }
3189 }
John Kessenichfc51d282015-08-19 13:34:18 -06003190
John Kessenich65336482016-06-16 14:06:26 -06003191 // projective component (might not to move)
3192 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3193 // are divided by the last component of P."
3194 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3195 // unused components will appear after all used components."
3196 if (cracked.proj) {
3197 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3198 int projTargetComp;
3199 switch (sampler.dim) {
3200 case glslang::Esd1D: projTargetComp = 1; break;
3201 case glslang::Esd2D: projTargetComp = 2; break;
3202 case glslang::EsdRect: projTargetComp = 2; break;
3203 default: projTargetComp = projSourceComp; break;
3204 }
3205 // copy the projective coordinate if we have to
3206 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003207 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003208 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3209 projSourceComp);
3210 params.coords = builder.createCompositeInsert(projComp, params.coords,
3211 builder.getTypeId(params.coords), projTargetComp);
3212 }
3213 }
3214
John Kessenich8c8505c2016-07-26 12:50:38 -06003215 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003216}
3217
3218spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3219{
3220 // Grab the function's pointer from the previously created function
3221 spv::Function* function = functionMap[node->getName().c_str()];
3222 if (! function)
3223 return 0;
3224
3225 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3226 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3227
3228 // See comments in makeFunctions() for details about the semantics for parameter passing.
3229 //
3230 // These imply we need a four step process:
3231 // 1. Evaluate the arguments
3232 // 2. Allocate and make copies of in, out, and inout arguments
3233 // 3. Make the call
3234 // 4. Copy back the results
3235
3236 // 1. Evaluate the arguments
3237 std::vector<spv::Builder::AccessChain> lValues;
3238 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003239 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003240 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003241 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003242 // build l-value
3243 builder.clearAccessChain();
3244 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003245 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003246 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003247 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003248 // save l-value
3249 lValues.push_back(builder.getAccessChain());
3250 } else {
3251 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003252 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003253 }
3254 }
3255
3256 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3257 // copy the original into that space.
3258 //
3259 // Also, build up the list of actual arguments to pass in for the call
3260 int lValueCount = 0;
3261 int rValueCount = 0;
3262 std::vector<spv::Id> spvArgs;
3263 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003264 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003265 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003266 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003267 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3268 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003269 builder.setAccessChain(lValues[lValueCount]);
3270 arg = builder.accessChainGetLValue();
3271 ++lValueCount;
3272 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003273 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003274 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3275 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3276 // need to copy the input into output space
3277 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003278 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003279 builder.clearAccessChain();
3280 builder.setAccessChainLValue(arg);
3281 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003282 }
3283 ++lValueCount;
3284 } else {
3285 arg = rValues[rValueCount];
3286 ++rValueCount;
3287 }
3288 spvArgs.push_back(arg);
3289 }
3290
3291 // 3. Make the call.
3292 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003293 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003294
3295 // 4. Copy back out an "out" arguments.
3296 lValueCount = 0;
3297 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003298 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003299 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3300 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3301 spv::Id copy = builder.createLoad(spvArgs[a]);
3302 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003303 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003304 }
3305 ++lValueCount;
3306 }
3307 }
3308
3309 return result;
3310}
3311
3312// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003313spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3314 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003315 spv::Id typeId, spv::Id left, spv::Id right,
3316 glslang::TBasicType typeProxy, bool reduceComparison)
3317{
Rex Xu8ff43de2016-04-22 16:51:45 +08003318 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003319#ifdef AMD_EXTENSIONS
3320 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3321#else
John Kessenich140f3df2015-06-26 16:58:36 -06003322 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003323#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003324 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003325
3326 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003327 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003328 bool comparison = false;
3329
3330 switch (op) {
3331 case glslang::EOpAdd:
3332 case glslang::EOpAddAssign:
3333 if (isFloat)
3334 binOp = spv::OpFAdd;
3335 else
3336 binOp = spv::OpIAdd;
3337 break;
3338 case glslang::EOpSub:
3339 case glslang::EOpSubAssign:
3340 if (isFloat)
3341 binOp = spv::OpFSub;
3342 else
3343 binOp = spv::OpISub;
3344 break;
3345 case glslang::EOpMul:
3346 case glslang::EOpMulAssign:
3347 if (isFloat)
3348 binOp = spv::OpFMul;
3349 else
3350 binOp = spv::OpIMul;
3351 break;
3352 case glslang::EOpVectorTimesScalar:
3353 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003354 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003355 if (builder.isVector(right))
3356 std::swap(left, right);
3357 assert(builder.isScalar(right));
3358 needMatchingVectors = false;
3359 binOp = spv::OpVectorTimesScalar;
3360 } else
3361 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003362 break;
3363 case glslang::EOpVectorTimesMatrix:
3364 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003365 binOp = spv::OpVectorTimesMatrix;
3366 break;
3367 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003368 binOp = spv::OpMatrixTimesVector;
3369 break;
3370 case glslang::EOpMatrixTimesScalar:
3371 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003372 binOp = spv::OpMatrixTimesScalar;
3373 break;
3374 case glslang::EOpMatrixTimesMatrix:
3375 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003376 binOp = spv::OpMatrixTimesMatrix;
3377 break;
3378 case glslang::EOpOuterProduct:
3379 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003380 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003381 break;
3382
3383 case glslang::EOpDiv:
3384 case glslang::EOpDivAssign:
3385 if (isFloat)
3386 binOp = spv::OpFDiv;
3387 else if (isUnsigned)
3388 binOp = spv::OpUDiv;
3389 else
3390 binOp = spv::OpSDiv;
3391 break;
3392 case glslang::EOpMod:
3393 case glslang::EOpModAssign:
3394 if (isFloat)
3395 binOp = spv::OpFMod;
3396 else if (isUnsigned)
3397 binOp = spv::OpUMod;
3398 else
3399 binOp = spv::OpSMod;
3400 break;
3401 case glslang::EOpRightShift:
3402 case glslang::EOpRightShiftAssign:
3403 if (isUnsigned)
3404 binOp = spv::OpShiftRightLogical;
3405 else
3406 binOp = spv::OpShiftRightArithmetic;
3407 break;
3408 case glslang::EOpLeftShift:
3409 case glslang::EOpLeftShiftAssign:
3410 binOp = spv::OpShiftLeftLogical;
3411 break;
3412 case glslang::EOpAnd:
3413 case glslang::EOpAndAssign:
3414 binOp = spv::OpBitwiseAnd;
3415 break;
3416 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003417 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003418 binOp = spv::OpLogicalAnd;
3419 break;
3420 case glslang::EOpInclusiveOr:
3421 case glslang::EOpInclusiveOrAssign:
3422 binOp = spv::OpBitwiseOr;
3423 break;
3424 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003425 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003426 binOp = spv::OpLogicalOr;
3427 break;
3428 case glslang::EOpExclusiveOr:
3429 case glslang::EOpExclusiveOrAssign:
3430 binOp = spv::OpBitwiseXor;
3431 break;
3432 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003433 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003434 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003435 break;
3436
3437 case glslang::EOpLessThan:
3438 case glslang::EOpGreaterThan:
3439 case glslang::EOpLessThanEqual:
3440 case glslang::EOpGreaterThanEqual:
3441 case glslang::EOpEqual:
3442 case glslang::EOpNotEqual:
3443 case glslang::EOpVectorEqual:
3444 case glslang::EOpVectorNotEqual:
3445 comparison = true;
3446 break;
3447 default:
3448 break;
3449 }
3450
John Kessenich7c1aa102015-10-15 13:29:11 -06003451 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003452 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003453 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003454 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003455 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003456
3457 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003458 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003459 builder.promoteScalar(precision, left, right);
3460
qining25262b32016-05-06 17:25:16 -04003461 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3462 addDecoration(result, noContraction);
3463 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003464 }
3465
3466 if (! comparison)
3467 return 0;
3468
John Kessenich7c1aa102015-10-15 13:29:11 -06003469 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003470
John Kessenich4583b612016-08-07 19:14:22 -06003471 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3472 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003473 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003474
3475 switch (op) {
3476 case glslang::EOpLessThan:
3477 if (isFloat)
3478 binOp = spv::OpFOrdLessThan;
3479 else if (isUnsigned)
3480 binOp = spv::OpULessThan;
3481 else
3482 binOp = spv::OpSLessThan;
3483 break;
3484 case glslang::EOpGreaterThan:
3485 if (isFloat)
3486 binOp = spv::OpFOrdGreaterThan;
3487 else if (isUnsigned)
3488 binOp = spv::OpUGreaterThan;
3489 else
3490 binOp = spv::OpSGreaterThan;
3491 break;
3492 case glslang::EOpLessThanEqual:
3493 if (isFloat)
3494 binOp = spv::OpFOrdLessThanEqual;
3495 else if (isUnsigned)
3496 binOp = spv::OpULessThanEqual;
3497 else
3498 binOp = spv::OpSLessThanEqual;
3499 break;
3500 case glslang::EOpGreaterThanEqual:
3501 if (isFloat)
3502 binOp = spv::OpFOrdGreaterThanEqual;
3503 else if (isUnsigned)
3504 binOp = spv::OpUGreaterThanEqual;
3505 else
3506 binOp = spv::OpSGreaterThanEqual;
3507 break;
3508 case glslang::EOpEqual:
3509 case glslang::EOpVectorEqual:
3510 if (isFloat)
3511 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003512 else if (isBool)
3513 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003514 else
3515 binOp = spv::OpIEqual;
3516 break;
3517 case glslang::EOpNotEqual:
3518 case glslang::EOpVectorNotEqual:
3519 if (isFloat)
3520 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003521 else if (isBool)
3522 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003523 else
3524 binOp = spv::OpINotEqual;
3525 break;
3526 default:
3527 break;
3528 }
3529
qining25262b32016-05-06 17:25:16 -04003530 if (binOp != spv::OpNop) {
3531 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3532 addDecoration(result, noContraction);
3533 return builder.setPrecision(result, precision);
3534 }
John Kessenich140f3df2015-06-26 16:58:36 -06003535
3536 return 0;
3537}
3538
John Kessenich04bb8a02015-12-12 12:28:14 -07003539//
3540// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3541// These can be any of:
3542//
3543// matrix * scalar
3544// scalar * matrix
3545// matrix * matrix linear algebraic
3546// matrix * vector
3547// vector * matrix
3548// matrix * matrix componentwise
3549// matrix op matrix op in {+, -, /}
3550// matrix op scalar op in {+, -, /}
3551// scalar op matrix op in {+, -, /}
3552//
qining25262b32016-05-06 17:25:16 -04003553spv::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 -07003554{
3555 bool firstClass = true;
3556
3557 // First, handle first-class matrix operations (* and matrix/scalar)
3558 switch (op) {
3559 case spv::OpFDiv:
3560 if (builder.isMatrix(left) && builder.isScalar(right)) {
3561 // turn matrix / scalar into a multiply...
3562 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3563 op = spv::OpMatrixTimesScalar;
3564 } else
3565 firstClass = false;
3566 break;
3567 case spv::OpMatrixTimesScalar:
3568 if (builder.isMatrix(right))
3569 std::swap(left, right);
3570 assert(builder.isScalar(right));
3571 break;
3572 case spv::OpVectorTimesMatrix:
3573 assert(builder.isVector(left));
3574 assert(builder.isMatrix(right));
3575 break;
3576 case spv::OpMatrixTimesVector:
3577 assert(builder.isMatrix(left));
3578 assert(builder.isVector(right));
3579 break;
3580 case spv::OpMatrixTimesMatrix:
3581 assert(builder.isMatrix(left));
3582 assert(builder.isMatrix(right));
3583 break;
3584 default:
3585 firstClass = false;
3586 break;
3587 }
3588
qining25262b32016-05-06 17:25:16 -04003589 if (firstClass) {
3590 spv::Id result = builder.createBinOp(op, typeId, left, right);
3591 addDecoration(result, noContraction);
3592 return builder.setPrecision(result, precision);
3593 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003594
LoopDawg592860c2016-06-09 08:57:35 -06003595 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003596 // The result type of all of them is the same type as the (a) matrix operand.
3597 // The algorithm is to:
3598 // - break the matrix(es) into vectors
3599 // - smear any scalar to a vector
3600 // - do vector operations
3601 // - make a matrix out the vector results
3602 switch (op) {
3603 case spv::OpFAdd:
3604 case spv::OpFSub:
3605 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003606 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003607 case spv::OpFMul:
3608 {
3609 // one time set up...
3610 bool leftMat = builder.isMatrix(left);
3611 bool rightMat = builder.isMatrix(right);
3612 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3613 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3614 spv::Id scalarType = builder.getScalarTypeId(typeId);
3615 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3616 std::vector<spv::Id> results;
3617 spv::Id smearVec = spv::NoResult;
3618 if (builder.isScalar(left))
3619 smearVec = builder.smearScalar(precision, left, vecType);
3620 else if (builder.isScalar(right))
3621 smearVec = builder.smearScalar(precision, right, vecType);
3622
3623 // do each vector op
3624 for (unsigned int c = 0; c < numCols; ++c) {
3625 std::vector<unsigned int> indexes;
3626 indexes.push_back(c);
3627 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3628 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003629 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3630 addDecoration(result, noContraction);
3631 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003632 }
3633
3634 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003635 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003636 }
3637 default:
3638 assert(0);
3639 return spv::NoResult;
3640 }
3641}
3642
qining25262b32016-05-06 17:25:16 -04003643spv::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 -06003644{
3645 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003646 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003647 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003648 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003649#ifdef AMD_EXTENSIONS
3650 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3651#else
Rex Xu04db3f52015-09-16 11:44:02 +08003652 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003653#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003654
3655 switch (op) {
3656 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003657 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003658 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003659 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003660 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003661 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003662 unaryOp = spv::OpSNegate;
3663 break;
3664
3665 case glslang::EOpLogicalNot:
3666 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003667 unaryOp = spv::OpLogicalNot;
3668 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003669 case glslang::EOpBitwiseNot:
3670 unaryOp = spv::OpNot;
3671 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003672
John Kessenich140f3df2015-06-26 16:58:36 -06003673 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003674 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003675 break;
3676 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003677 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003678 break;
3679 case glslang::EOpTranspose:
3680 unaryOp = spv::OpTranspose;
3681 break;
3682
3683 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003684 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003685 break;
3686 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003687 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003688 break;
3689 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003690 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003691 break;
3692 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003693 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003694 break;
3695 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003696 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003697 break;
3698 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003699 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003700 break;
3701 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003702 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003703 break;
3704 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003705 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003706 break;
3707
3708 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003709 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003710 break;
3711 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003712 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003713 break;
3714 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003715 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003716 break;
3717 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003718 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003719 break;
3720 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003721 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003722 break;
3723 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003724 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003725 break;
3726
3727 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003728 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003729 break;
3730 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003731 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003732 break;
3733
3734 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003735 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003736 break;
3737 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003738 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003739 break;
3740 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003741 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003742 break;
3743 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003744 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003745 break;
3746 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003747 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003748 break;
3749 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003750 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003751 break;
3752
3753 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003754 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003755 break;
3756 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003757 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003758 break;
3759 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003760 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003761 break;
3762 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003763 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003764 break;
3765 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003766 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003767 break;
3768 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003769 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003770 break;
3771
3772 case glslang::EOpIsNan:
3773 unaryOp = spv::OpIsNan;
3774 break;
3775 case glslang::EOpIsInf:
3776 unaryOp = spv::OpIsInf;
3777 break;
LoopDawg592860c2016-06-09 08:57:35 -06003778 case glslang::EOpIsFinite:
3779 unaryOp = spv::OpIsFinite;
3780 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003781
Rex Xucbc426e2015-12-15 16:03:10 +08003782 case glslang::EOpFloatBitsToInt:
3783 case glslang::EOpFloatBitsToUint:
3784 case glslang::EOpIntBitsToFloat:
3785 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003786 case glslang::EOpDoubleBitsToInt64:
3787 case glslang::EOpDoubleBitsToUint64:
3788 case glslang::EOpInt64BitsToDouble:
3789 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003790 unaryOp = spv::OpBitcast;
3791 break;
3792
John Kessenich140f3df2015-06-26 16:58:36 -06003793 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003794 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003795 break;
3796 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003797 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003798 break;
3799 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003800 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003801 break;
3802 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003803 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003804 break;
3805 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003806 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003807 break;
3808 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003809 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003810 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003811 case glslang::EOpPackSnorm4x8:
3812 libCall = spv::GLSLstd450PackSnorm4x8;
3813 break;
3814 case glslang::EOpUnpackSnorm4x8:
3815 libCall = spv::GLSLstd450UnpackSnorm4x8;
3816 break;
3817 case glslang::EOpPackUnorm4x8:
3818 libCall = spv::GLSLstd450PackUnorm4x8;
3819 break;
3820 case glslang::EOpUnpackUnorm4x8:
3821 libCall = spv::GLSLstd450UnpackUnorm4x8;
3822 break;
3823 case glslang::EOpPackDouble2x32:
3824 libCall = spv::GLSLstd450PackDouble2x32;
3825 break;
3826 case glslang::EOpUnpackDouble2x32:
3827 libCall = spv::GLSLstd450UnpackDouble2x32;
3828 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003829
Rex Xu8ff43de2016-04-22 16:51:45 +08003830 case glslang::EOpPackInt2x32:
3831 case glslang::EOpUnpackInt2x32:
3832 case glslang::EOpPackUint2x32:
3833 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003834 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003835 break;
3836
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003837#ifdef AMD_EXTENSIONS
3838 case glslang::EOpPackFloat2x16:
3839 case glslang::EOpUnpackFloat2x16:
3840 unaryOp = spv::OpBitcast;
3841 break;
3842#endif
3843
John Kessenich140f3df2015-06-26 16:58:36 -06003844 case glslang::EOpDPdx:
3845 unaryOp = spv::OpDPdx;
3846 break;
3847 case glslang::EOpDPdy:
3848 unaryOp = spv::OpDPdy;
3849 break;
3850 case glslang::EOpFwidth:
3851 unaryOp = spv::OpFwidth;
3852 break;
3853 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003854 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003855 unaryOp = spv::OpDPdxFine;
3856 break;
3857 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003858 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003859 unaryOp = spv::OpDPdyFine;
3860 break;
3861 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003862 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003863 unaryOp = spv::OpFwidthFine;
3864 break;
3865 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003866 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003867 unaryOp = spv::OpDPdxCoarse;
3868 break;
3869 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003870 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003871 unaryOp = spv::OpDPdyCoarse;
3872 break;
3873 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003874 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003875 unaryOp = spv::OpFwidthCoarse;
3876 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003877 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003878 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003879 libCall = spv::GLSLstd450InterpolateAtCentroid;
3880 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003881 case glslang::EOpAny:
3882 unaryOp = spv::OpAny;
3883 break;
3884 case glslang::EOpAll:
3885 unaryOp = spv::OpAll;
3886 break;
3887
3888 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003889 if (isFloat)
3890 libCall = spv::GLSLstd450FAbs;
3891 else
3892 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003893 break;
3894 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003895 if (isFloat)
3896 libCall = spv::GLSLstd450FSign;
3897 else
3898 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003899 break;
3900
John Kessenichfc51d282015-08-19 13:34:18 -06003901 case glslang::EOpAtomicCounterIncrement:
3902 case glslang::EOpAtomicCounterDecrement:
3903 case glslang::EOpAtomicCounter:
3904 {
3905 // Handle all of the atomics in one place, in createAtomicOperation()
3906 std::vector<spv::Id> operands;
3907 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003908 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003909 }
3910
John Kessenichfc51d282015-08-19 13:34:18 -06003911 case glslang::EOpBitFieldReverse:
3912 unaryOp = spv::OpBitReverse;
3913 break;
3914 case glslang::EOpBitCount:
3915 unaryOp = spv::OpBitCount;
3916 break;
3917 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003918 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003919 break;
3920 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003921 if (isUnsigned)
3922 libCall = spv::GLSLstd450FindUMsb;
3923 else
3924 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003925 break;
3926
Rex Xu574ab042016-04-14 16:53:07 +08003927 case glslang::EOpBallot:
3928 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003929 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003930 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003931 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003932#ifdef AMD_EXTENSIONS
3933 case glslang::EOpMinInvocations:
3934 case glslang::EOpMaxInvocations:
3935 case glslang::EOpAddInvocations:
3936 case glslang::EOpMinInvocationsNonUniform:
3937 case glslang::EOpMaxInvocationsNonUniform:
3938 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08003939 case glslang::EOpMinInvocationsInclusiveScan:
3940 case glslang::EOpMaxInvocationsInclusiveScan:
3941 case glslang::EOpAddInvocationsInclusiveScan:
3942 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
3943 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
3944 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
3945 case glslang::EOpMinInvocationsExclusiveScan:
3946 case glslang::EOpMaxInvocationsExclusiveScan:
3947 case glslang::EOpAddInvocationsExclusiveScan:
3948 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
3949 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
3950 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08003951#endif
Rex Xu51596642016-09-21 18:56:12 +08003952 {
3953 std::vector<spv::Id> operands;
3954 operands.push_back(operand);
3955 return createInvocationsOperation(op, typeId, operands, typeProxy);
3956 }
Rex Xu9d93a232016-05-05 12:30:44 +08003957
3958#ifdef AMD_EXTENSIONS
3959 case glslang::EOpMbcnt:
3960 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3961 libCall = spv::MbcntAMD;
3962 break;
3963
3964 case glslang::EOpCubeFaceIndex:
3965 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3966 libCall = spv::CubeFaceIndexAMD;
3967 break;
3968
3969 case glslang::EOpCubeFaceCoord:
3970 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3971 libCall = spv::CubeFaceCoordAMD;
3972 break;
3973#endif
Rex Xu338b1852016-05-05 20:38:33 +08003974
John Kessenich140f3df2015-06-26 16:58:36 -06003975 default:
3976 return 0;
3977 }
3978
3979 spv::Id id;
3980 if (libCall >= 0) {
3981 std::vector<spv::Id> args;
3982 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08003983 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08003984 } else {
John Kessenich91cef522016-05-05 16:45:40 -06003985 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08003986 }
John Kessenich140f3df2015-06-26 16:58:36 -06003987
qining25262b32016-05-06 17:25:16 -04003988 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07003989 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003990}
3991
John Kessenich7a53f762016-01-20 11:19:27 -07003992// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04003993spv::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 -07003994{
3995 // Handle unary operations vector by vector.
3996 // The result type is the same type as the original type.
3997 // The algorithm is to:
3998 // - break the matrix into vectors
3999 // - apply the operation to each vector
4000 // - make a matrix out the vector results
4001
4002 // get the types sorted out
4003 int numCols = builder.getNumColumns(operand);
4004 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004005 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4006 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004007 std::vector<spv::Id> results;
4008
4009 // do each vector op
4010 for (int c = 0; c < numCols; ++c) {
4011 std::vector<unsigned int> indexes;
4012 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004013 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4014 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4015 addDecoration(destVec, noContraction);
4016 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004017 }
4018
4019 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004020 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004021}
4022
Rex Xu73e3ce72016-04-27 18:48:17 +08004023spv::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 -06004024{
4025 spv::Op convOp = spv::OpNop;
4026 spv::Id zero = 0;
4027 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004028 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004029
4030 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4031
4032 switch (op) {
4033 case glslang::EOpConvIntToBool:
4034 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004035 case glslang::EOpConvInt64ToBool:
4036 case glslang::EOpConvUint64ToBool:
4037 zero = (op == glslang::EOpConvInt64ToBool ||
4038 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004039 zero = makeSmearedConstant(zero, vectorSize);
4040 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4041
4042 case glslang::EOpConvFloatToBool:
4043 zero = builder.makeFloatConstant(0.0F);
4044 zero = makeSmearedConstant(zero, vectorSize);
4045 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4046
4047 case glslang::EOpConvDoubleToBool:
4048 zero = builder.makeDoubleConstant(0.0);
4049 zero = makeSmearedConstant(zero, vectorSize);
4050 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4051
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004052#ifdef AMD_EXTENSIONS
4053 case glslang::EOpConvFloat16ToBool:
4054 zero = builder.makeFloat16Constant(0.0F);
4055 zero = makeSmearedConstant(zero, vectorSize);
4056 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4057#endif
4058
John Kessenich140f3df2015-06-26 16:58:36 -06004059 case glslang::EOpConvBoolToFloat:
4060 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004061 zero = builder.makeFloatConstant(0.0F);
4062 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004063 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004064
John Kessenich140f3df2015-06-26 16:58:36 -06004065 case glslang::EOpConvBoolToDouble:
4066 convOp = spv::OpSelect;
4067 zero = builder.makeDoubleConstant(0.0);
4068 one = builder.makeDoubleConstant(1.0);
4069 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004070
4071#ifdef AMD_EXTENSIONS
4072 case glslang::EOpConvBoolToFloat16:
4073 convOp = spv::OpSelect;
4074 zero = builder.makeFloat16Constant(0.0F);
4075 one = builder.makeFloat16Constant(1.0F);
4076 break;
4077#endif
4078
John Kessenich140f3df2015-06-26 16:58:36 -06004079 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004080 case glslang::EOpConvBoolToInt64:
4081 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4082 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004083 convOp = spv::OpSelect;
4084 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004085
John Kessenich140f3df2015-06-26 16:58:36 -06004086 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004087 case glslang::EOpConvBoolToUint64:
4088 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4089 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004090 convOp = spv::OpSelect;
4091 break;
4092
4093 case glslang::EOpConvIntToFloat:
4094 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004095 case glslang::EOpConvInt64ToFloat:
4096 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004097#ifdef AMD_EXTENSIONS
4098 case glslang::EOpConvIntToFloat16:
4099 case glslang::EOpConvInt64ToFloat16:
4100#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004101 convOp = spv::OpConvertSToF;
4102 break;
4103
4104 case glslang::EOpConvUintToFloat:
4105 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004106 case glslang::EOpConvUint64ToFloat:
4107 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004108#ifdef AMD_EXTENSIONS
4109 case glslang::EOpConvUintToFloat16:
4110 case glslang::EOpConvUint64ToFloat16:
4111#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004112 convOp = spv::OpConvertUToF;
4113 break;
4114
4115 case glslang::EOpConvDoubleToFloat:
4116 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004117#ifdef AMD_EXTENSIONS
4118 case glslang::EOpConvDoubleToFloat16:
4119 case glslang::EOpConvFloat16ToDouble:
4120 case glslang::EOpConvFloatToFloat16:
4121 case glslang::EOpConvFloat16ToFloat:
4122#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004123 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004124 if (builder.isMatrixType(destType))
4125 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004126 break;
4127
4128 case glslang::EOpConvFloatToInt:
4129 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004130 case glslang::EOpConvFloatToInt64:
4131 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004132#ifdef AMD_EXTENSIONS
4133 case glslang::EOpConvFloat16ToInt:
4134 case glslang::EOpConvFloat16ToInt64:
4135#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004136 convOp = spv::OpConvertFToS;
4137 break;
4138
4139 case glslang::EOpConvUintToInt:
4140 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004141 case glslang::EOpConvUint64ToInt64:
4142 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004143 if (builder.isInSpecConstCodeGenMode()) {
4144 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004145 zero = (op == glslang::EOpConvUint64ToInt64 ||
4146 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004147 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004148 // Use OpIAdd, instead of OpBitcast to do the conversion when
4149 // generating for OpSpecConstantOp instruction.
4150 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4151 }
4152 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004153 convOp = spv::OpBitcast;
4154 break;
4155
4156 case glslang::EOpConvFloatToUint:
4157 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004158 case glslang::EOpConvFloatToUint64:
4159 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004160#ifdef AMD_EXTENSIONS
4161 case glslang::EOpConvFloat16ToUint:
4162 case glslang::EOpConvFloat16ToUint64:
4163#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004164 convOp = spv::OpConvertFToU;
4165 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004166
4167 case glslang::EOpConvIntToInt64:
4168 case glslang::EOpConvInt64ToInt:
4169 convOp = spv::OpSConvert;
4170 break;
4171
4172 case glslang::EOpConvUintToUint64:
4173 case glslang::EOpConvUint64ToUint:
4174 convOp = spv::OpUConvert;
4175 break;
4176
4177 case glslang::EOpConvIntToUint64:
4178 case glslang::EOpConvInt64ToUint:
4179 case glslang::EOpConvUint64ToInt:
4180 case glslang::EOpConvUintToInt64:
4181 // OpSConvert/OpUConvert + OpBitCast
4182 switch (op) {
4183 case glslang::EOpConvIntToUint64:
4184 convOp = spv::OpSConvert;
4185 type = builder.makeIntType(64);
4186 break;
4187 case glslang::EOpConvInt64ToUint:
4188 convOp = spv::OpSConvert;
4189 type = builder.makeIntType(32);
4190 break;
4191 case glslang::EOpConvUint64ToInt:
4192 convOp = spv::OpUConvert;
4193 type = builder.makeUintType(32);
4194 break;
4195 case glslang::EOpConvUintToInt64:
4196 convOp = spv::OpUConvert;
4197 type = builder.makeUintType(64);
4198 break;
4199 default:
4200 assert(0);
4201 break;
4202 }
4203
4204 if (vectorSize > 0)
4205 type = builder.makeVectorType(type, vectorSize);
4206
4207 operand = builder.createUnaryOp(convOp, type, operand);
4208
4209 if (builder.isInSpecConstCodeGenMode()) {
4210 // Build zero scalar or vector for OpIAdd.
4211 zero = (op == glslang::EOpConvIntToUint64 ||
4212 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4213 zero = makeSmearedConstant(zero, vectorSize);
4214 // Use OpIAdd, instead of OpBitcast to do the conversion when
4215 // generating for OpSpecConstantOp instruction.
4216 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4217 }
4218 // For normal run-time conversion instruction, use OpBitcast.
4219 convOp = spv::OpBitcast;
4220 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004221 default:
4222 break;
4223 }
4224
4225 spv::Id result = 0;
4226 if (convOp == spv::OpNop)
4227 return result;
4228
4229 if (convOp == spv::OpSelect) {
4230 zero = makeSmearedConstant(zero, vectorSize);
4231 one = makeSmearedConstant(one, vectorSize);
4232 result = builder.createTriOp(convOp, destType, operand, one, zero);
4233 } else
4234 result = builder.createUnaryOp(convOp, destType, operand);
4235
John Kessenich32cfd492016-02-02 12:37:46 -07004236 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004237}
4238
4239spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4240{
4241 if (vectorSize == 0)
4242 return constant;
4243
4244 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4245 std::vector<spv::Id> components;
4246 for (int c = 0; c < vectorSize; ++c)
4247 components.push_back(constant);
4248 return builder.makeCompositeConstant(vectorTypeId, components);
4249}
4250
John Kessenich426394d2015-07-23 10:22:48 -06004251// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004252spv::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 -06004253{
4254 spv::Op opCode = spv::OpNop;
4255
4256 switch (op) {
4257 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004258 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004259 opCode = spv::OpAtomicIAdd;
4260 break;
4261 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004262 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004263 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004264 break;
4265 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004266 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004267 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004268 break;
4269 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004270 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004271 opCode = spv::OpAtomicAnd;
4272 break;
4273 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004274 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004275 opCode = spv::OpAtomicOr;
4276 break;
4277 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004278 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004279 opCode = spv::OpAtomicXor;
4280 break;
4281 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004282 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004283 opCode = spv::OpAtomicExchange;
4284 break;
4285 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004286 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004287 opCode = spv::OpAtomicCompareExchange;
4288 break;
4289 case glslang::EOpAtomicCounterIncrement:
4290 opCode = spv::OpAtomicIIncrement;
4291 break;
4292 case glslang::EOpAtomicCounterDecrement:
4293 opCode = spv::OpAtomicIDecrement;
4294 break;
4295 case glslang::EOpAtomicCounter:
4296 opCode = spv::OpAtomicLoad;
4297 break;
4298 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004299 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004300 break;
4301 }
4302
4303 // Sort out the operands
4304 // - mapping from glslang -> SPV
4305 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004306 // - compare-exchange swaps the value and comparator
4307 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004308 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4309 auto opIt = operands.begin(); // walk the glslang operands
4310 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004311 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4312 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4313 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004314 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4315 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004316 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004317 spvAtomicOperands.push_back(*(opIt + 1));
4318 spvAtomicOperands.push_back(*opIt);
4319 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004320 }
John Kessenich426394d2015-07-23 10:22:48 -06004321
John Kessenich3e60a6f2015-09-14 22:45:16 -06004322 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004323 for (; opIt != operands.end(); ++opIt)
4324 spvAtomicOperands.push_back(*opIt);
4325
4326 return builder.createOp(opCode, typeId, spvAtomicOperands);
4327}
4328
John Kessenich91cef522016-05-05 16:45:40 -06004329// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004330spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004331{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004332#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004333 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004334 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004335#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004336
Rex Xu51596642016-09-21 18:56:12 +08004337 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004338 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004339 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4340
chaocf200da82016-12-20 12:44:35 -08004341 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4342 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004343 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4344 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004345 } else if (op == glslang::EOpAnyInvocation ||
4346 op == glslang::EOpAllInvocations ||
4347 op == glslang::EOpAllInvocationsEqual) {
4348 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4349 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004350 } else {
4351 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004352#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004353 if (op == glslang::EOpMinInvocationsNonUniform ||
4354 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004355 op == glslang::EOpAddInvocationsNonUniform ||
4356 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4357 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4358 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4359 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4360 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4361 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004362 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004363#endif
Rex Xu51596642016-09-21 18:56:12 +08004364
4365 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004366#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004367 switch (op) {
4368 case glslang::EOpMinInvocations:
4369 case glslang::EOpMaxInvocations:
4370 case glslang::EOpAddInvocations:
4371 case glslang::EOpMinInvocationsNonUniform:
4372 case glslang::EOpMaxInvocationsNonUniform:
4373 case glslang::EOpAddInvocationsNonUniform:
4374 groupOperation = spv::GroupOperationReduce;
4375 spvGroupOperands.push_back(groupOperation);
4376 break;
4377 case glslang::EOpMinInvocationsInclusiveScan:
4378 case glslang::EOpMaxInvocationsInclusiveScan:
4379 case glslang::EOpAddInvocationsInclusiveScan:
4380 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4381 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4382 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4383 groupOperation = spv::GroupOperationInclusiveScan;
4384 spvGroupOperands.push_back(groupOperation);
4385 break;
4386 case glslang::EOpMinInvocationsExclusiveScan:
4387 case glslang::EOpMaxInvocationsExclusiveScan:
4388 case glslang::EOpAddInvocationsExclusiveScan:
4389 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4390 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4391 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4392 groupOperation = spv::GroupOperationExclusiveScan;
4393 spvGroupOperands.push_back(groupOperation);
4394 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004395 default:
4396 break;
Rex Xu430ef402016-10-14 17:22:23 +08004397 }
Rex Xu9d93a232016-05-05 12:30:44 +08004398#endif
Rex Xu51596642016-09-21 18:56:12 +08004399 }
4400
4401 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4402 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004403
4404 switch (op) {
4405 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004406 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004407 break;
John Kessenich91cef522016-05-05 16:45:40 -06004408 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004409 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004410 break;
John Kessenich91cef522016-05-05 16:45:40 -06004411 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004412 opCode = spv::OpSubgroupAllEqualKHR;
4413 break;
Rex Xu51596642016-09-21 18:56:12 +08004414 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004415 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004416 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004417 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004418 break;
4419 case glslang::EOpReadFirstInvocation:
4420 opCode = spv::OpSubgroupFirstInvocationKHR;
4421 break;
4422 case glslang::EOpBallot:
4423 {
4424 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4425 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4426 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4427 //
4428 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4429 //
4430 spv::Id uintType = builder.makeUintType(32);
4431 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4432 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4433
4434 std::vector<spv::Id> components;
4435 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4436 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4437
4438 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4439 return builder.createUnaryOp(spv::OpBitcast, typeId,
4440 builder.createCompositeConstruct(uvec2Type, components));
4441 }
4442
Rex Xu9d93a232016-05-05 12:30:44 +08004443#ifdef AMD_EXTENSIONS
4444 case glslang::EOpMinInvocations:
4445 case glslang::EOpMaxInvocations:
4446 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004447 case glslang::EOpMinInvocationsInclusiveScan:
4448 case glslang::EOpMaxInvocationsInclusiveScan:
4449 case glslang::EOpAddInvocationsInclusiveScan:
4450 case glslang::EOpMinInvocationsExclusiveScan:
4451 case glslang::EOpMaxInvocationsExclusiveScan:
4452 case glslang::EOpAddInvocationsExclusiveScan:
4453 if (op == glslang::EOpMinInvocations ||
4454 op == glslang::EOpMinInvocationsInclusiveScan ||
4455 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004456 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004457 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004458 else {
4459 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004460 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004461 else
Rex Xu51596642016-09-21 18:56:12 +08004462 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004463 }
Rex Xu430ef402016-10-14 17:22:23 +08004464 } else if (op == glslang::EOpMaxInvocations ||
4465 op == glslang::EOpMaxInvocationsInclusiveScan ||
4466 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004467 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004468 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004469 else {
4470 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004471 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004472 else
Rex Xu51596642016-09-21 18:56:12 +08004473 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004474 }
4475 } else {
4476 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004477 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004478 else
Rex Xu51596642016-09-21 18:56:12 +08004479 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004480 }
4481
Rex Xu2bbbe062016-08-23 15:41:05 +08004482 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004483 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004484
4485 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004486 case glslang::EOpMinInvocationsNonUniform:
4487 case glslang::EOpMaxInvocationsNonUniform:
4488 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004489 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4490 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4491 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4492 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4493 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4494 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4495 if (op == glslang::EOpMinInvocationsNonUniform ||
4496 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4497 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004498 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004499 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004500 else {
4501 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004502 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004503 else
Rex Xu51596642016-09-21 18:56:12 +08004504 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004505 }
4506 }
Rex Xu430ef402016-10-14 17:22:23 +08004507 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4508 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4509 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004510 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004511 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004512 else {
4513 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004514 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004515 else
Rex Xu51596642016-09-21 18:56:12 +08004516 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004517 }
4518 }
4519 else {
4520 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004521 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004522 else
Rex Xu51596642016-09-21 18:56:12 +08004523 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004524 }
4525
Rex Xu2bbbe062016-08-23 15:41:05 +08004526 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004527 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004528
4529 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004530#endif
John Kessenich91cef522016-05-05 16:45:40 -06004531 default:
4532 logger->missingFunctionality("invocation operation");
4533 return spv::NoResult;
4534 }
Rex Xu51596642016-09-21 18:56:12 +08004535
4536 assert(opCode != spv::OpNop);
4537 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004538}
4539
Rex Xu2bbbe062016-08-23 15:41:05 +08004540// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004541spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004542{
Rex Xub7072052016-09-26 15:53:40 +08004543#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004544 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4545 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004546 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004547 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004548 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4549 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4550 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004551#else
4552 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4553 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004554 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4555 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004556#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004557
4558 // Handle group invocation operations scalar by scalar.
4559 // The result type is the same type as the original type.
4560 // The algorithm is to:
4561 // - break the vector into scalars
4562 // - apply the operation to each scalar
4563 // - make a vector out the scalar results
4564
4565 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004566 int numComponents = builder.getNumComponents(operands[0]);
4567 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004568 std::vector<spv::Id> results;
4569
4570 // do each scalar op
4571 for (int comp = 0; comp < numComponents; ++comp) {
4572 std::vector<unsigned int> indexes;
4573 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004574 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004575 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004576 if (op == spv::OpSubgroupReadInvocationKHR) {
4577 spvGroupOperands.push_back(scalar);
4578 spvGroupOperands.push_back(operands[1]);
4579 } else if (op == spv::OpGroupBroadcast) {
4580 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004581 spvGroupOperands.push_back(scalar);
4582 spvGroupOperands.push_back(operands[1]);
4583 } else {
chaocf200da82016-12-20 12:44:35 -08004584 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004585 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004586 spvGroupOperands.push_back(scalar);
4587 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004588
Rex Xub7072052016-09-26 15:53:40 +08004589 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004590 }
4591
4592 // put the pieces together
4593 return builder.createCompositeConstruct(typeId, results);
4594}
Rex Xu2bbbe062016-08-23 15:41:05 +08004595
John Kessenich5e4b1242015-08-06 22:53:06 -06004596spv::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 -06004597{
Rex Xu8ff43de2016-04-22 16:51:45 +08004598 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004599#ifdef AMD_EXTENSIONS
4600 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4601#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004602 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004603#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004604
John Kessenich140f3df2015-06-26 16:58:36 -06004605 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004606 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004607 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004608 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004609 spv::Id typeId0 = 0;
4610 if (consumedOperands > 0)
4611 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08004612 spv::Id typeId1 = 0;
4613 if (consumedOperands > 1)
4614 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07004615 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004616
4617 switch (op) {
4618 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004619 if (isFloat)
4620 libCall = spv::GLSLstd450FMin;
4621 else if (isUnsigned)
4622 libCall = spv::GLSLstd450UMin;
4623 else
4624 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004625 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004626 break;
4627 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004628 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004629 break;
4630 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004631 if (isFloat)
4632 libCall = spv::GLSLstd450FMax;
4633 else if (isUnsigned)
4634 libCall = spv::GLSLstd450UMax;
4635 else
4636 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004637 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004638 break;
4639 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004640 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004641 break;
4642 case glslang::EOpDot:
4643 opCode = spv::OpDot;
4644 break;
4645 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004646 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004647 break;
4648
4649 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004650 if (isFloat)
4651 libCall = spv::GLSLstd450FClamp;
4652 else if (isUnsigned)
4653 libCall = spv::GLSLstd450UClamp;
4654 else
4655 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004656 builder.promoteScalar(precision, operands.front(), operands[1]);
4657 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004658 break;
4659 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004660 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4661 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004662 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004663 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004664 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004665 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004666 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004667 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004668 break;
4669 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004670 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004671 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004672 break;
4673 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004674 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004675 builder.promoteScalar(precision, operands[0], operands[2]);
4676 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004677 break;
4678
4679 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004680 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004681 break;
4682 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004683 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004684 break;
4685 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004686 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004687 break;
4688 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004689 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004690 break;
4691 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004692 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004693 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004694 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004695 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004696 libCall = spv::GLSLstd450InterpolateAtSample;
4697 break;
4698 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004699 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004700 libCall = spv::GLSLstd450InterpolateAtOffset;
4701 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004702 case glslang::EOpAddCarry:
4703 opCode = spv::OpIAddCarry;
4704 typeId = builder.makeStructResultType(typeId0, typeId0);
4705 consumedOperands = 2;
4706 break;
4707 case glslang::EOpSubBorrow:
4708 opCode = spv::OpISubBorrow;
4709 typeId = builder.makeStructResultType(typeId0, typeId0);
4710 consumedOperands = 2;
4711 break;
4712 case glslang::EOpUMulExtended:
4713 opCode = spv::OpUMulExtended;
4714 typeId = builder.makeStructResultType(typeId0, typeId0);
4715 consumedOperands = 2;
4716 break;
4717 case glslang::EOpIMulExtended:
4718 opCode = spv::OpSMulExtended;
4719 typeId = builder.makeStructResultType(typeId0, typeId0);
4720 consumedOperands = 2;
4721 break;
4722 case glslang::EOpBitfieldExtract:
4723 if (isUnsigned)
4724 opCode = spv::OpBitFieldUExtract;
4725 else
4726 opCode = spv::OpBitFieldSExtract;
4727 break;
4728 case glslang::EOpBitfieldInsert:
4729 opCode = spv::OpBitFieldInsert;
4730 break;
4731
4732 case glslang::EOpFma:
4733 libCall = spv::GLSLstd450Fma;
4734 break;
4735 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004736 {
4737 libCall = spv::GLSLstd450FrexpStruct;
4738 assert(builder.isPointerType(typeId1));
4739 typeId1 = builder.getContainedTypeId(typeId1);
4740#ifdef AMD_EXTENSIONS
4741 int width = builder.getScalarTypeWidth(typeId1);
4742#else
4743 int width = 32;
4744#endif
4745 if (builder.getNumComponents(operands[0]) == 1)
4746 frexpIntType = builder.makeIntegerType(width, true);
4747 else
4748 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
4749 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4750 consumedOperands = 1;
4751 }
John Kessenich55e7d112015-11-15 21:33:39 -07004752 break;
4753 case glslang::EOpLdexp:
4754 libCall = spv::GLSLstd450Ldexp;
4755 break;
4756
Rex Xu574ab042016-04-14 16:53:07 +08004757 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004758 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004759
Rex Xu9d93a232016-05-05 12:30:44 +08004760#ifdef AMD_EXTENSIONS
4761 case glslang::EOpSwizzleInvocations:
4762 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4763 libCall = spv::SwizzleInvocationsAMD;
4764 break;
4765 case glslang::EOpSwizzleInvocationsMasked:
4766 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4767 libCall = spv::SwizzleInvocationsMaskedAMD;
4768 break;
4769 case glslang::EOpWriteInvocation:
4770 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4771 libCall = spv::WriteInvocationAMD;
4772 break;
4773
4774 case glslang::EOpMin3:
4775 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4776 if (isFloat)
4777 libCall = spv::FMin3AMD;
4778 else {
4779 if (isUnsigned)
4780 libCall = spv::UMin3AMD;
4781 else
4782 libCall = spv::SMin3AMD;
4783 }
4784 break;
4785 case glslang::EOpMax3:
4786 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4787 if (isFloat)
4788 libCall = spv::FMax3AMD;
4789 else {
4790 if (isUnsigned)
4791 libCall = spv::UMax3AMD;
4792 else
4793 libCall = spv::SMax3AMD;
4794 }
4795 break;
4796 case glslang::EOpMid3:
4797 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4798 if (isFloat)
4799 libCall = spv::FMid3AMD;
4800 else {
4801 if (isUnsigned)
4802 libCall = spv::UMid3AMD;
4803 else
4804 libCall = spv::SMid3AMD;
4805 }
4806 break;
4807
4808 case glslang::EOpInterpolateAtVertex:
4809 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4810 libCall = spv::InterpolateAtVertexAMD;
4811 break;
4812#endif
4813
John Kessenich140f3df2015-06-26 16:58:36 -06004814 default:
4815 return 0;
4816 }
4817
4818 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004819 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004820 // Use an extended instruction from the standard library.
4821 // Construct the call arguments, without modifying the original operands vector.
4822 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4823 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004824 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004825 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004826 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004827 case 0:
4828 // should all be handled by visitAggregate and createNoArgOperation
4829 assert(0);
4830 return 0;
4831 case 1:
4832 // should all be handled by createUnaryOperation
4833 assert(0);
4834 return 0;
4835 case 2:
4836 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4837 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004838 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004839 // anything 3 or over doesn't have l-value operands, so all should be consumed
4840 assert(consumedOperands == operands.size());
4841 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004842 break;
4843 }
4844 }
4845
John Kessenich55e7d112015-11-15 21:33:39 -07004846 // Decode the return types that were structures
4847 switch (op) {
4848 case glslang::EOpAddCarry:
4849 case glslang::EOpSubBorrow:
4850 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4851 id = builder.createCompositeExtract(id, typeId0, 0);
4852 break;
4853 case glslang::EOpUMulExtended:
4854 case glslang::EOpIMulExtended:
4855 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4856 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4857 break;
4858 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004859 {
4860 assert(operands.size() == 2);
4861 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
4862 // "exp" is floating-point type (from HLSL intrinsic)
4863 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
4864 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
4865 builder.createStore(member1, operands[1]);
4866 } else
4867 // "exp" is integer type (from GLSL built-in function)
4868 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4869 id = builder.createCompositeExtract(id, typeId0, 0);
4870 }
John Kessenich55e7d112015-11-15 21:33:39 -07004871 break;
4872 default:
4873 break;
4874 }
4875
John Kessenich32cfd492016-02-02 12:37:46 -07004876 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004877}
4878
Rex Xu9d93a232016-05-05 12:30:44 +08004879// Intrinsics with no arguments (or no return value, and no precision).
4880spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004881{
4882 // TODO: get the barrier operands correct
4883
4884 switch (op) {
4885 case glslang::EOpEmitVertex:
4886 builder.createNoResultOp(spv::OpEmitVertex);
4887 return 0;
4888 case glslang::EOpEndPrimitive:
4889 builder.createNoResultOp(spv::OpEndPrimitive);
4890 return 0;
4891 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004892 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004893 return 0;
4894 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004895 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004896 return 0;
4897 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004898 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004899 return 0;
4900 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004901 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004902 return 0;
4903 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004904 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004905 return 0;
4906 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004907 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004908 return 0;
4909 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004910 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004911 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004912 case glslang::EOpAllMemoryBarrierWithGroupSync:
4913 // Control barrier with non-"None" semantic is also a memory barrier.
4914 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4915 return 0;
4916 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4917 // Control barrier with non-"None" semantic is also a memory barrier.
4918 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4919 return 0;
4920 case glslang::EOpWorkgroupMemoryBarrier:
4921 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4922 return 0;
4923 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4924 // Control barrier with non-"None" semantic is also a memory barrier.
4925 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4926 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004927#ifdef AMD_EXTENSIONS
4928 case glslang::EOpTime:
4929 {
4930 std::vector<spv::Id> args; // Dummy arguments
4931 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4932 return builder.setPrecision(id, precision);
4933 }
4934#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004935 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004936 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004937 return 0;
4938 }
4939}
4940
4941spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4942{
John Kessenich2f273362015-07-18 22:34:27 -06004943 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004944 spv::Id id;
4945 if (symbolValues.end() != iter) {
4946 id = iter->second;
4947 return id;
4948 }
4949
4950 // it was not found, create it
4951 id = createSpvVariable(symbol);
4952 symbolValues[symbol->getId()] = id;
4953
Rex Xuc884b4a2016-06-29 15:03:44 +08004954 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004955 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004956 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004957 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004958 if (symbol->getType().getQualifier().hasSpecConstantId())
4959 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004960 if (symbol->getQualifier().hasIndex())
4961 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4962 if (symbol->getQualifier().hasComponent())
4963 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4964 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004965 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004966 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004967 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004968 if (symbol->getQualifier().hasXfbBuffer())
4969 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4970 if (symbol->getQualifier().hasXfbOffset())
4971 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4972 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004973 // atomic counters use this:
4974 if (symbol->getQualifier().hasOffset())
4975 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004976 }
4977
scygan2c864272016-05-18 18:09:17 +02004978 if (symbol->getQualifier().hasLocation())
4979 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004980 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004981 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004982 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06004983 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07004984 }
John Kessenich140f3df2015-06-26 16:58:36 -06004985 if (symbol->getQualifier().hasSet())
4986 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07004987 else if (IsDescriptorResource(symbol->getType())) {
4988 // default to 0
4989 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
4990 }
John Kessenich140f3df2015-06-26 16:58:36 -06004991 if (symbol->getQualifier().hasBinding())
4992 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07004993 if (symbol->getQualifier().hasAttachment())
4994 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06004995 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004996 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004997 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004998 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004999 if (symbol->getQualifier().hasXfbBuffer())
5000 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5001 }
5002
Rex Xu1da878f2016-02-21 20:59:01 +08005003 if (symbol->getType().isImage()) {
5004 std::vector<spv::Decoration> memory;
5005 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5006 for (unsigned int i = 0; i < memory.size(); ++i)
5007 addDecoration(id, memory[i]);
5008 }
5009
John Kessenich140f3df2015-06-26 16:58:36 -06005010 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005011 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005012 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005013 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005014
John Kessenichecba76f2017-01-06 00:34:48 -07005015#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005016 if (builtIn == spv::BuiltInSampleMask) {
5017 spv::Decoration decoration;
5018 // GL_NV_sample_mask_override_coverage extension
5019 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005020 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005021 else
5022 decoration = (spv::Decoration)spv::DecorationMax;
5023 addDecoration(id, decoration);
5024 if (decoration != spv::DecorationMax) {
5025 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5026 }
5027 }
chaoc771d89f2017-01-13 01:10:53 -08005028 else if (builtIn == spv::BuiltInLayer) {
5029 // SPV_NV_viewport_array2 extension
5030 if (symbol->getQualifier().layoutViewportRelative)
5031 {
5032 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5033 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5034 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5035 }
5036 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5037 {
5038 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5039 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5040 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5041 }
5042 }
5043
chaoc6e5acae2016-12-20 13:28:52 -08005044 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005045 addDecoration(id, spv::DecorationPassthroughNV);
5046 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005047 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5048 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005049#endif
5050
John Kessenich140f3df2015-06-26 16:58:36 -06005051 return id;
5052}
5053
John Kessenich55e7d112015-11-15 21:33:39 -07005054// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005055void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5056{
John Kessenich4016e382016-07-15 11:53:56 -06005057 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005058 builder.addDecoration(id, dec);
5059}
5060
John Kessenich55e7d112015-11-15 21:33:39 -07005061// If 'dec' is valid, add a one-operand decoration to an object
5062void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5063{
John Kessenich4016e382016-07-15 11:53:56 -06005064 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005065 builder.addDecoration(id, dec, value);
5066}
5067
5068// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005069void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5070{
John Kessenich4016e382016-07-15 11:53:56 -06005071 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005072 builder.addMemberDecoration(id, (unsigned)member, dec);
5073}
5074
John Kessenich92187592016-02-01 13:45:25 -07005075// If 'dec' is valid, add a one-operand decoration to a struct member
5076void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5077{
John Kessenich4016e382016-07-15 11:53:56 -06005078 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005079 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5080}
5081
John Kessenich55e7d112015-11-15 21:33:39 -07005082// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005083// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005084//
5085// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5086//
5087// Recursively walk the nodes. The nodes form a tree whose leaves are
5088// regular constants, which themselves are trees that createSpvConstant()
5089// recursively walks. So, this function walks the "top" of the tree:
5090// - emit specialization constant-building instructions for specConstant
5091// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005092spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005093{
John Kessenich7cc0e282016-03-20 00:46:02 -06005094 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005095
qining4f4bb812016-04-03 23:55:17 -04005096 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005097 if (! node.getQualifier().specConstant) {
5098 // hand off to the non-spec-constant path
5099 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5100 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005101 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005102 nextConst, false);
5103 }
5104
5105 // We now know we have a specialization constant to build
5106
John Kessenichd94c0032016-05-30 19:29:40 -06005107 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005108 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5109 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5110 std::vector<spv::Id> dimConstId;
5111 for (int dim = 0; dim < 3; ++dim) {
5112 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5113 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5114 if (specConst)
5115 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5116 }
5117 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5118 }
5119
5120 // An AST node labelled as specialization constant should be a symbol node.
5121 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5122 if (auto* sn = node.getAsSymbolNode()) {
5123 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005124 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5125 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5126 // will set the builder into spec constant op instruction generating mode.
5127 sub_tree->traverse(this);
5128 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005129 } else if (auto* const_union_array = &sn->getConstArray()){
5130 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005131 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5132 builder.addName(id, sn->getName().c_str());
5133 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005134 }
5135 }
qining4f4bb812016-04-03 23:55:17 -04005136
5137 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5138 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005139 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005140 exit(1);
5141 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005142}
5143
John Kessenich140f3df2015-06-26 16:58:36 -06005144// Use 'consts' as the flattened glslang source of scalar constants to recursively
5145// build the aggregate SPIR-V constant.
5146//
5147// If there are not enough elements present in 'consts', 0 will be substituted;
5148// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5149//
qining08408382016-03-21 09:51:37 -04005150spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005151{
5152 // vector of constants for SPIR-V
5153 std::vector<spv::Id> spvConsts;
5154
5155 // Type is used for struct and array constants
5156 spv::Id typeId = convertGlslangToSpvType(glslangType);
5157
5158 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005159 glslang::TType elementType(glslangType, 0);
5160 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005161 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005162 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005163 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005164 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005165 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005166 } else if (glslangType.getStruct()) {
5167 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5168 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005169 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005170 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005171 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5172 bool zero = nextConst >= consts.size();
5173 switch (glslangType.getBasicType()) {
5174 case glslang::EbtInt:
5175 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5176 break;
5177 case glslang::EbtUint:
5178 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5179 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005180 case glslang::EbtInt64:
5181 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5182 break;
5183 case glslang::EbtUint64:
5184 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5185 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005186 case glslang::EbtFloat:
5187 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5188 break;
5189 case glslang::EbtDouble:
5190 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5191 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005192#ifdef AMD_EXTENSIONS
5193 case glslang::EbtFloat16:
5194 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5195 break;
5196#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005197 case glslang::EbtBool:
5198 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5199 break;
5200 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005201 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005202 break;
5203 }
5204 ++nextConst;
5205 }
5206 } else {
5207 // we have a non-aggregate (scalar) constant
5208 bool zero = nextConst >= consts.size();
5209 spv::Id scalar = 0;
5210 switch (glslangType.getBasicType()) {
5211 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005212 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005213 break;
5214 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005215 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005216 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005217 case glslang::EbtInt64:
5218 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5219 break;
5220 case glslang::EbtUint64:
5221 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5222 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005223 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005224 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005225 break;
5226 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005227 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005228 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005229#ifdef AMD_EXTENSIONS
5230 case glslang::EbtFloat16:
5231 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5232 break;
5233#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005234 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005235 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005236 break;
5237 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005238 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005239 break;
5240 }
5241 ++nextConst;
5242 return scalar;
5243 }
5244
5245 return builder.makeCompositeConstant(typeId, spvConsts);
5246}
5247
John Kessenich7c1aa102015-10-15 13:29:11 -06005248// Return true if the node is a constant or symbol whose reading has no
5249// non-trivial observable cost or effect.
5250bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5251{
5252 // don't know what this is
5253 if (node == nullptr)
5254 return false;
5255
5256 // a constant is safe
5257 if (node->getAsConstantUnion() != nullptr)
5258 return true;
5259
5260 // not a symbol means non-trivial
5261 if (node->getAsSymbolNode() == nullptr)
5262 return false;
5263
5264 // a symbol, depends on what's being read
5265 switch (node->getType().getQualifier().storage) {
5266 case glslang::EvqTemporary:
5267 case glslang::EvqGlobal:
5268 case glslang::EvqIn:
5269 case glslang::EvqInOut:
5270 case glslang::EvqConst:
5271 case glslang::EvqConstReadOnly:
5272 case glslang::EvqUniform:
5273 return true;
5274 default:
5275 return false;
5276 }
qining25262b32016-05-06 17:25:16 -04005277}
John Kessenich7c1aa102015-10-15 13:29:11 -06005278
5279// A node is trivial if it is a single operation with no side effects.
5280// Error on the side of saying non-trivial.
5281// Return true if trivial.
5282bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5283{
5284 if (node == nullptr)
5285 return false;
5286
5287 // symbols and constants are trivial
5288 if (isTrivialLeaf(node))
5289 return true;
5290
5291 // otherwise, it needs to be a simple operation or one or two leaf nodes
5292
5293 // not a simple operation
5294 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5295 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5296 if (binaryNode == nullptr && unaryNode == nullptr)
5297 return false;
5298
5299 // not on leaf nodes
5300 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5301 return false;
5302
5303 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5304 return false;
5305 }
5306
5307 switch (node->getAsOperator()->getOp()) {
5308 case glslang::EOpLogicalNot:
5309 case glslang::EOpConvIntToBool:
5310 case glslang::EOpConvUintToBool:
5311 case glslang::EOpConvFloatToBool:
5312 case glslang::EOpConvDoubleToBool:
5313 case glslang::EOpEqual:
5314 case glslang::EOpNotEqual:
5315 case glslang::EOpLessThan:
5316 case glslang::EOpGreaterThan:
5317 case glslang::EOpLessThanEqual:
5318 case glslang::EOpGreaterThanEqual:
5319 case glslang::EOpIndexDirect:
5320 case glslang::EOpIndexDirectStruct:
5321 case glslang::EOpLogicalXor:
5322 case glslang::EOpAny:
5323 case glslang::EOpAll:
5324 return true;
5325 default:
5326 return false;
5327 }
5328}
5329
5330// Emit short-circuiting code, where 'right' is never evaluated unless
5331// the left side is true (for &&) or false (for ||).
5332spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5333{
5334 spv::Id boolTypeId = builder.makeBoolType();
5335
5336 // emit left operand
5337 builder.clearAccessChain();
5338 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005339 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005340
5341 // Operands to accumulate OpPhi operands
5342 std::vector<spv::Id> phiOperands;
5343 // accumulate left operand's phi information
5344 phiOperands.push_back(leftId);
5345 phiOperands.push_back(builder.getBuildPoint()->getId());
5346
5347 // Make the two kinds of operation symmetric with a "!"
5348 // || => emit "if (! left) result = right"
5349 // && => emit "if ( left) result = right"
5350 //
5351 // TODO: this runtime "not" for || could be avoided by adding functionality
5352 // to 'builder' to have an "else" without an "then"
5353 if (op == glslang::EOpLogicalOr)
5354 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5355
5356 // make an "if" based on the left value
5357 spv::Builder::If ifBuilder(leftId, builder);
5358
5359 // emit right operand as the "then" part of the "if"
5360 builder.clearAccessChain();
5361 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005362 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005363
5364 // accumulate left operand's phi information
5365 phiOperands.push_back(rightId);
5366 phiOperands.push_back(builder.getBuildPoint()->getId());
5367
5368 // finish the "if"
5369 ifBuilder.makeEndIf();
5370
5371 // phi together the two results
5372 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5373}
5374
Rex Xu9d93a232016-05-05 12:30:44 +08005375// Return type Id of the imported set of extended instructions corresponds to the name.
5376// Import this set if it has not been imported yet.
5377spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5378{
5379 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5380 return extBuiltinMap[name];
5381 else {
Rex Xu51596642016-09-21 18:56:12 +08005382 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005383 spv::Id extBuiltins = builder.import(name);
5384 extBuiltinMap[name] = extBuiltins;
5385 return extBuiltins;
5386 }
5387}
5388
John Kessenich140f3df2015-06-26 16:58:36 -06005389}; // end anonymous namespace
5390
5391namespace glslang {
5392
John Kessenich68d78fd2015-07-12 19:28:10 -06005393void GetSpirvVersion(std::string& version)
5394{
John Kessenich9e55f632015-07-15 10:03:39 -06005395 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005396 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005397 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005398 version = buf;
5399}
5400
John Kessenich140f3df2015-06-26 16:58:36 -06005401// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005402void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005403{
5404 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005405 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005406 if (out.fail())
5407 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005408 for (int i = 0; i < (int)spirv.size(); ++i) {
5409 unsigned int word = spirv[i];
5410 out.write((const char*)&word, 4);
5411 }
5412 out.close();
5413}
5414
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005415// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005416void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005417{
5418 std::ofstream out;
5419 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005420 if (out.fail())
5421 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005422 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005423 if (varName != nullptr) {
5424 out << "\t #pragma once" << std::endl;
5425 out << "const uint32_t " << varName << "[] = {" << std::endl;
5426 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005427 const int WORDS_PER_LINE = 8;
5428 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5429 out << "\t";
5430 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5431 const unsigned int word = spirv[i + j];
5432 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5433 if (i + j + 1 < (int)spirv.size()) {
5434 out << ",";
5435 }
5436 }
5437 out << std::endl;
5438 }
Flavio15017db2017-02-15 14:29:33 -08005439 if (varName != nullptr) {
5440 out << "};";
5441 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005442 out.close();
5443}
5444
John Kessenich140f3df2015-06-26 16:58:36 -06005445//
5446// Set up the glslang traversal
5447//
5448void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5449{
Lei Zhang17535f72016-05-04 15:55:59 -04005450 spv::SpvBuildLogger logger;
5451 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005452}
5453
Lei Zhang17535f72016-05-04 15:55:59 -04005454void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005455{
John Kessenich140f3df2015-06-26 16:58:36 -06005456 TIntermNode* root = intermediate.getTreeRoot();
5457
5458 if (root == 0)
5459 return;
5460
5461 glslang::GetThreadPoolAllocator().push();
5462
Lei Zhang17535f72016-05-04 15:55:59 -04005463 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005464 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005465 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005466 it.dumpSpv(spirv);
5467
5468 glslang::GetThreadPoolAllocator().pop();
5469}
5470
5471}; // end namespace glslang