blob: 1e03909bf6d2c928feaf118b4d4f9b05f88f76af [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
steve-lunarge7412492017-03-23 11:56:07 -0600872 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600873 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600874 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600875
steve-lunarge7412492017-03-23 11:56:07 -0600876 glslang::TLayoutGeometry primitive;
877
878 if (glslangIntermediate->getStage() == EShLangTessControl) {
879 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
880 primitive = glslangIntermediate->getOutputPrimitive();
881 } else {
882 primitive = glslangIntermediate->getInputPrimitive();
883 }
884
885 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700886 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
887 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
888 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600889 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600890 }
John Kessenich4016e382016-07-15 11:53:56 -0600891 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600892 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
893
John Kesseniche6903322015-10-13 16:29:02 -0600894 switch (glslangIntermediate->getVertexSpacing()) {
895 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
896 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
897 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600898 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600899 }
John Kessenich4016e382016-07-15 11:53:56 -0600900 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600901 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
902
903 switch (glslangIntermediate->getVertexOrder()) {
904 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
905 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600906 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600907 }
John Kessenich4016e382016-07-15 11:53:56 -0600908 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600909 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
910
911 if (glslangIntermediate->getPointMode())
912 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600913 break;
914
915 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600916 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600917 switch (glslangIntermediate->getInputPrimitive()) {
918 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
919 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
920 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700921 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600922 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600923 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600924 }
John Kessenich4016e382016-07-15 11:53:56 -0600925 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600926 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600927
John Kessenich140f3df2015-06-26 16:58:36 -0600928 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
929
930 switch (glslangIntermediate->getOutputPrimitive()) {
931 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
932 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
933 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600934 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600935 }
John Kessenich4016e382016-07-15 11:53:56 -0600936 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600937 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
938 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
939 break;
940
941 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600942 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600943 if (glslangIntermediate->getPixelCenterInteger())
944 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600945
John Kessenich140f3df2015-06-26 16:58:36 -0600946 if (glslangIntermediate->getOriginUpperLeft())
947 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600948 else
949 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600950
951 if (glslangIntermediate->getEarlyFragmentTests())
952 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
953
954 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600955 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
956 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600957 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600958 }
John Kessenich4016e382016-07-15 11:53:56 -0600959 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600960 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
961
962 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
963 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600964 break;
965
966 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600967 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600968 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
969 glslangIntermediate->getLocalSize(1),
970 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600971 break;
972
973 default:
974 break;
975 }
John Kessenich140f3df2015-06-26 16:58:36 -0600976}
977
John Kessenichfca82622016-11-26 13:23:20 -0700978// Finish creating SPV, after the traversal is complete.
979void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700980{
John Kessenich517fe7a2016-11-26 13:31:47 -0700981 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700982 builder.setBuildPoint(shaderEntry->getLastBlock());
983 builder.leaveFunction();
984 }
985
John Kessenich7ba63412015-12-20 17:37:07 -0700986 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100987 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
988 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700989
qiningda397332016-03-09 19:54:03 -0500990 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700991}
992
John Kessenichfca82622016-11-26 13:23:20 -0700993// Write the SPV into 'out'.
994void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -0600995{
John Kessenichfca82622016-11-26 13:23:20 -0700996 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -0600997}
998
999//
1000// Implement the traversal functions.
1001//
1002// Return true from interior nodes to have the external traversal
1003// continue on to children. Return false if children were
1004// already processed.
1005//
1006
1007//
qining25262b32016-05-06 17:25:16 -04001008// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001009// - uniform/input reads
1010// - output writes
1011// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1012// - something simple that degenerates into the last bullet
1013//
1014void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1015{
qining75d1d802016-04-06 14:42:01 -04001016 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1017 if (symbol->getType().getQualifier().isSpecConstant())
1018 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1019
John Kessenich140f3df2015-06-26 16:58:36 -06001020 // getSymbolId() will set up all the IO decorations on the first call.
1021 // Formal function parameters were mapped during makeFunctions().
1022 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001023
1024 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1025 if (builder.isPointer(id)) {
1026 spv::StorageClass sc = builder.getStorageClass(id);
1027 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1028 iOSet.insert(id);
1029 }
1030
1031 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001032 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001033 // Prepare to generate code for the access
1034
1035 // L-value chains will be computed left to right. We're on the symbol now,
1036 // which is the left-most part of the access chain, so now is "clear" time,
1037 // followed by setting the base.
1038 builder.clearAccessChain();
1039
1040 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001041 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001042 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001043 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001044 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001045 // These are also pure R-values.
1046 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001047 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001048 builder.setAccessChainRValue(id);
1049 else
1050 builder.setAccessChainLValue(id);
1051 }
1052}
1053
1054bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1055{
qining40887662016-04-03 22:20:42 -04001056 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1057 if (node->getType().getQualifier().isSpecConstant())
1058 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1059
John Kessenich140f3df2015-06-26 16:58:36 -06001060 // First, handle special cases
1061 switch (node->getOp()) {
1062 case glslang::EOpAssign:
1063 case glslang::EOpAddAssign:
1064 case glslang::EOpSubAssign:
1065 case glslang::EOpMulAssign:
1066 case glslang::EOpVectorTimesMatrixAssign:
1067 case glslang::EOpVectorTimesScalarAssign:
1068 case glslang::EOpMatrixTimesScalarAssign:
1069 case glslang::EOpMatrixTimesMatrixAssign:
1070 case glslang::EOpDivAssign:
1071 case glslang::EOpModAssign:
1072 case glslang::EOpAndAssign:
1073 case glslang::EOpInclusiveOrAssign:
1074 case glslang::EOpExclusiveOrAssign:
1075 case glslang::EOpLeftShiftAssign:
1076 case glslang::EOpRightShiftAssign:
1077 // A bin-op assign "a += b" means the same thing as "a = a + b"
1078 // where a is evaluated before b. For a simple assignment, GLSL
1079 // says to evaluate the left before the right. So, always, left
1080 // node then right node.
1081 {
1082 // get the left l-value, save it away
1083 builder.clearAccessChain();
1084 node->getLeft()->traverse(this);
1085 spv::Builder::AccessChain lValue = builder.getAccessChain();
1086
1087 // evaluate the right
1088 builder.clearAccessChain();
1089 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001090 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001091
1092 if (node->getOp() != glslang::EOpAssign) {
1093 // the left is also an r-value
1094 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001095 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001096
1097 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001098 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001099 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001100 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1101 node->getType().getBasicType());
1102
1103 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001104 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001105 }
1106
1107 // store the result
1108 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001109 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001110
1111 // assignments are expressions having an rValue after they are evaluated...
1112 builder.clearAccessChain();
1113 builder.setAccessChainRValue(rValue);
1114 }
1115 return false;
1116 case glslang::EOpIndexDirect:
1117 case glslang::EOpIndexDirectStruct:
1118 {
1119 // Get the left part of the access chain.
1120 node->getLeft()->traverse(this);
1121
1122 // Add the next element in the chain
1123
David Netoa901ffe2016-06-08 14:11:40 +01001124 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001125 if (! node->getLeft()->getType().isArray() &&
1126 node->getLeft()->getType().isVector() &&
1127 node->getOp() == glslang::EOpIndexDirect) {
1128 // This is essentially a hard-coded vector swizzle of size 1,
1129 // so short circuit the access-chain stuff with a swizzle.
1130 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001131 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001132 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001133 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001134 int spvIndex = glslangIndex;
1135 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1136 node->getOp() == glslang::EOpIndexDirectStruct)
1137 {
1138 // This may be, e.g., an anonymous block-member selection, which generally need
1139 // index remapping due to hidden members in anonymous blocks.
1140 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1141 assert(remapper.size() > 0);
1142 spvIndex = remapper[glslangIndex];
1143 }
John Kessenichebb50532016-05-16 19:22:05 -06001144
David Netoa901ffe2016-06-08 14:11:40 +01001145 // normal case for indexing array or structure or block
1146 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1147
1148 // Add capabilities here for accessing PointSize and clip/cull distance.
1149 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001150 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001151 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001152 }
1153 }
1154 return false;
1155 case glslang::EOpIndexIndirect:
1156 {
1157 // Structure or array or vector indirection.
1158 // Will use native SPIR-V access-chain for struct and array indirection;
1159 // matrices are arrays of vectors, so will also work for a matrix.
1160 // Will use the access chain's 'component' for variable index into a vector.
1161
1162 // This adapter is building access chains left to right.
1163 // Set up the access chain to the left.
1164 node->getLeft()->traverse(this);
1165
1166 // save it so that computing the right side doesn't trash it
1167 spv::Builder::AccessChain partial = builder.getAccessChain();
1168
1169 // compute the next index in the chain
1170 builder.clearAccessChain();
1171 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001172 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001173
1174 // restore the saved access chain
1175 builder.setAccessChain(partial);
1176
1177 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001178 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001179 else
John Kessenichfa668da2015-09-13 14:46:30 -06001180 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001181 }
1182 return false;
1183 case glslang::EOpVectorSwizzle:
1184 {
1185 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001186 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001187 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001188 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001189 }
1190 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001191 case glslang::EOpMatrixSwizzle:
1192 logger->missingFunctionality("matrix swizzle");
1193 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001194 case glslang::EOpLogicalOr:
1195 case glslang::EOpLogicalAnd:
1196 {
1197
1198 // These may require short circuiting, but can sometimes be done as straight
1199 // binary operations. The right operand must be short circuited if it has
1200 // side effects, and should probably be if it is complex.
1201 if (isTrivial(node->getRight()->getAsTyped()))
1202 break; // handle below as a normal binary operation
1203 // otherwise, we need to do dynamic short circuiting on the right operand
1204 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1205 builder.clearAccessChain();
1206 builder.setAccessChainRValue(result);
1207 }
1208 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001209 default:
1210 break;
1211 }
1212
1213 // Assume generic binary op...
1214
John Kessenich32cfd492016-02-02 12:37:46 -07001215 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001216 builder.clearAccessChain();
1217 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001218 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001219
John Kessenich32cfd492016-02-02 12:37:46 -07001220 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001221 builder.clearAccessChain();
1222 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001223 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001224
John Kessenich32cfd492016-02-02 12:37:46 -07001225 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001226 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001227 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001228 convertGlslangToSpvType(node->getType()), left, right,
1229 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001230
John Kessenich50e57562015-12-21 21:21:11 -07001231 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001232 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001233 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001234 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001235 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001236 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001237 return false;
1238 }
John Kessenich140f3df2015-06-26 16:58:36 -06001239}
1240
1241bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1242{
qining40887662016-04-03 22:20:42 -04001243 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1244 if (node->getType().getQualifier().isSpecConstant())
1245 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1246
John Kessenichfc51d282015-08-19 13:34:18 -06001247 spv::Id result = spv::NoResult;
1248
1249 // try texturing first
1250 result = createImageTextureFunctionCall(node);
1251 if (result != spv::NoResult) {
1252 builder.clearAccessChain();
1253 builder.setAccessChainRValue(result);
1254
1255 return false; // done with this node
1256 }
1257
1258 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001259
1260 if (node->getOp() == glslang::EOpArrayLength) {
1261 // Quite special; won't want to evaluate the operand.
1262
1263 // Normal .length() would have been constant folded by the front-end.
1264 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001265 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001266 assert(node->getOperand()->getType().isRuntimeSizedArray());
1267 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1268 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001269 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1270 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001271
1272 builder.clearAccessChain();
1273 builder.setAccessChainRValue(length);
1274
1275 return false;
1276 }
1277
John Kessenichfc51d282015-08-19 13:34:18 -06001278 // Start by evaluating the operand
1279
John Kessenich8c8505c2016-07-26 12:50:38 -06001280 // Does it need a swizzle inversion? If so, evaluation is inverted;
1281 // operate first on the swizzle base, then apply the swizzle.
1282 spv::Id invertedType = spv::NoType;
1283 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1284 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1285 invertedType = getInvertedSwizzleType(*node->getOperand());
1286
John Kessenich140f3df2015-06-26 16:58:36 -06001287 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001288 if (invertedType != spv::NoType)
1289 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1290 else
1291 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001292
Rex Xufc618912015-09-09 16:42:49 +08001293 spv::Id operand = spv::NoResult;
1294
1295 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1296 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001297 node->getOp() == glslang::EOpAtomicCounter ||
1298 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001299 operand = builder.accessChainGetLValue(); // Special case l-value operands
1300 else
John Kessenich32cfd492016-02-02 12:37:46 -07001301 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001302
John Kessenichf6640762016-08-01 19:44:00 -06001303 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001304 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001305
1306 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001307 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001308 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001309
1310 // if not, then possibly an operation
1311 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001312 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001313
1314 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001315 if (invertedType)
1316 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1317
John Kessenich140f3df2015-06-26 16:58:36 -06001318 builder.clearAccessChain();
1319 builder.setAccessChainRValue(result);
1320
1321 return false; // done with this node
1322 }
1323
1324 // it must be a special case, check...
1325 switch (node->getOp()) {
1326 case glslang::EOpPostIncrement:
1327 case glslang::EOpPostDecrement:
1328 case glslang::EOpPreIncrement:
1329 case glslang::EOpPreDecrement:
1330 {
1331 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001332 spv::Id one = 0;
1333 if (node->getBasicType() == glslang::EbtFloat)
1334 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001335 else if (node->getBasicType() == glslang::EbtDouble)
1336 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001337#ifdef AMD_EXTENSIONS
1338 else if (node->getBasicType() == glslang::EbtFloat16)
1339 one = builder.makeFloat16Constant(1.0F);
1340#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001341 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1342 one = builder.makeInt64Constant(1);
1343 else
1344 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001345 glslang::TOperator op;
1346 if (node->getOp() == glslang::EOpPreIncrement ||
1347 node->getOp() == glslang::EOpPostIncrement)
1348 op = glslang::EOpAdd;
1349 else
1350 op = glslang::EOpSub;
1351
John Kessenichf6640762016-08-01 19:44:00 -06001352 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001353 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001354 convertGlslangToSpvType(node->getType()), operand, one,
1355 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001356 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001357
1358 // The result of operation is always stored, but conditionally the
1359 // consumed result. The consumed result is always an r-value.
1360 builder.accessChainStore(result);
1361 builder.clearAccessChain();
1362 if (node->getOp() == glslang::EOpPreIncrement ||
1363 node->getOp() == glslang::EOpPreDecrement)
1364 builder.setAccessChainRValue(result);
1365 else
1366 builder.setAccessChainRValue(operand);
1367 }
1368
1369 return false;
1370
1371 case glslang::EOpEmitStreamVertex:
1372 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1373 return false;
1374 case glslang::EOpEndStreamPrimitive:
1375 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1376 return false;
1377
1378 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001379 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001380 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001381 }
John Kessenich140f3df2015-06-26 16:58:36 -06001382}
1383
1384bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1385{
qining27e04a02016-04-14 16:40:20 -04001386 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1387 if (node->getType().getQualifier().isSpecConstant())
1388 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1389
John Kessenichfc51d282015-08-19 13:34:18 -06001390 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001391 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1392 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001393
1394 // try texturing
1395 result = createImageTextureFunctionCall(node);
1396 if (result != spv::NoResult) {
1397 builder.clearAccessChain();
1398 builder.setAccessChainRValue(result);
1399
1400 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001401 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001402 // "imageStore" is a special case, which has no result
1403 return false;
1404 }
John Kessenichfc51d282015-08-19 13:34:18 -06001405
John Kessenich140f3df2015-06-26 16:58:36 -06001406 glslang::TOperator binOp = glslang::EOpNull;
1407 bool reduceComparison = true;
1408 bool isMatrix = false;
1409 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001410 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001411
1412 assert(node->getOp());
1413
John Kessenichf6640762016-08-01 19:44:00 -06001414 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001415
1416 switch (node->getOp()) {
1417 case glslang::EOpSequence:
1418 {
1419 if (preVisit)
1420 ++sequenceDepth;
1421 else
1422 --sequenceDepth;
1423
1424 if (sequenceDepth == 1) {
1425 // If this is the parent node of all the functions, we want to see them
1426 // early, so all call points have actual SPIR-V functions to reference.
1427 // In all cases, still let the traverser visit the children for us.
1428 makeFunctions(node->getAsAggregate()->getSequence());
1429
John Kessenich6fccb3c2016-09-19 16:01:41 -06001430 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001431 // anything else gets there, so visit out of order, doing them all now.
1432 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1433
John Kessenich6a60c2f2016-12-08 21:01:59 -07001434 // 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 -06001435 // so do them manually.
1436 visitFunctions(node->getAsAggregate()->getSequence());
1437
1438 return false;
1439 }
1440
1441 return true;
1442 }
1443 case glslang::EOpLinkerObjects:
1444 {
1445 if (visit == glslang::EvPreVisit)
1446 linkageOnly = true;
1447 else
1448 linkageOnly = false;
1449
1450 return true;
1451 }
1452 case glslang::EOpComma:
1453 {
1454 // processing from left to right naturally leaves the right-most
1455 // lying around in the access chain
1456 glslang::TIntermSequence& glslangOperands = node->getSequence();
1457 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1458 glslangOperands[i]->traverse(this);
1459
1460 return false;
1461 }
1462 case glslang::EOpFunction:
1463 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001464 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001465 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001466 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001467 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001468 } else {
1469 handleFunctionEntry(node);
1470 }
1471 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001472 if (inEntryPoint)
1473 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001474 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001475 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001476 }
1477
1478 return true;
1479 case glslang::EOpParameters:
1480 // Parameters will have been consumed by EOpFunction processing, but not
1481 // the body, so we still visited the function node's children, making this
1482 // child redundant.
1483 return false;
1484 case glslang::EOpFunctionCall:
1485 {
1486 if (node->isUserDefined())
1487 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001488 // 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 -07001489 if (result) {
1490 builder.clearAccessChain();
1491 builder.setAccessChainRValue(result);
1492 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001493 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001494
1495 return false;
1496 }
1497 case glslang::EOpConstructMat2x2:
1498 case glslang::EOpConstructMat2x3:
1499 case glslang::EOpConstructMat2x4:
1500 case glslang::EOpConstructMat3x2:
1501 case glslang::EOpConstructMat3x3:
1502 case glslang::EOpConstructMat3x4:
1503 case glslang::EOpConstructMat4x2:
1504 case glslang::EOpConstructMat4x3:
1505 case glslang::EOpConstructMat4x4:
1506 case glslang::EOpConstructDMat2x2:
1507 case glslang::EOpConstructDMat2x3:
1508 case glslang::EOpConstructDMat2x4:
1509 case glslang::EOpConstructDMat3x2:
1510 case glslang::EOpConstructDMat3x3:
1511 case glslang::EOpConstructDMat3x4:
1512 case glslang::EOpConstructDMat4x2:
1513 case glslang::EOpConstructDMat4x3:
1514 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001515#ifdef AMD_EXTENSIONS
1516 case glslang::EOpConstructF16Mat2x2:
1517 case glslang::EOpConstructF16Mat2x3:
1518 case glslang::EOpConstructF16Mat2x4:
1519 case glslang::EOpConstructF16Mat3x2:
1520 case glslang::EOpConstructF16Mat3x3:
1521 case glslang::EOpConstructF16Mat3x4:
1522 case glslang::EOpConstructF16Mat4x2:
1523 case glslang::EOpConstructF16Mat4x3:
1524 case glslang::EOpConstructF16Mat4x4:
1525#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001526 isMatrix = true;
1527 // fall through
1528 case glslang::EOpConstructFloat:
1529 case glslang::EOpConstructVec2:
1530 case glslang::EOpConstructVec3:
1531 case glslang::EOpConstructVec4:
1532 case glslang::EOpConstructDouble:
1533 case glslang::EOpConstructDVec2:
1534 case glslang::EOpConstructDVec3:
1535 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001536#ifdef AMD_EXTENSIONS
1537 case glslang::EOpConstructFloat16:
1538 case glslang::EOpConstructF16Vec2:
1539 case glslang::EOpConstructF16Vec3:
1540 case glslang::EOpConstructF16Vec4:
1541#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001542 case glslang::EOpConstructBool:
1543 case glslang::EOpConstructBVec2:
1544 case glslang::EOpConstructBVec3:
1545 case glslang::EOpConstructBVec4:
1546 case glslang::EOpConstructInt:
1547 case glslang::EOpConstructIVec2:
1548 case glslang::EOpConstructIVec3:
1549 case glslang::EOpConstructIVec4:
1550 case glslang::EOpConstructUint:
1551 case glslang::EOpConstructUVec2:
1552 case glslang::EOpConstructUVec3:
1553 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001554 case glslang::EOpConstructInt64:
1555 case glslang::EOpConstructI64Vec2:
1556 case glslang::EOpConstructI64Vec3:
1557 case glslang::EOpConstructI64Vec4:
1558 case glslang::EOpConstructUint64:
1559 case glslang::EOpConstructU64Vec2:
1560 case glslang::EOpConstructU64Vec3:
1561 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001562 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001563 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001564 {
1565 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001566 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001567 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001568 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001569 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001570 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001571 std::vector<spv::Id> constituents;
1572 for (int c = 0; c < (int)arguments.size(); ++c)
1573 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001574 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001575 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001576 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001577 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001578 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001579
1580 builder.clearAccessChain();
1581 builder.setAccessChainRValue(constructed);
1582
1583 return false;
1584 }
1585
1586 // These six are component-wise compares with component-wise results.
1587 // Forward on to createBinaryOperation(), requesting a vector result.
1588 case glslang::EOpLessThan:
1589 case glslang::EOpGreaterThan:
1590 case glslang::EOpLessThanEqual:
1591 case glslang::EOpGreaterThanEqual:
1592 case glslang::EOpVectorEqual:
1593 case glslang::EOpVectorNotEqual:
1594 {
1595 // Map the operation to a binary
1596 binOp = node->getOp();
1597 reduceComparison = false;
1598 switch (node->getOp()) {
1599 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1600 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1601 default: binOp = node->getOp(); break;
1602 }
1603
1604 break;
1605 }
1606 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001607 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001608 binOp = glslang::EOpMul;
1609 break;
1610 case glslang::EOpOuterProduct:
1611 // two vectors multiplied to make a matrix
1612 binOp = glslang::EOpOuterProduct;
1613 break;
1614 case glslang::EOpDot:
1615 {
qining25262b32016-05-06 17:25:16 -04001616 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001617 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001618 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001619 binOp = glslang::EOpMul;
1620 break;
1621 }
1622 case glslang::EOpMod:
1623 // when an aggregate, this is the floating-point mod built-in function,
1624 // which can be emitted by the one in createBinaryOperation()
1625 binOp = glslang::EOpMod;
1626 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001627 case glslang::EOpEmitVertex:
1628 case glslang::EOpEndPrimitive:
1629 case glslang::EOpBarrier:
1630 case glslang::EOpMemoryBarrier:
1631 case glslang::EOpMemoryBarrierAtomicCounter:
1632 case glslang::EOpMemoryBarrierBuffer:
1633 case glslang::EOpMemoryBarrierImage:
1634 case glslang::EOpMemoryBarrierShared:
1635 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001636 case glslang::EOpAllMemoryBarrierWithGroupSync:
1637 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1638 case glslang::EOpWorkgroupMemoryBarrier:
1639 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001640 noReturnValue = true;
1641 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1642 break;
1643
John Kessenich426394d2015-07-23 10:22:48 -06001644 case glslang::EOpAtomicAdd:
1645 case glslang::EOpAtomicMin:
1646 case glslang::EOpAtomicMax:
1647 case glslang::EOpAtomicAnd:
1648 case glslang::EOpAtomicOr:
1649 case glslang::EOpAtomicXor:
1650 case glslang::EOpAtomicExchange:
1651 case glslang::EOpAtomicCompSwap:
1652 atomic = true;
1653 break;
1654
John Kessenich140f3df2015-06-26 16:58:36 -06001655 default:
1656 break;
1657 }
1658
1659 //
1660 // See if it maps to a regular operation.
1661 //
John Kessenich140f3df2015-06-26 16:58:36 -06001662 if (binOp != glslang::EOpNull) {
1663 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1664 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1665 assert(left && right);
1666
1667 builder.clearAccessChain();
1668 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001669 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001670
1671 builder.clearAccessChain();
1672 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001673 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001674
qining25262b32016-05-06 17:25:16 -04001675 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001676 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001677 left->getType().getBasicType(), reduceComparison);
1678
1679 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001680 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001681 builder.clearAccessChain();
1682 builder.setAccessChainRValue(result);
1683
1684 return false;
1685 }
1686
John Kessenich426394d2015-07-23 10:22:48 -06001687 //
1688 // Create the list of operands.
1689 //
John Kessenich140f3df2015-06-26 16:58:36 -06001690 glslang::TIntermSequence& glslangOperands = node->getSequence();
1691 std::vector<spv::Id> operands;
1692 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001693 // special case l-value operands; there are just a few
1694 bool lvalue = false;
1695 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001696 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001697 case glslang::EOpModf:
1698 if (arg == 1)
1699 lvalue = true;
1700 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001701 case glslang::EOpInterpolateAtSample:
1702 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001703#ifdef AMD_EXTENSIONS
1704 case glslang::EOpInterpolateAtVertex:
1705#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001706 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001707 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001708
1709 // Does it need a swizzle inversion? If so, evaluation is inverted;
1710 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001711 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001712 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1713 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1714 }
Rex Xu7a26c172015-12-08 17:12:09 +08001715 break;
Rex Xud4782c12015-09-06 16:30:11 +08001716 case glslang::EOpAtomicAdd:
1717 case glslang::EOpAtomicMin:
1718 case glslang::EOpAtomicMax:
1719 case glslang::EOpAtomicAnd:
1720 case glslang::EOpAtomicOr:
1721 case glslang::EOpAtomicXor:
1722 case glslang::EOpAtomicExchange:
1723 case glslang::EOpAtomicCompSwap:
1724 if (arg == 0)
1725 lvalue = true;
1726 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001727 case glslang::EOpAddCarry:
1728 case glslang::EOpSubBorrow:
1729 if (arg == 2)
1730 lvalue = true;
1731 break;
1732 case glslang::EOpUMulExtended:
1733 case glslang::EOpIMulExtended:
1734 if (arg >= 2)
1735 lvalue = true;
1736 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001737 default:
1738 break;
1739 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001740 builder.clearAccessChain();
1741 if (invertedType != spv::NoType && arg == 0)
1742 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1743 else
1744 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001745 if (lvalue)
1746 operands.push_back(builder.accessChainGetLValue());
1747 else
John Kessenich32cfd492016-02-02 12:37:46 -07001748 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001749 }
John Kessenich426394d2015-07-23 10:22:48 -06001750
1751 if (atomic) {
1752 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001753 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001754 } else {
1755 // Pass through to generic operations.
1756 switch (glslangOperands.size()) {
1757 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001758 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001759 break;
1760 case 1:
qining25262b32016-05-06 17:25:16 -04001761 result = createUnaryOperation(
1762 node->getOp(), precision,
1763 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001764 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001765 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001766 break;
1767 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001768 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001769 break;
1770 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001771 if (invertedType)
1772 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001773 }
1774
1775 if (noReturnValue)
1776 return false;
1777
1778 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001779 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001780 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001781 } else {
1782 builder.clearAccessChain();
1783 builder.setAccessChainRValue(result);
1784 return false;
1785 }
1786}
1787
John Kessenich433e9ff2017-01-26 20:31:11 -07001788// This path handles both if-then-else and ?:
1789// The if-then-else has a node type of void, while
1790// ?: has either a void or a non-void node type
1791//
1792// Leaving the result, when not void:
1793// GLSL only has r-values as the result of a :?, but
1794// if we have an l-value, that can be more efficient if it will
1795// become the base of a complex r-value expression, because the
1796// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001797bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1798{
John Kessenich433e9ff2017-01-26 20:31:11 -07001799 // See if it simple and safe to generate OpSelect instead of using control flow.
1800 // Crucially, side effects must be avoided, and there are performance trade-offs.
1801 // Return true if good idea (and safe) for OpSelect, false otherwise.
1802 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001803 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1804 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001805 return false;
1806
1807 if (node->getTrueBlock() == nullptr ||
1808 node->getFalseBlock() == nullptr)
1809 return false;
1810
1811 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1812 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1813
1814 // return true if a single operand to ? : is okay for OpSelect
1815 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001816 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001817 };
1818
1819 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1820 operandOkay(node->getFalseBlock()->getAsTyped());
1821 };
1822
1823 // Emit OpSelect for this selection.
1824 const auto handleAsOpSelect = [&]() {
1825 node->getCondition()->traverse(this);
1826 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1827 node->getTrueBlock()->traverse(this);
1828 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1829 node->getFalseBlock()->traverse(this);
1830 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1831
John Kesseniche434ad92017-03-30 10:09:28 -06001832 // smear condition to vector, if necessary (AST is always scalar)
1833 if (builder.isVector(trueValue))
1834 condition = builder.smearScalar(spv::NoPrecision, condition,
1835 builder.makeVectorType(builder.makeBoolType(),
1836 builder.getNumComponents(trueValue)));
1837
1838 spv::Id select = builder.createTriOp(spv::OpSelect,
1839 convertGlslangToSpvType(node->getType()), condition,
1840 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001841 builder.clearAccessChain();
1842 builder.setAccessChainRValue(select);
1843 };
1844
1845 // Try for OpSelect
1846
1847 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001848 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1849 if (node->getType().getQualifier().isSpecConstant())
1850 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1851
John Kessenich433e9ff2017-01-26 20:31:11 -07001852 handleAsOpSelect();
1853 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001854 }
1855
John Kessenich433e9ff2017-01-26 20:31:11 -07001856 // Instead, emit control flow...
1857
1858 // Don't handle results as temporaries, because there will be two names
1859 // and better to leave SSA to later passes.
1860 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1861 ? spv::NoResult
1862 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1863
John Kessenich140f3df2015-06-26 16:58:36 -06001864 // emit the condition before doing anything with selection
1865 node->getCondition()->traverse(this);
1866
1867 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001868 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001869
John Kessenich433e9ff2017-01-26 20:31:11 -07001870 // emit the "then" statement
1871 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001872 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001873 if (result != spv::NoResult)
1874 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001875 }
1876
John Kessenich433e9ff2017-01-26 20:31:11 -07001877 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001878 ifBuilder.makeBeginElse();
1879 // emit the "else" statement
1880 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001881 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001882 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001883 }
1884
John Kessenich433e9ff2017-01-26 20:31:11 -07001885 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001886 ifBuilder.makeEndIf();
1887
John Kessenich433e9ff2017-01-26 20:31:11 -07001888 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001889 // GLSL only has r-values as the result of a :?, but
1890 // if we have an l-value, that can be more efficient if it will
1891 // become the base of a complex r-value expression, because the
1892 // next layer copies r-values into memory to use the access-chain mechanism
1893 builder.clearAccessChain();
1894 builder.setAccessChainLValue(result);
1895 }
1896
1897 return false;
1898}
1899
1900bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1901{
1902 // emit and get the condition before doing anything with switch
1903 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001904 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001905
1906 // browse the children to sort out code segments
1907 int defaultSegment = -1;
1908 std::vector<TIntermNode*> codeSegments;
1909 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1910 std::vector<int> caseValues;
1911 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1912 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1913 TIntermNode* child = *c;
1914 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001915 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001916 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001917 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001918 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1919 } else
1920 codeSegments.push_back(child);
1921 }
1922
qining25262b32016-05-06 17:25:16 -04001923 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001924 // statements between the last case and the end of the switch statement
1925 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1926 (int)codeSegments.size() == defaultSegment)
1927 codeSegments.push_back(nullptr);
1928
1929 // make the switch statement
1930 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001931 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001932
1933 // emit all the code in the segments
1934 breakForLoop.push(false);
1935 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1936 builder.nextSwitchSegment(segmentBlocks, s);
1937 if (codeSegments[s])
1938 codeSegments[s]->traverse(this);
1939 else
1940 builder.addSwitchBreak();
1941 }
1942 breakForLoop.pop();
1943
1944 builder.endSwitch(segmentBlocks);
1945
1946 return false;
1947}
1948
1949void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1950{
1951 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001952 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001953
1954 builder.clearAccessChain();
1955 builder.setAccessChainRValue(constant);
1956}
1957
1958bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1959{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001960 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001961 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001962 // Spec requires back edges to target header blocks, and every header block
1963 // must dominate its merge block. Make a header block first to ensure these
1964 // conditions are met. By definition, it will contain OpLoopMerge, followed
1965 // by a block-ending branch. But we don't want to put any other body/test
1966 // instructions in it, since the body/test may have arbitrary instructions,
1967 // including merges of its own.
1968 builder.setBuildPoint(&blocks.head);
1969 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001970 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001971 spv::Block& test = builder.makeNewBlock();
1972 builder.createBranch(&test);
1973
1974 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001975 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001976 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001977 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001978 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1979
1980 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001981 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001982 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);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001990 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001991 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001992 builder.createBranch(&blocks.body);
1993
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001994 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001995 builder.setBuildPoint(&blocks.body);
1996 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001997 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001998 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001999 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002000
2001 builder.setBuildPoint(&blocks.continue_target);
2002 if (node->getTerminal())
2003 node->getTerminal()->traverse(this);
2004 if (node->getTest()) {
2005 node->getTest()->traverse(this);
2006 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002007 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002008 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002009 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002010 // TODO: unless there was a break/return/discard instruction
2011 // somewhere in the body, this is an infinite loop, so we should
2012 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002013 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002014 }
John Kessenich140f3df2015-06-26 16:58:36 -06002015 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002016 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002017 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002018 return false;
2019}
2020
2021bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2022{
2023 if (node->getExpression())
2024 node->getExpression()->traverse(this);
2025
2026 switch (node->getFlowOp()) {
2027 case glslang::EOpKill:
2028 builder.makeDiscard();
2029 break;
2030 case glslang::EOpBreak:
2031 if (breakForLoop.top())
2032 builder.createLoopExit();
2033 else
2034 builder.addSwitchBreak();
2035 break;
2036 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002037 builder.createLoopContinue();
2038 break;
2039 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002040 if (node->getExpression()) {
2041 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2042 spv::Id returnId = accessChainLoad(glslangReturnType);
2043 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2044 builder.clearAccessChain();
2045 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2046 builder.setAccessChainLValue(copyId);
2047 multiTypeStore(glslangReturnType, returnId);
2048 returnId = builder.createLoad(copyId);
2049 }
2050 builder.makeReturn(false, returnId);
2051 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002052 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002053
2054 builder.clearAccessChain();
2055 break;
2056
2057 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002058 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002059 break;
2060 }
2061
2062 return false;
2063}
2064
2065spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2066{
qining25262b32016-05-06 17:25:16 -04002067 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002068 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002069 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002070 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002071 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002072 }
2073
2074 // Now, handle actual variables
2075 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
2076 spv::Id spvType = convertGlslangToSpvType(node->getType());
2077
2078 const char* name = node->getName().c_str();
2079 if (glslang::IsAnonymous(name))
2080 name = "";
2081
2082 return builder.createVariable(storageClass, spvType, name);
2083}
2084
2085// Return type Id of the sampled type.
2086spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2087{
2088 switch (sampler.type) {
2089 case glslang::EbtFloat: return builder.makeFloatType(32);
2090 case glslang::EbtInt: return builder.makeIntType(32);
2091 case glslang::EbtUint: return builder.makeUintType(32);
2092 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002093 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002094 return builder.makeFloatType(32);
2095 }
2096}
2097
John Kessenich8c8505c2016-07-26 12:50:38 -06002098// If node is a swizzle operation, return the type that should be used if
2099// the swizzle base is first consumed by another operation, before the swizzle
2100// is applied.
2101spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2102{
John Kessenichecba76f2017-01-06 00:34:48 -07002103 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002104 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2105 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2106 else
2107 return spv::NoType;
2108}
2109
2110// When inverting a swizzle with a parent op, this function
2111// will apply the swizzle operation to a completed parent operation.
2112spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2113{
2114 std::vector<unsigned> swizzle;
2115 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2116 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2117}
2118
John Kessenich8c8505c2016-07-26 12:50:38 -06002119// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2120void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2121{
2122 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2123 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2124 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2125}
2126
John Kessenich3ac051e2015-12-20 11:29:16 -07002127// Convert from a glslang type to an SPV type, by calling into a
2128// recursive version of this function. This establishes the inherited
2129// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002130spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2131{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002132 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002133}
2134
2135// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002136// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002137// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002138spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002139{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002140 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002141
2142 switch (type.getBasicType()) {
2143 case glslang::EbtVoid:
2144 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002145 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002146 break;
2147 case glslang::EbtFloat:
2148 spvType = builder.makeFloatType(32);
2149 break;
2150 case glslang::EbtDouble:
2151 spvType = builder.makeFloatType(64);
2152 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002153#ifdef AMD_EXTENSIONS
2154 case glslang::EbtFloat16:
2155 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002156 spvType = builder.makeFloatType(16);
2157 break;
2158#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002159 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002160 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2161 // a 32-bit int where non-0 means true.
2162 if (explicitLayout != glslang::ElpNone)
2163 spvType = builder.makeUintType(32);
2164 else
2165 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002166 break;
2167 case glslang::EbtInt:
2168 spvType = builder.makeIntType(32);
2169 break;
2170 case glslang::EbtUint:
2171 spvType = builder.makeUintType(32);
2172 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002173 case glslang::EbtInt64:
2174 builder.addCapability(spv::CapabilityInt64);
2175 spvType = builder.makeIntType(64);
2176 break;
2177 case glslang::EbtUint64:
2178 builder.addCapability(spv::CapabilityInt64);
2179 spvType = builder.makeUintType(64);
2180 break;
John Kessenich426394d2015-07-23 10:22:48 -06002181 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002182 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002183 spvType = builder.makeUintType(32);
2184 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002185 case glslang::EbtSampler:
2186 {
2187 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002188 if (sampler.sampler) {
2189 // pure sampler
2190 spvType = builder.makeSamplerType();
2191 } else {
2192 // an image is present, make its type
2193 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2194 sampler.image ? 2 : 1, TranslateImageFormat(type));
2195 if (sampler.combined) {
2196 // already has both image and sampler, make the combined type
2197 spvType = builder.makeSampledImageType(spvType);
2198 }
John Kessenich55e7d112015-11-15 21:33:39 -07002199 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002200 }
John Kessenich140f3df2015-06-26 16:58:36 -06002201 break;
2202 case glslang::EbtStruct:
2203 case glslang::EbtBlock:
2204 {
2205 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002206 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002207
2208 // Try to share structs for different layouts, but not yet for other
2209 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002210 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002211 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002212 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002213 break;
2214
2215 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002216 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002217 memberRemapper[glslangMembers].resize(glslangMembers->size());
2218 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002219 }
2220 break;
2221 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002222 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002223 break;
2224 }
2225
2226 if (type.isMatrix())
2227 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2228 else {
2229 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2230 if (type.getVectorSize() > 1)
2231 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2232 }
2233
2234 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002235 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2236
John Kessenichc9a80832015-09-12 12:17:44 -06002237 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002238 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002239 // We need to decorate array strides for types needing explicit layout, except blocks.
2240 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002241 // Use a dummy glslang type for querying internal strides of
2242 // arrays of arrays, but using just a one-dimensional array.
2243 glslang::TType simpleArrayType(type, 0); // deference type of the array
2244 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2245 simpleArrayType.getArraySizes().dereference();
2246
2247 // Will compute the higher-order strides here, rather than making a whole
2248 // pile of types and doing repetitive recursion on their contents.
2249 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2250 }
John Kessenichf8842e52016-01-04 19:22:56 -07002251
2252 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002253 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002254 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002255 if (stride > 0)
2256 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002257 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002258 }
2259 } else {
2260 // single-dimensional array, and don't yet have stride
2261
John Kessenichf8842e52016-01-04 19:22:56 -07002262 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002263 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2264 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002265 }
John Kessenich31ed4832015-09-09 17:51:38 -06002266
John Kessenichc9a80832015-09-12 12:17:44 -06002267 // Do the outer dimension, which might not be known for a runtime-sized array
2268 if (type.isRuntimeSizedArray()) {
2269 spvType = builder.makeRuntimeArray(spvType);
2270 } else {
2271 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002272 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002273 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002274 if (stride > 0)
2275 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002276 }
2277
2278 return spvType;
2279}
2280
John Kessenich0e737842017-03-24 18:38:16 -06002281// TODO: this functionality should exist at a higher level, in creating the AST
2282//
2283// Identify interface members that don't have their required extension turned on.
2284//
2285bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2286{
2287 auto& extensions = glslangIntermediate->getRequestedExtensions();
2288
Rex Xubcf291a2017-03-29 23:01:36 +08002289 if (member.getFieldName() == "gl_ViewportMask" &&
2290 extensions.find("GL_NV_viewport_array2") == extensions.end())
2291 return true;
2292 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2293 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2294 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002295 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2296 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2297 return true;
2298 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2299 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2300 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002301 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2302 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2303 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002304
2305 return false;
2306};
2307
John Kessenich6090df02016-06-30 21:18:02 -06002308// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2309// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2310// Mutually recursive with convertGlslangToSpvType().
2311spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2312 const glslang::TTypeList* glslangMembers,
2313 glslang::TLayoutPacking explicitLayout,
2314 const glslang::TQualifier& qualifier)
2315{
2316 // Create a vector of struct types for SPIR-V to consume
2317 std::vector<spv::Id> spvMembers;
2318 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2319 int locationOffset = 0; // for use across struct members, when they are called recursively
2320 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2321 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2322 if (glslangMember.hiddenMember()) {
2323 ++memberDelta;
2324 if (type.getBasicType() == glslang::EbtBlock)
2325 memberRemapper[glslangMembers][i] = -1;
2326 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002327 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002328 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002329 if (filterMember(glslangMember))
2330 continue;
2331 }
John Kessenich6090df02016-06-30 21:18:02 -06002332 // modify just this child's view of the qualifier
2333 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2334 InheritQualifiers(memberQualifier, qualifier);
2335
2336 // manually inherit location; it's more complex
2337 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2338 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2339 if (qualifier.hasLocation())
2340 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2341
2342 // recurse
2343 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2344 }
2345 }
2346
2347 // Make the SPIR-V type
2348 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002349 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002350 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2351
2352 // Decorate it
2353 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2354
2355 return spvType;
2356}
2357
2358void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2359 const glslang::TTypeList* glslangMembers,
2360 glslang::TLayoutPacking explicitLayout,
2361 const glslang::TQualifier& qualifier,
2362 spv::Id spvType)
2363{
2364 // Name and decorate the non-hidden members
2365 int offset = -1;
2366 int locationOffset = 0; // for use within the members of this struct
2367 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2368 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2369 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002370 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002371 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002372 if (filterMember(glslangMember))
2373 continue;
2374 }
John Kessenich6090df02016-06-30 21:18:02 -06002375
2376 // modify just this child's view of the qualifier
2377 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2378 InheritQualifiers(memberQualifier, qualifier);
2379
2380 // using -1 above to indicate a hidden member
2381 if (member >= 0) {
2382 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2383 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2384 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2385 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002386 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2387 type.getQualifier().storage == glslang::EvqVaryingOut) {
2388 if (type.getBasicType() == glslang::EbtBlock ||
2389 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002390 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2391 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2392 }
2393 }
2394 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2395
2396 if (qualifier.storage == glslang::EvqBuffer) {
2397 std::vector<spv::Decoration> memory;
2398 TranslateMemoryDecoration(memberQualifier, memory);
2399 for (unsigned int i = 0; i < memory.size(); ++i)
2400 addMemberDecoration(spvType, member, memory[i]);
2401 }
2402
John Kessenich2f47bc92016-06-30 21:47:35 -06002403 // Compute location decoration; tricky based on whether inheritance is at play and
2404 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002405 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2406 // probably move to the linker stage of the front end proper, and just have the
2407 // answer sitting already distributed throughout the individual member locations.
2408 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002409 // Ignore member locations if the container is an array, as that's
2410 // ill-specified and decisions have been made to not allow this anyway.
2411 // The object itself must have a location, and that comes out from decorating the object,
2412 // not the type (this code decorates types).
2413 if (! type.isArray()) {
2414 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2415 // struct members should not have explicit locations
2416 assert(type.getBasicType() != glslang::EbtStruct);
2417 location = memberQualifier.layoutLocation;
2418 } else if (type.getBasicType() != glslang::EbtBlock) {
2419 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2420 // The members, and their nested types, must not themselves have Location decorations.
2421 } else if (qualifier.hasLocation()) // inheritance
2422 location = qualifier.layoutLocation + locationOffset;
2423 }
John Kessenich6090df02016-06-30 21:18:02 -06002424 if (location >= 0)
2425 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2426
John Kessenich2f47bc92016-06-30 21:47:35 -06002427 if (qualifier.hasLocation()) // track for upcoming inheritance
2428 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2429
John Kessenich6090df02016-06-30 21:18:02 -06002430 // component, XFB, others
2431 if (glslangMember.getQualifier().hasComponent())
2432 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2433 if (glslangMember.getQualifier().hasXfbOffset())
2434 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2435 else if (explicitLayout != glslang::ElpNone) {
2436 // figure out what to do with offset, which is accumulating
2437 int nextOffset;
2438 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2439 if (offset >= 0)
2440 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2441 offset = nextOffset;
2442 }
2443
2444 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2445 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2446
2447 // built-in variable decorations
2448 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002449 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002450 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002451
2452#ifdef NV_EXTENSIONS
2453 if (builtIn == spv::BuiltInLayer) {
2454 // SPV_NV_viewport_array2 extension
2455 if (glslangMember.getQualifier().layoutViewportRelative){
2456 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2457 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2458 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2459 }
2460 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2461 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2462 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2463 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2464 }
2465 }
chaocdf3956c2017-02-14 14:52:34 -08002466 if (glslangMember.getQualifier().layoutPassthrough) {
2467 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2468 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2469 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2470 }
chaoc771d89f2017-01-13 01:10:53 -08002471#endif
John Kessenich6090df02016-06-30 21:18:02 -06002472 }
2473 }
2474
2475 // Decorate the structure
2476 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2477 addDecoration(spvType, TranslateBlockDecoration(type));
2478 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2479 builder.addCapability(spv::CapabilityGeometryStreams);
2480 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2481 }
2482 if (glslangIntermediate->getXfbMode()) {
2483 builder.addCapability(spv::CapabilityTransformFeedback);
2484 if (type.getQualifier().hasXfbStride())
2485 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2486 if (type.getQualifier().hasXfbBuffer())
2487 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2488 }
2489}
2490
John Kessenich6c292d32016-02-15 20:58:50 -07002491// Turn the expression forming the array size into an id.
2492// This is not quite trivial, because of specialization constants.
2493// Sometimes, a raw constant is turned into an Id, and sometimes
2494// a specialization constant expression is.
2495spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2496{
2497 // First, see if this is sized with a node, meaning a specialization constant:
2498 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2499 if (specNode != nullptr) {
2500 builder.clearAccessChain();
2501 specNode->traverse(this);
2502 return accessChainLoad(specNode->getAsTyped()->getType());
2503 }
qining25262b32016-05-06 17:25:16 -04002504
John Kessenich6c292d32016-02-15 20:58:50 -07002505 // Otherwise, need a compile-time (front end) size, get it:
2506 int size = arraySizes.getDimSize(dim);
2507 assert(size > 0);
2508 return builder.makeUintConstant(size);
2509}
2510
John Kessenich103bef92016-02-08 21:38:15 -07002511// Wrap the builder's accessChainLoad to:
2512// - localize handling of RelaxedPrecision
2513// - use the SPIR-V inferred type instead of another conversion of the glslang type
2514// (avoids unnecessary work and possible type punning for structures)
2515// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002516spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2517{
John Kessenich103bef92016-02-08 21:38:15 -07002518 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2519 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2520
2521 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002522 if (type.getBasicType() == glslang::EbtBool) {
2523 if (builder.isScalarType(nominalTypeId)) {
2524 // Conversion for bool
2525 spv::Id boolType = builder.makeBoolType();
2526 if (nominalTypeId != boolType)
2527 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2528 } else if (builder.isVectorType(nominalTypeId)) {
2529 // Conversion for bvec
2530 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2531 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2532 if (nominalTypeId != bvecType)
2533 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2534 }
2535 }
John Kessenich103bef92016-02-08 21:38:15 -07002536
2537 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002538}
2539
Rex Xu27253232016-02-23 17:51:09 +08002540// Wrap the builder's accessChainStore to:
2541// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002542//
2543// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002544void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2545{
2546 // Need to convert to abstract types when necessary
2547 if (type.getBasicType() == glslang::EbtBool) {
2548 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2549
2550 if (builder.isScalarType(nominalTypeId)) {
2551 // Conversion for bool
2552 spv::Id boolType = builder.makeBoolType();
2553 if (nominalTypeId != boolType) {
2554 spv::Id zero = builder.makeUintConstant(0);
2555 spv::Id one = builder.makeUintConstant(1);
2556 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2557 }
2558 } else if (builder.isVectorType(nominalTypeId)) {
2559 // Conversion for bvec
2560 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2561 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2562 if (nominalTypeId != bvecType) {
2563 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2564 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2565 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2566 }
2567 }
2568 }
2569
2570 builder.accessChainStore(rvalue);
2571}
2572
John Kessenich4bf71552016-09-02 11:20:21 -06002573// For storing when types match at the glslang level, but not might match at the
2574// SPIR-V level.
2575//
2576// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002577// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002578// as in a member-decorated way.
2579//
2580// NOTE: This function can handle any store request; if it's not special it
2581// simplifies to a simple OpStore.
2582//
2583// Implicitly uses the existing builder.accessChain as the storage target.
2584void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2585{
John Kessenichb3e24e42016-09-11 12:33:43 -06002586 // we only do the complex path here if it's an aggregate
2587 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002588 accessChainStore(type, rValue);
2589 return;
2590 }
2591
John Kessenichb3e24e42016-09-11 12:33:43 -06002592 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002593 spv::Id rType = builder.getTypeId(rValue);
2594 spv::Id lValue = builder.accessChainGetLValue();
2595 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2596 if (lType == rType) {
2597 accessChainStore(type, rValue);
2598 return;
2599 }
2600
John Kessenichb3e24e42016-09-11 12:33:43 -06002601 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002602 // where the two types were the same type in GLSL. This requires member
2603 // by member copy, recursively.
2604
John Kessenichb3e24e42016-09-11 12:33:43 -06002605 // If an array, copy element by element.
2606 if (type.isArray()) {
2607 glslang::TType glslangElementType(type, 0);
2608 spv::Id elementRType = builder.getContainedTypeId(rType);
2609 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2610 // get the source member
2611 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002612
John Kessenichb3e24e42016-09-11 12:33:43 -06002613 // set up the target storage
2614 builder.clearAccessChain();
2615 builder.setAccessChainLValue(lValue);
2616 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002617
John Kessenichb3e24e42016-09-11 12:33:43 -06002618 // store the member
2619 multiTypeStore(glslangElementType, elementRValue);
2620 }
2621 } else {
2622 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002623
John Kessenichb3e24e42016-09-11 12:33:43 -06002624 // loop over structure members
2625 const glslang::TTypeList& members = *type.getStruct();
2626 for (int m = 0; m < (int)members.size(); ++m) {
2627 const glslang::TType& glslangMemberType = *members[m].type;
2628
2629 // get the source member
2630 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2631 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2632
2633 // set up the target storage
2634 builder.clearAccessChain();
2635 builder.setAccessChainLValue(lValue);
2636 builder.accessChainPush(builder.makeIntConstant(m));
2637
2638 // store the member
2639 multiTypeStore(glslangMemberType, memberRValue);
2640 }
John Kessenich4bf71552016-09-02 11:20:21 -06002641 }
2642}
2643
John Kessenichf85e8062015-12-19 13:57:10 -07002644// Decide whether or not this type should be
2645// decorated with offsets and strides, and if so
2646// whether std140 or std430 rules should be applied.
2647glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002648{
John Kessenichf85e8062015-12-19 13:57:10 -07002649 // has to be a block
2650 if (type.getBasicType() != glslang::EbtBlock)
2651 return glslang::ElpNone;
2652
2653 // has to be a uniform or buffer block
2654 if (type.getQualifier().storage != glslang::EvqUniform &&
2655 type.getQualifier().storage != glslang::EvqBuffer)
2656 return glslang::ElpNone;
2657
2658 // return the layout to use
2659 switch (type.getQualifier().layoutPacking) {
2660 case glslang::ElpStd140:
2661 case glslang::ElpStd430:
2662 return type.getQualifier().layoutPacking;
2663 default:
2664 return glslang::ElpNone;
2665 }
John Kessenich31ed4832015-09-09 17:51:38 -06002666}
2667
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002668// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002669int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002670{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002671 int size;
John Kessenich49987892015-12-29 17:11:44 -07002672 int stride;
2673 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002674
2675 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002676}
2677
John Kessenich49987892015-12-29 17:11:44 -07002678// 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 -07002679// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002680int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002681{
John Kessenich49987892015-12-29 17:11:44 -07002682 glslang::TType elementType;
2683 elementType.shallowCopy(matrixType);
2684 elementType.clearArraySizes();
2685
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002686 int size;
John Kessenich49987892015-12-29 17:11:44 -07002687 int stride;
2688 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2689
2690 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002691}
2692
John Kessenich5e4b1242015-08-06 22:53:06 -06002693// Given a member type of a struct, realign the current offset for it, and compute
2694// the next (not yet aligned) offset for the next member, which will get aligned
2695// on the next call.
2696// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2697// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2698// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002699void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002700 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002701{
2702 // this will get a positive value when deemed necessary
2703 nextOffset = -1;
2704
John Kessenich5e4b1242015-08-06 22:53:06 -06002705 // override anything in currentOffset with user-set offset
2706 if (memberType.getQualifier().hasOffset())
2707 currentOffset = memberType.getQualifier().layoutOffset;
2708
2709 // It could be that current linker usage in glslang updated all the layoutOffset,
2710 // in which case the following code does not matter. But, that's not quite right
2711 // once cross-compilation unit GLSL validation is done, as the original user
2712 // settings are needed in layoutOffset, and then the following will come into play.
2713
John Kessenichf85e8062015-12-19 13:57:10 -07002714 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002715 if (! memberType.getQualifier().hasOffset())
2716 currentOffset = -1;
2717
2718 return;
2719 }
2720
John Kessenichf85e8062015-12-19 13:57:10 -07002721 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002722 if (currentOffset < 0)
2723 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002724
John Kessenich5e4b1242015-08-06 22:53:06 -06002725 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2726 // but possibly not yet correctly aligned.
2727
2728 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002729 int dummyStride;
2730 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002731 glslang::RoundToPow2(currentOffset, memberAlignment);
2732 nextOffset = currentOffset + memberSize;
2733}
2734
David Netoa901ffe2016-06-08 14:11:40 +01002735void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002736{
David Netoa901ffe2016-06-08 14:11:40 +01002737 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2738 switch (glslangBuiltIn)
2739 {
2740 case glslang::EbvClipDistance:
2741 case glslang::EbvCullDistance:
2742 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002743#ifdef NV_EXTENSIONS
2744 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002745 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002746 case glslang::EbvViewportMaskNV:
2747 case glslang::EbvSecondaryPositionNV:
2748 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002749 case glslang::EbvPositionPerViewNV:
2750 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002751#endif
David Netoa901ffe2016-06-08 14:11:40 +01002752 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2753 // Alternately, we could just call this for any glslang built-in, since the
2754 // capability already guards against duplicates.
2755 TranslateBuiltInDecoration(glslangBuiltIn, false);
2756 break;
2757 default:
2758 // Capabilities were already generated when the struct was declared.
2759 break;
2760 }
John Kessenichebb50532016-05-16 19:22:05 -06002761}
2762
John Kessenich6fccb3c2016-09-19 16:01:41 -06002763bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002764{
John Kessenicheee9d532016-09-19 18:09:30 -06002765 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002766}
2767
2768// Make all the functions, skeletally, without actually visiting their bodies.
2769void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2770{
2771 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2772 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002773 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002774 continue;
2775
2776 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002777 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002778 //
qining25262b32016-05-06 17:25:16 -04002779 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002780 // function. What it is an address of varies:
2781 //
John Kessenich4bf71552016-09-02 11:20:21 -06002782 // - "in" parameters not marked as "const" can be written to without modifying the calling
2783 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002784 //
2785 // - "const in" parameters can just be the r-value, as no writes need occur.
2786 //
John Kessenich4bf71552016-09-02 11:20:21 -06002787 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2788 // 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 -06002789
2790 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002791 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002792 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2793
John Kessenich37789792017-03-21 23:56:40 -06002794 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() == glslangIntermediate->implicitThisName;
2795
John Kessenich140f3df2015-06-26 16:58:36 -06002796 for (int p = 0; p < (int)parameters.size(); ++p) {
2797 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2798 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002799 // can we pass by reference?
2800 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002801 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002802 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002803 (p == 0 && implicitThis)) // implicit 'this'
Jason Ekstranded15ef12016-06-08 13:54:48 -07002804 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2805 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002806 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2807 else
John Kessenich4bf71552016-09-02 11:20:21 -06002808 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002809 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002810 paramTypes.push_back(typeId);
2811 }
2812
2813 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002814 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2815 convertGlslangToSpvType(glslFunction->getType()),
2816 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06002817 if (implicitThis)
2818 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06002819
2820 // Track function to emit/call later
2821 functionMap[glslFunction->getName().c_str()] = function;
2822
2823 // Set the parameter id's
2824 for (int p = 0; p < (int)parameters.size(); ++p) {
2825 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2826 // give a name too
2827 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2828 }
2829 }
2830}
2831
2832// Process all the initializers, while skipping the functions and link objects
2833void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2834{
2835 builder.setBuildPoint(shaderEntry->getLastBlock());
2836 for (int i = 0; i < (int)initializers.size(); ++i) {
2837 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2838 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2839
2840 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002841 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002842 initializer->traverse(this);
2843 }
2844 }
2845}
2846
2847// Process all the functions, while skipping initializers.
2848void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2849{
2850 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2851 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002852 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002853 node->traverse(this);
2854 }
2855}
2856
2857void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2858{
qining25262b32016-05-06 17:25:16 -04002859 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002860 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002861 currentFunction = functionMap[node->getName().c_str()];
2862 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002863 builder.setBuildPoint(functionBlock);
2864}
2865
Rex Xu04db3f52015-09-16 11:44:02 +08002866void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002867{
Rex Xufc618912015-09-09 16:42:49 +08002868 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002869
2870 glslang::TSampler sampler = {};
2871 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002872 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002873 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2874 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2875 }
2876
John Kessenich140f3df2015-06-26 16:58:36 -06002877 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2878 builder.clearAccessChain();
2879 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002880
2881 // Special case l-value operands
2882 bool lvalue = false;
2883 switch (node.getOp()) {
2884 case glslang::EOpImageAtomicAdd:
2885 case glslang::EOpImageAtomicMin:
2886 case glslang::EOpImageAtomicMax:
2887 case glslang::EOpImageAtomicAnd:
2888 case glslang::EOpImageAtomicOr:
2889 case glslang::EOpImageAtomicXor:
2890 case glslang::EOpImageAtomicExchange:
2891 case glslang::EOpImageAtomicCompSwap:
2892 if (i == 0)
2893 lvalue = true;
2894 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002895 case glslang::EOpSparseImageLoad:
2896 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2897 lvalue = true;
2898 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002899 case glslang::EOpSparseTexture:
2900 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2901 lvalue = true;
2902 break;
2903 case glslang::EOpSparseTextureClamp:
2904 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2905 lvalue = true;
2906 break;
2907 case glslang::EOpSparseTextureLod:
2908 case glslang::EOpSparseTextureOffset:
2909 if (i == 3)
2910 lvalue = true;
2911 break;
2912 case glslang::EOpSparseTextureFetch:
2913 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2914 lvalue = true;
2915 break;
2916 case glslang::EOpSparseTextureFetchOffset:
2917 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2918 lvalue = true;
2919 break;
2920 case glslang::EOpSparseTextureLodOffset:
2921 case glslang::EOpSparseTextureGrad:
2922 case glslang::EOpSparseTextureOffsetClamp:
2923 if (i == 4)
2924 lvalue = true;
2925 break;
2926 case glslang::EOpSparseTextureGradOffset:
2927 case glslang::EOpSparseTextureGradClamp:
2928 if (i == 5)
2929 lvalue = true;
2930 break;
2931 case glslang::EOpSparseTextureGradOffsetClamp:
2932 if (i == 6)
2933 lvalue = true;
2934 break;
2935 case glslang::EOpSparseTextureGather:
2936 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2937 lvalue = true;
2938 break;
2939 case glslang::EOpSparseTextureGatherOffset:
2940 case glslang::EOpSparseTextureGatherOffsets:
2941 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2942 lvalue = true;
2943 break;
Rex Xufc618912015-09-09 16:42:49 +08002944 default:
2945 break;
2946 }
2947
Rex Xu6b86d492015-09-16 17:48:22 +08002948 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002949 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002950 else
John Kessenich32cfd492016-02-02 12:37:46 -07002951 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002952 }
2953}
2954
John Kessenichfc51d282015-08-19 13:34:18 -06002955void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002956{
John Kessenichfc51d282015-08-19 13:34:18 -06002957 builder.clearAccessChain();
2958 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002959 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002960}
John Kessenich140f3df2015-06-26 16:58:36 -06002961
John Kessenichfc51d282015-08-19 13:34:18 -06002962spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2963{
Rex Xufc618912015-09-09 16:42:49 +08002964 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002965 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002966 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002967 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002968
John Kessenichfc51d282015-08-19 13:34:18 -06002969 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002970 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2971 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2972 std::vector<spv::Id> arguments;
2973 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002974 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002975 else
2976 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002977 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002978
2979 spv::Builder::TextureParameters params = { };
2980 params.sampler = arguments[0];
2981
Rex Xu04db3f52015-09-16 11:44:02 +08002982 glslang::TCrackedTextureOp cracked;
2983 node->crackTexture(sampler, cracked);
2984
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002985 const bool isUnsignedResult =
2986 node->getType().getBasicType() == glslang::EbtUint64 ||
2987 node->getType().getBasicType() == glslang::EbtUint;
2988
John Kessenichfc51d282015-08-19 13:34:18 -06002989 // Check for queries
2990 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002991 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
2992 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07002993 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002994
John Kessenichfc51d282015-08-19 13:34:18 -06002995 switch (node->getOp()) {
2996 case glslang::EOpImageQuerySize:
2997 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002998 if (arguments.size() > 1) {
2999 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003000 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003001 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003002 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003003 case glslang::EOpImageQuerySamples:
3004 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003005 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003006 case glslang::EOpTextureQueryLod:
3007 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003008 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003009 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003010 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003011 case glslang::EOpSparseTexelsResident:
3012 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003013 default:
3014 assert(0);
3015 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003016 }
John Kessenich140f3df2015-06-26 16:58:36 -06003017 }
3018
Rex Xufc618912015-09-09 16:42:49 +08003019 // Check for image functions other than queries
3020 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003021 std::vector<spv::Id> operands;
3022 auto opIt = arguments.begin();
3023 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003024
3025 // Handle subpass operations
3026 // TODO: GLSL should change to have the "MS" only on the type rather than the
3027 // built-in function.
3028 if (cracked.subpass) {
3029 // add on the (0,0) coordinate
3030 spv::Id zero = builder.makeIntConstant(0);
3031 std::vector<spv::Id> comps;
3032 comps.push_back(zero);
3033 comps.push_back(zero);
3034 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3035 if (sampler.ms) {
3036 operands.push_back(spv::ImageOperandsSampleMask);
3037 operands.push_back(*(opIt++));
3038 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003039 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003040 }
3041
John Kessenich56bab042015-09-16 10:54:31 -06003042 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003043 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003044 if (sampler.ms) {
3045 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003046 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003047 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003048 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3049 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003050 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003051 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003052 if (sampler.ms) {
3053 operands.push_back(*(opIt + 1));
3054 operands.push_back(spv::ImageOperandsSampleMask);
3055 operands.push_back(*opIt);
3056 } else
3057 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003058 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003059 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3060 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003061 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003062 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3063 builder.addCapability(spv::CapabilitySparseResidency);
3064 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3065 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3066
3067 if (sampler.ms) {
3068 operands.push_back(spv::ImageOperandsSampleMask);
3069 operands.push_back(*opIt++);
3070 }
3071
3072 // Create the return type that was a special structure
3073 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003074 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003075 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3076 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3077
3078 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3079
3080 // Decode the return type
3081 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3082 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003083 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003084 // Process image atomic operations
3085
3086 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3087 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003088 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003089
John Kessenich8c8505c2016-07-26 12:50:38 -06003090 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003091 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003092
3093 std::vector<spv::Id> operands;
3094 operands.push_back(pointer);
3095 for (; opIt != arguments.end(); ++opIt)
3096 operands.push_back(*opIt);
3097
John Kessenich8c8505c2016-07-26 12:50:38 -06003098 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003099 }
3100 }
3101
3102 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003103 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003104 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3105
John Kessenichfc51d282015-08-19 13:34:18 -06003106 // check for bias argument
3107 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003108 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003109 int nonBiasArgCount = 2;
3110 if (cracked.offset)
3111 ++nonBiasArgCount;
3112 if (cracked.grad)
3113 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003114 if (cracked.lodClamp)
3115 ++nonBiasArgCount;
3116 if (sparse)
3117 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003118
3119 if ((int)arguments.size() > nonBiasArgCount)
3120 bias = true;
3121 }
3122
John Kessenicha5c33d62016-06-02 23:45:21 -06003123 // See if the sampler param should really be just the SPV image part
3124 if (cracked.fetch) {
3125 // a fetch needs to have the image extracted first
3126 if (builder.isSampledImage(params.sampler))
3127 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3128 }
3129
John Kessenichfc51d282015-08-19 13:34:18 -06003130 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003131
John Kessenichfc51d282015-08-19 13:34:18 -06003132 params.coords = arguments[1];
3133 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003134 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003135
3136 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003137 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003138 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003139 ++extraArgs;
3140 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003141 params.Dref = arguments[2];
3142 ++extraArgs;
3143 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003144 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003145 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003146 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003147 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003148 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003149 dRefComp = builder.getNumComponents(params.coords) - 1;
3150 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003151 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3152 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003153
3154 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003155 if (cracked.lod) {
3156 params.lod = arguments[2];
3157 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003158 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3159 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3160 noImplicitLod = true;
3161 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003162
3163 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003164 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003165 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003166 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003167 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003168
3169 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003170 if (cracked.grad) {
3171 params.gradX = arguments[2 + extraArgs];
3172 params.gradY = arguments[3 + extraArgs];
3173 extraArgs += 2;
3174 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003175
3176 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003177 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003178 params.offset = arguments[2 + extraArgs];
3179 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003180 } else if (cracked.offsets) {
3181 params.offsets = arguments[2 + extraArgs];
3182 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003183 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003184
3185 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003186 if (cracked.lodClamp) {
3187 params.lodClamp = arguments[2 + extraArgs];
3188 ++extraArgs;
3189 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003190
3191 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003192 if (sparse) {
3193 params.texelOut = arguments[2 + extraArgs];
3194 ++extraArgs;
3195 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003196
3197 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003198 if (bias) {
3199 params.bias = arguments[2 + extraArgs];
3200 ++extraArgs;
3201 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003202
3203 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003204 if (cracked.gather && ! sampler.shadow) {
3205 // default component is 0, if missing, otherwise an argument
3206 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003207 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003208 ++extraArgs;
3209 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003210 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003211 }
3212 }
John Kessenichfc51d282015-08-19 13:34:18 -06003213
John Kessenich65336482016-06-16 14:06:26 -06003214 // projective component (might not to move)
3215 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3216 // are divided by the last component of P."
3217 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3218 // unused components will appear after all used components."
3219 if (cracked.proj) {
3220 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3221 int projTargetComp;
3222 switch (sampler.dim) {
3223 case glslang::Esd1D: projTargetComp = 1; break;
3224 case glslang::Esd2D: projTargetComp = 2; break;
3225 case glslang::EsdRect: projTargetComp = 2; break;
3226 default: projTargetComp = projSourceComp; break;
3227 }
3228 // copy the projective coordinate if we have to
3229 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003230 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003231 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3232 projSourceComp);
3233 params.coords = builder.createCompositeInsert(projComp, params.coords,
3234 builder.getTypeId(params.coords), projTargetComp);
3235 }
3236 }
3237
John Kessenich8c8505c2016-07-26 12:50:38 -06003238 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003239}
3240
3241spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3242{
3243 // Grab the function's pointer from the previously created function
3244 spv::Function* function = functionMap[node->getName().c_str()];
3245 if (! function)
3246 return 0;
3247
3248 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3249 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3250
3251 // See comments in makeFunctions() for details about the semantics for parameter passing.
3252 //
3253 // These imply we need a four step process:
3254 // 1. Evaluate the arguments
3255 // 2. Allocate and make copies of in, out, and inout arguments
3256 // 3. Make the call
3257 // 4. Copy back the results
3258
3259 // 1. Evaluate the arguments
3260 std::vector<spv::Builder::AccessChain> lValues;
3261 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003262 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003263 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 // build l-value
3266 builder.clearAccessChain();
3267 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003268 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003269 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003270 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003271 // save l-value
3272 lValues.push_back(builder.getAccessChain());
3273 } else {
3274 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003275 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003276 }
3277 }
3278
3279 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3280 // copy the original into that space.
3281 //
3282 // Also, build up the list of actual arguments to pass in for the call
3283 int lValueCount = 0;
3284 int rValueCount = 0;
3285 std::vector<spv::Id> spvArgs;
3286 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003287 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003288 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003289 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003290 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3291 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003292 builder.setAccessChain(lValues[lValueCount]);
3293 arg = builder.accessChainGetLValue();
3294 ++lValueCount;
3295 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003296 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003297 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3298 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3299 // need to copy the input into output space
3300 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003301 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003302 builder.clearAccessChain();
3303 builder.setAccessChainLValue(arg);
3304 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003305 }
3306 ++lValueCount;
3307 } else {
3308 arg = rValues[rValueCount];
3309 ++rValueCount;
3310 }
3311 spvArgs.push_back(arg);
3312 }
3313
3314 // 3. Make the call.
3315 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003316 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003317
3318 // 4. Copy back out an "out" arguments.
3319 lValueCount = 0;
3320 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003321 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003322 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3323 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3324 spv::Id copy = builder.createLoad(spvArgs[a]);
3325 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003326 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003327 }
3328 ++lValueCount;
3329 }
3330 }
3331
3332 return result;
3333}
3334
3335// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003336spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3337 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003338 spv::Id typeId, spv::Id left, spv::Id right,
3339 glslang::TBasicType typeProxy, bool reduceComparison)
3340{
Rex Xu8ff43de2016-04-22 16:51:45 +08003341 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003342#ifdef AMD_EXTENSIONS
3343 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3344#else
John Kessenich140f3df2015-06-26 16:58:36 -06003345 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003346#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003347 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003348
3349 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003350 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003351 bool comparison = false;
3352
3353 switch (op) {
3354 case glslang::EOpAdd:
3355 case glslang::EOpAddAssign:
3356 if (isFloat)
3357 binOp = spv::OpFAdd;
3358 else
3359 binOp = spv::OpIAdd;
3360 break;
3361 case glslang::EOpSub:
3362 case glslang::EOpSubAssign:
3363 if (isFloat)
3364 binOp = spv::OpFSub;
3365 else
3366 binOp = spv::OpISub;
3367 break;
3368 case glslang::EOpMul:
3369 case glslang::EOpMulAssign:
3370 if (isFloat)
3371 binOp = spv::OpFMul;
3372 else
3373 binOp = spv::OpIMul;
3374 break;
3375 case glslang::EOpVectorTimesScalar:
3376 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003377 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003378 if (builder.isVector(right))
3379 std::swap(left, right);
3380 assert(builder.isScalar(right));
3381 needMatchingVectors = false;
3382 binOp = spv::OpVectorTimesScalar;
3383 } else
3384 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003385 break;
3386 case glslang::EOpVectorTimesMatrix:
3387 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003388 binOp = spv::OpVectorTimesMatrix;
3389 break;
3390 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003391 binOp = spv::OpMatrixTimesVector;
3392 break;
3393 case glslang::EOpMatrixTimesScalar:
3394 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003395 binOp = spv::OpMatrixTimesScalar;
3396 break;
3397 case glslang::EOpMatrixTimesMatrix:
3398 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003399 binOp = spv::OpMatrixTimesMatrix;
3400 break;
3401 case glslang::EOpOuterProduct:
3402 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003403 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003404 break;
3405
3406 case glslang::EOpDiv:
3407 case glslang::EOpDivAssign:
3408 if (isFloat)
3409 binOp = spv::OpFDiv;
3410 else if (isUnsigned)
3411 binOp = spv::OpUDiv;
3412 else
3413 binOp = spv::OpSDiv;
3414 break;
3415 case glslang::EOpMod:
3416 case glslang::EOpModAssign:
3417 if (isFloat)
3418 binOp = spv::OpFMod;
3419 else if (isUnsigned)
3420 binOp = spv::OpUMod;
3421 else
3422 binOp = spv::OpSMod;
3423 break;
3424 case glslang::EOpRightShift:
3425 case glslang::EOpRightShiftAssign:
3426 if (isUnsigned)
3427 binOp = spv::OpShiftRightLogical;
3428 else
3429 binOp = spv::OpShiftRightArithmetic;
3430 break;
3431 case glslang::EOpLeftShift:
3432 case glslang::EOpLeftShiftAssign:
3433 binOp = spv::OpShiftLeftLogical;
3434 break;
3435 case glslang::EOpAnd:
3436 case glslang::EOpAndAssign:
3437 binOp = spv::OpBitwiseAnd;
3438 break;
3439 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003440 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003441 binOp = spv::OpLogicalAnd;
3442 break;
3443 case glslang::EOpInclusiveOr:
3444 case glslang::EOpInclusiveOrAssign:
3445 binOp = spv::OpBitwiseOr;
3446 break;
3447 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003448 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003449 binOp = spv::OpLogicalOr;
3450 break;
3451 case glslang::EOpExclusiveOr:
3452 case glslang::EOpExclusiveOrAssign:
3453 binOp = spv::OpBitwiseXor;
3454 break;
3455 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003456 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003457 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003458 break;
3459
3460 case glslang::EOpLessThan:
3461 case glslang::EOpGreaterThan:
3462 case glslang::EOpLessThanEqual:
3463 case glslang::EOpGreaterThanEqual:
3464 case glslang::EOpEqual:
3465 case glslang::EOpNotEqual:
3466 case glslang::EOpVectorEqual:
3467 case glslang::EOpVectorNotEqual:
3468 comparison = true;
3469 break;
3470 default:
3471 break;
3472 }
3473
John Kessenich7c1aa102015-10-15 13:29:11 -06003474 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003475 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003476 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003477 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003478 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003479
3480 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003481 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003482 builder.promoteScalar(precision, left, right);
3483
qining25262b32016-05-06 17:25:16 -04003484 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3485 addDecoration(result, noContraction);
3486 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003487 }
3488
3489 if (! comparison)
3490 return 0;
3491
John Kessenich7c1aa102015-10-15 13:29:11 -06003492 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003493
John Kessenich4583b612016-08-07 19:14:22 -06003494 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3495 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003496 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003497
3498 switch (op) {
3499 case glslang::EOpLessThan:
3500 if (isFloat)
3501 binOp = spv::OpFOrdLessThan;
3502 else if (isUnsigned)
3503 binOp = spv::OpULessThan;
3504 else
3505 binOp = spv::OpSLessThan;
3506 break;
3507 case glslang::EOpGreaterThan:
3508 if (isFloat)
3509 binOp = spv::OpFOrdGreaterThan;
3510 else if (isUnsigned)
3511 binOp = spv::OpUGreaterThan;
3512 else
3513 binOp = spv::OpSGreaterThan;
3514 break;
3515 case glslang::EOpLessThanEqual:
3516 if (isFloat)
3517 binOp = spv::OpFOrdLessThanEqual;
3518 else if (isUnsigned)
3519 binOp = spv::OpULessThanEqual;
3520 else
3521 binOp = spv::OpSLessThanEqual;
3522 break;
3523 case glslang::EOpGreaterThanEqual:
3524 if (isFloat)
3525 binOp = spv::OpFOrdGreaterThanEqual;
3526 else if (isUnsigned)
3527 binOp = spv::OpUGreaterThanEqual;
3528 else
3529 binOp = spv::OpSGreaterThanEqual;
3530 break;
3531 case glslang::EOpEqual:
3532 case glslang::EOpVectorEqual:
3533 if (isFloat)
3534 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003535 else if (isBool)
3536 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003537 else
3538 binOp = spv::OpIEqual;
3539 break;
3540 case glslang::EOpNotEqual:
3541 case glslang::EOpVectorNotEqual:
3542 if (isFloat)
3543 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003544 else if (isBool)
3545 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003546 else
3547 binOp = spv::OpINotEqual;
3548 break;
3549 default:
3550 break;
3551 }
3552
qining25262b32016-05-06 17:25:16 -04003553 if (binOp != spv::OpNop) {
3554 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3555 addDecoration(result, noContraction);
3556 return builder.setPrecision(result, precision);
3557 }
John Kessenich140f3df2015-06-26 16:58:36 -06003558
3559 return 0;
3560}
3561
John Kessenich04bb8a02015-12-12 12:28:14 -07003562//
3563// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3564// These can be any of:
3565//
3566// matrix * scalar
3567// scalar * matrix
3568// matrix * matrix linear algebraic
3569// matrix * vector
3570// vector * matrix
3571// matrix * matrix componentwise
3572// matrix op matrix op in {+, -, /}
3573// matrix op scalar op in {+, -, /}
3574// scalar op matrix op in {+, -, /}
3575//
qining25262b32016-05-06 17:25:16 -04003576spv::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 -07003577{
3578 bool firstClass = true;
3579
3580 // First, handle first-class matrix operations (* and matrix/scalar)
3581 switch (op) {
3582 case spv::OpFDiv:
3583 if (builder.isMatrix(left) && builder.isScalar(right)) {
3584 // turn matrix / scalar into a multiply...
3585 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3586 op = spv::OpMatrixTimesScalar;
3587 } else
3588 firstClass = false;
3589 break;
3590 case spv::OpMatrixTimesScalar:
3591 if (builder.isMatrix(right))
3592 std::swap(left, right);
3593 assert(builder.isScalar(right));
3594 break;
3595 case spv::OpVectorTimesMatrix:
3596 assert(builder.isVector(left));
3597 assert(builder.isMatrix(right));
3598 break;
3599 case spv::OpMatrixTimesVector:
3600 assert(builder.isMatrix(left));
3601 assert(builder.isVector(right));
3602 break;
3603 case spv::OpMatrixTimesMatrix:
3604 assert(builder.isMatrix(left));
3605 assert(builder.isMatrix(right));
3606 break;
3607 default:
3608 firstClass = false;
3609 break;
3610 }
3611
qining25262b32016-05-06 17:25:16 -04003612 if (firstClass) {
3613 spv::Id result = builder.createBinOp(op, typeId, left, right);
3614 addDecoration(result, noContraction);
3615 return builder.setPrecision(result, precision);
3616 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003617
LoopDawg592860c2016-06-09 08:57:35 -06003618 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003619 // The result type of all of them is the same type as the (a) matrix operand.
3620 // The algorithm is to:
3621 // - break the matrix(es) into vectors
3622 // - smear any scalar to a vector
3623 // - do vector operations
3624 // - make a matrix out the vector results
3625 switch (op) {
3626 case spv::OpFAdd:
3627 case spv::OpFSub:
3628 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003629 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003630 case spv::OpFMul:
3631 {
3632 // one time set up...
3633 bool leftMat = builder.isMatrix(left);
3634 bool rightMat = builder.isMatrix(right);
3635 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3636 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3637 spv::Id scalarType = builder.getScalarTypeId(typeId);
3638 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3639 std::vector<spv::Id> results;
3640 spv::Id smearVec = spv::NoResult;
3641 if (builder.isScalar(left))
3642 smearVec = builder.smearScalar(precision, left, vecType);
3643 else if (builder.isScalar(right))
3644 smearVec = builder.smearScalar(precision, right, vecType);
3645
3646 // do each vector op
3647 for (unsigned int c = 0; c < numCols; ++c) {
3648 std::vector<unsigned int> indexes;
3649 indexes.push_back(c);
3650 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3651 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003652 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3653 addDecoration(result, noContraction);
3654 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003655 }
3656
3657 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003658 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003659 }
3660 default:
3661 assert(0);
3662 return spv::NoResult;
3663 }
3664}
3665
qining25262b32016-05-06 17:25:16 -04003666spv::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 -06003667{
3668 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003669 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003670 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003671 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003672#ifdef AMD_EXTENSIONS
3673 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3674#else
Rex Xu04db3f52015-09-16 11:44:02 +08003675 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003676#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003677
3678 switch (op) {
3679 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003680 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003681 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003682 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003683 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003684 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003685 unaryOp = spv::OpSNegate;
3686 break;
3687
3688 case glslang::EOpLogicalNot:
3689 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003690 unaryOp = spv::OpLogicalNot;
3691 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003692 case glslang::EOpBitwiseNot:
3693 unaryOp = spv::OpNot;
3694 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003695
John Kessenich140f3df2015-06-26 16:58:36 -06003696 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003697 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003698 break;
3699 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003700 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003701 break;
3702 case glslang::EOpTranspose:
3703 unaryOp = spv::OpTranspose;
3704 break;
3705
3706 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003707 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003708 break;
3709 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003710 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003711 break;
3712 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003713 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003714 break;
3715 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003716 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003717 break;
3718 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003719 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003720 break;
3721 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003722 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003723 break;
3724 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003725 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003726 break;
3727 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003728 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003729 break;
3730
3731 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003732 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003733 break;
3734 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003735 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003736 break;
3737 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003738 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003739 break;
3740 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003741 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003742 break;
3743 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003744 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003745 break;
3746 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003747 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003748 break;
3749
3750 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003751 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003752 break;
3753 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003754 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003755 break;
3756
3757 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003758 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003759 break;
3760 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003761 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003762 break;
3763 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003764 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003765 break;
3766 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003767 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003768 break;
3769 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003770 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003771 break;
3772 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003773 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003774 break;
3775
3776 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003777 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003778 break;
3779 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003780 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003781 break;
3782 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003783 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003784 break;
3785 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003786 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003787 break;
3788 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003789 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003790 break;
3791 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003792 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003793 break;
3794
3795 case glslang::EOpIsNan:
3796 unaryOp = spv::OpIsNan;
3797 break;
3798 case glslang::EOpIsInf:
3799 unaryOp = spv::OpIsInf;
3800 break;
LoopDawg592860c2016-06-09 08:57:35 -06003801 case glslang::EOpIsFinite:
3802 unaryOp = spv::OpIsFinite;
3803 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003804
Rex Xucbc426e2015-12-15 16:03:10 +08003805 case glslang::EOpFloatBitsToInt:
3806 case glslang::EOpFloatBitsToUint:
3807 case glslang::EOpIntBitsToFloat:
3808 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003809 case glslang::EOpDoubleBitsToInt64:
3810 case glslang::EOpDoubleBitsToUint64:
3811 case glslang::EOpInt64BitsToDouble:
3812 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003813 unaryOp = spv::OpBitcast;
3814 break;
3815
John Kessenich140f3df2015-06-26 16:58:36 -06003816 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003817 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003818 break;
3819 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003820 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003821 break;
3822 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003823 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003824 break;
3825 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003826 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003827 break;
3828 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003829 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003830 break;
3831 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003832 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003833 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003834 case glslang::EOpPackSnorm4x8:
3835 libCall = spv::GLSLstd450PackSnorm4x8;
3836 break;
3837 case glslang::EOpUnpackSnorm4x8:
3838 libCall = spv::GLSLstd450UnpackSnorm4x8;
3839 break;
3840 case glslang::EOpPackUnorm4x8:
3841 libCall = spv::GLSLstd450PackUnorm4x8;
3842 break;
3843 case glslang::EOpUnpackUnorm4x8:
3844 libCall = spv::GLSLstd450UnpackUnorm4x8;
3845 break;
3846 case glslang::EOpPackDouble2x32:
3847 libCall = spv::GLSLstd450PackDouble2x32;
3848 break;
3849 case glslang::EOpUnpackDouble2x32:
3850 libCall = spv::GLSLstd450UnpackDouble2x32;
3851 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003852
Rex Xu8ff43de2016-04-22 16:51:45 +08003853 case glslang::EOpPackInt2x32:
3854 case glslang::EOpUnpackInt2x32:
3855 case glslang::EOpPackUint2x32:
3856 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003857 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003858 break;
3859
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003860#ifdef AMD_EXTENSIONS
3861 case glslang::EOpPackFloat2x16:
3862 case glslang::EOpUnpackFloat2x16:
3863 unaryOp = spv::OpBitcast;
3864 break;
3865#endif
3866
John Kessenich140f3df2015-06-26 16:58:36 -06003867 case glslang::EOpDPdx:
3868 unaryOp = spv::OpDPdx;
3869 break;
3870 case glslang::EOpDPdy:
3871 unaryOp = spv::OpDPdy;
3872 break;
3873 case glslang::EOpFwidth:
3874 unaryOp = spv::OpFwidth;
3875 break;
3876 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003877 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003878 unaryOp = spv::OpDPdxFine;
3879 break;
3880 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003881 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003882 unaryOp = spv::OpDPdyFine;
3883 break;
3884 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003885 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003886 unaryOp = spv::OpFwidthFine;
3887 break;
3888 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003889 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003890 unaryOp = spv::OpDPdxCoarse;
3891 break;
3892 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003893 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003894 unaryOp = spv::OpDPdyCoarse;
3895 break;
3896 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003897 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003898 unaryOp = spv::OpFwidthCoarse;
3899 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003900 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003901 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003902 libCall = spv::GLSLstd450InterpolateAtCentroid;
3903 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003904 case glslang::EOpAny:
3905 unaryOp = spv::OpAny;
3906 break;
3907 case glslang::EOpAll:
3908 unaryOp = spv::OpAll;
3909 break;
3910
3911 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003912 if (isFloat)
3913 libCall = spv::GLSLstd450FAbs;
3914 else
3915 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003916 break;
3917 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003918 if (isFloat)
3919 libCall = spv::GLSLstd450FSign;
3920 else
3921 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003922 break;
3923
John Kessenichfc51d282015-08-19 13:34:18 -06003924 case glslang::EOpAtomicCounterIncrement:
3925 case glslang::EOpAtomicCounterDecrement:
3926 case glslang::EOpAtomicCounter:
3927 {
3928 // Handle all of the atomics in one place, in createAtomicOperation()
3929 std::vector<spv::Id> operands;
3930 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003931 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003932 }
3933
John Kessenichfc51d282015-08-19 13:34:18 -06003934 case glslang::EOpBitFieldReverse:
3935 unaryOp = spv::OpBitReverse;
3936 break;
3937 case glslang::EOpBitCount:
3938 unaryOp = spv::OpBitCount;
3939 break;
3940 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003941 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003942 break;
3943 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003944 if (isUnsigned)
3945 libCall = spv::GLSLstd450FindUMsb;
3946 else
3947 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003948 break;
3949
Rex Xu574ab042016-04-14 16:53:07 +08003950 case glslang::EOpBallot:
3951 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003952 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003953 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003954 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003955#ifdef AMD_EXTENSIONS
3956 case glslang::EOpMinInvocations:
3957 case glslang::EOpMaxInvocations:
3958 case glslang::EOpAddInvocations:
3959 case glslang::EOpMinInvocationsNonUniform:
3960 case glslang::EOpMaxInvocationsNonUniform:
3961 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08003962 case glslang::EOpMinInvocationsInclusiveScan:
3963 case glslang::EOpMaxInvocationsInclusiveScan:
3964 case glslang::EOpAddInvocationsInclusiveScan:
3965 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
3966 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
3967 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
3968 case glslang::EOpMinInvocationsExclusiveScan:
3969 case glslang::EOpMaxInvocationsExclusiveScan:
3970 case glslang::EOpAddInvocationsExclusiveScan:
3971 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
3972 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
3973 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08003974#endif
Rex Xu51596642016-09-21 18:56:12 +08003975 {
3976 std::vector<spv::Id> operands;
3977 operands.push_back(operand);
3978 return createInvocationsOperation(op, typeId, operands, typeProxy);
3979 }
Rex Xu9d93a232016-05-05 12:30:44 +08003980
3981#ifdef AMD_EXTENSIONS
3982 case glslang::EOpMbcnt:
3983 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3984 libCall = spv::MbcntAMD;
3985 break;
3986
3987 case glslang::EOpCubeFaceIndex:
3988 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3989 libCall = spv::CubeFaceIndexAMD;
3990 break;
3991
3992 case glslang::EOpCubeFaceCoord:
3993 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3994 libCall = spv::CubeFaceCoordAMD;
3995 break;
3996#endif
Rex Xu338b1852016-05-05 20:38:33 +08003997
John Kessenich140f3df2015-06-26 16:58:36 -06003998 default:
3999 return 0;
4000 }
4001
4002 spv::Id id;
4003 if (libCall >= 0) {
4004 std::vector<spv::Id> args;
4005 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004006 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004007 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004008 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004009 }
John Kessenich140f3df2015-06-26 16:58:36 -06004010
qining25262b32016-05-06 17:25:16 -04004011 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004012 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004013}
4014
John Kessenich7a53f762016-01-20 11:19:27 -07004015// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004016spv::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 -07004017{
4018 // Handle unary operations vector by vector.
4019 // The result type is the same type as the original type.
4020 // The algorithm is to:
4021 // - break the matrix into vectors
4022 // - apply the operation to each vector
4023 // - make a matrix out the vector results
4024
4025 // get the types sorted out
4026 int numCols = builder.getNumColumns(operand);
4027 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004028 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4029 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004030 std::vector<spv::Id> results;
4031
4032 // do each vector op
4033 for (int c = 0; c < numCols; ++c) {
4034 std::vector<unsigned int> indexes;
4035 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004036 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4037 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4038 addDecoration(destVec, noContraction);
4039 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004040 }
4041
4042 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004043 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004044}
4045
Rex Xu73e3ce72016-04-27 18:48:17 +08004046spv::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 -06004047{
4048 spv::Op convOp = spv::OpNop;
4049 spv::Id zero = 0;
4050 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004051 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004052
4053 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4054
4055 switch (op) {
4056 case glslang::EOpConvIntToBool:
4057 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004058 case glslang::EOpConvInt64ToBool:
4059 case glslang::EOpConvUint64ToBool:
4060 zero = (op == glslang::EOpConvInt64ToBool ||
4061 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004062 zero = makeSmearedConstant(zero, vectorSize);
4063 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4064
4065 case glslang::EOpConvFloatToBool:
4066 zero = builder.makeFloatConstant(0.0F);
4067 zero = makeSmearedConstant(zero, vectorSize);
4068 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4069
4070 case glslang::EOpConvDoubleToBool:
4071 zero = builder.makeDoubleConstant(0.0);
4072 zero = makeSmearedConstant(zero, vectorSize);
4073 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4074
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004075#ifdef AMD_EXTENSIONS
4076 case glslang::EOpConvFloat16ToBool:
4077 zero = builder.makeFloat16Constant(0.0F);
4078 zero = makeSmearedConstant(zero, vectorSize);
4079 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4080#endif
4081
John Kessenich140f3df2015-06-26 16:58:36 -06004082 case glslang::EOpConvBoolToFloat:
4083 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004084 zero = builder.makeFloatConstant(0.0F);
4085 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004086 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004087
John Kessenich140f3df2015-06-26 16:58:36 -06004088 case glslang::EOpConvBoolToDouble:
4089 convOp = spv::OpSelect;
4090 zero = builder.makeDoubleConstant(0.0);
4091 one = builder.makeDoubleConstant(1.0);
4092 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004093
4094#ifdef AMD_EXTENSIONS
4095 case glslang::EOpConvBoolToFloat16:
4096 convOp = spv::OpSelect;
4097 zero = builder.makeFloat16Constant(0.0F);
4098 one = builder.makeFloat16Constant(1.0F);
4099 break;
4100#endif
4101
John Kessenich140f3df2015-06-26 16:58:36 -06004102 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004103 case glslang::EOpConvBoolToInt64:
4104 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4105 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004106 convOp = spv::OpSelect;
4107 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004108
John Kessenich140f3df2015-06-26 16:58:36 -06004109 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004110 case glslang::EOpConvBoolToUint64:
4111 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4112 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004113 convOp = spv::OpSelect;
4114 break;
4115
4116 case glslang::EOpConvIntToFloat:
4117 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004118 case glslang::EOpConvInt64ToFloat:
4119 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004120#ifdef AMD_EXTENSIONS
4121 case glslang::EOpConvIntToFloat16:
4122 case glslang::EOpConvInt64ToFloat16:
4123#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004124 convOp = spv::OpConvertSToF;
4125 break;
4126
4127 case glslang::EOpConvUintToFloat:
4128 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004129 case glslang::EOpConvUint64ToFloat:
4130 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004131#ifdef AMD_EXTENSIONS
4132 case glslang::EOpConvUintToFloat16:
4133 case glslang::EOpConvUint64ToFloat16:
4134#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004135 convOp = spv::OpConvertUToF;
4136 break;
4137
4138 case glslang::EOpConvDoubleToFloat:
4139 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004140#ifdef AMD_EXTENSIONS
4141 case glslang::EOpConvDoubleToFloat16:
4142 case glslang::EOpConvFloat16ToDouble:
4143 case glslang::EOpConvFloatToFloat16:
4144 case glslang::EOpConvFloat16ToFloat:
4145#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004146 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004147 if (builder.isMatrixType(destType))
4148 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004149 break;
4150
4151 case glslang::EOpConvFloatToInt:
4152 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004153 case glslang::EOpConvFloatToInt64:
4154 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004155#ifdef AMD_EXTENSIONS
4156 case glslang::EOpConvFloat16ToInt:
4157 case glslang::EOpConvFloat16ToInt64:
4158#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004159 convOp = spv::OpConvertFToS;
4160 break;
4161
4162 case glslang::EOpConvUintToInt:
4163 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004164 case glslang::EOpConvUint64ToInt64:
4165 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004166 if (builder.isInSpecConstCodeGenMode()) {
4167 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004168 zero = (op == glslang::EOpConvUint64ToInt64 ||
4169 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004170 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004171 // Use OpIAdd, instead of OpBitcast to do the conversion when
4172 // generating for OpSpecConstantOp instruction.
4173 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4174 }
4175 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004176 convOp = spv::OpBitcast;
4177 break;
4178
4179 case glslang::EOpConvFloatToUint:
4180 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004181 case glslang::EOpConvFloatToUint64:
4182 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004183#ifdef AMD_EXTENSIONS
4184 case glslang::EOpConvFloat16ToUint:
4185 case glslang::EOpConvFloat16ToUint64:
4186#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004187 convOp = spv::OpConvertFToU;
4188 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004189
4190 case glslang::EOpConvIntToInt64:
4191 case glslang::EOpConvInt64ToInt:
4192 convOp = spv::OpSConvert;
4193 break;
4194
4195 case glslang::EOpConvUintToUint64:
4196 case glslang::EOpConvUint64ToUint:
4197 convOp = spv::OpUConvert;
4198 break;
4199
4200 case glslang::EOpConvIntToUint64:
4201 case glslang::EOpConvInt64ToUint:
4202 case glslang::EOpConvUint64ToInt:
4203 case glslang::EOpConvUintToInt64:
4204 // OpSConvert/OpUConvert + OpBitCast
4205 switch (op) {
4206 case glslang::EOpConvIntToUint64:
4207 convOp = spv::OpSConvert;
4208 type = builder.makeIntType(64);
4209 break;
4210 case glslang::EOpConvInt64ToUint:
4211 convOp = spv::OpSConvert;
4212 type = builder.makeIntType(32);
4213 break;
4214 case glslang::EOpConvUint64ToInt:
4215 convOp = spv::OpUConvert;
4216 type = builder.makeUintType(32);
4217 break;
4218 case glslang::EOpConvUintToInt64:
4219 convOp = spv::OpUConvert;
4220 type = builder.makeUintType(64);
4221 break;
4222 default:
4223 assert(0);
4224 break;
4225 }
4226
4227 if (vectorSize > 0)
4228 type = builder.makeVectorType(type, vectorSize);
4229
4230 operand = builder.createUnaryOp(convOp, type, operand);
4231
4232 if (builder.isInSpecConstCodeGenMode()) {
4233 // Build zero scalar or vector for OpIAdd.
4234 zero = (op == glslang::EOpConvIntToUint64 ||
4235 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4236 zero = makeSmearedConstant(zero, vectorSize);
4237 // Use OpIAdd, instead of OpBitcast to do the conversion when
4238 // generating for OpSpecConstantOp instruction.
4239 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4240 }
4241 // For normal run-time conversion instruction, use OpBitcast.
4242 convOp = spv::OpBitcast;
4243 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004244 default:
4245 break;
4246 }
4247
4248 spv::Id result = 0;
4249 if (convOp == spv::OpNop)
4250 return result;
4251
4252 if (convOp == spv::OpSelect) {
4253 zero = makeSmearedConstant(zero, vectorSize);
4254 one = makeSmearedConstant(one, vectorSize);
4255 result = builder.createTriOp(convOp, destType, operand, one, zero);
4256 } else
4257 result = builder.createUnaryOp(convOp, destType, operand);
4258
John Kessenich32cfd492016-02-02 12:37:46 -07004259 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004260}
4261
4262spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4263{
4264 if (vectorSize == 0)
4265 return constant;
4266
4267 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4268 std::vector<spv::Id> components;
4269 for (int c = 0; c < vectorSize; ++c)
4270 components.push_back(constant);
4271 return builder.makeCompositeConstant(vectorTypeId, components);
4272}
4273
John Kessenich426394d2015-07-23 10:22:48 -06004274// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004275spv::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 -06004276{
4277 spv::Op opCode = spv::OpNop;
4278
4279 switch (op) {
4280 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004281 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004282 opCode = spv::OpAtomicIAdd;
4283 break;
4284 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004285 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004286 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004287 break;
4288 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004289 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004290 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004291 break;
4292 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004293 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004294 opCode = spv::OpAtomicAnd;
4295 break;
4296 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004297 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004298 opCode = spv::OpAtomicOr;
4299 break;
4300 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004301 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004302 opCode = spv::OpAtomicXor;
4303 break;
4304 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004305 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004306 opCode = spv::OpAtomicExchange;
4307 break;
4308 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004309 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004310 opCode = spv::OpAtomicCompareExchange;
4311 break;
4312 case glslang::EOpAtomicCounterIncrement:
4313 opCode = spv::OpAtomicIIncrement;
4314 break;
4315 case glslang::EOpAtomicCounterDecrement:
4316 opCode = spv::OpAtomicIDecrement;
4317 break;
4318 case glslang::EOpAtomicCounter:
4319 opCode = spv::OpAtomicLoad;
4320 break;
4321 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004322 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004323 break;
4324 }
4325
4326 // Sort out the operands
4327 // - mapping from glslang -> SPV
4328 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004329 // - compare-exchange swaps the value and comparator
4330 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004331 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4332 auto opIt = operands.begin(); // walk the glslang operands
4333 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004334 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4335 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4336 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004337 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4338 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004339 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004340 spvAtomicOperands.push_back(*(opIt + 1));
4341 spvAtomicOperands.push_back(*opIt);
4342 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004343 }
John Kessenich426394d2015-07-23 10:22:48 -06004344
John Kessenich3e60a6f2015-09-14 22:45:16 -06004345 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004346 for (; opIt != operands.end(); ++opIt)
4347 spvAtomicOperands.push_back(*opIt);
4348
4349 return builder.createOp(opCode, typeId, spvAtomicOperands);
4350}
4351
John Kessenich91cef522016-05-05 16:45:40 -06004352// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004353spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004354{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004355#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004356 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004357 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004358#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004359
Rex Xu51596642016-09-21 18:56:12 +08004360 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004361 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004362 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4363
chaocf200da82016-12-20 12:44:35 -08004364 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4365 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004366 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4367 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004368 } else if (op == glslang::EOpAnyInvocation ||
4369 op == glslang::EOpAllInvocations ||
4370 op == glslang::EOpAllInvocationsEqual) {
4371 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4372 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004373 } else {
4374 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004375#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004376 if (op == glslang::EOpMinInvocationsNonUniform ||
4377 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004378 op == glslang::EOpAddInvocationsNonUniform ||
4379 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4380 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4381 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4382 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4383 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4384 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004385 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004386#endif
Rex Xu51596642016-09-21 18:56:12 +08004387
4388 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004389#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004390 switch (op) {
4391 case glslang::EOpMinInvocations:
4392 case glslang::EOpMaxInvocations:
4393 case glslang::EOpAddInvocations:
4394 case glslang::EOpMinInvocationsNonUniform:
4395 case glslang::EOpMaxInvocationsNonUniform:
4396 case glslang::EOpAddInvocationsNonUniform:
4397 groupOperation = spv::GroupOperationReduce;
4398 spvGroupOperands.push_back(groupOperation);
4399 break;
4400 case glslang::EOpMinInvocationsInclusiveScan:
4401 case glslang::EOpMaxInvocationsInclusiveScan:
4402 case glslang::EOpAddInvocationsInclusiveScan:
4403 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4404 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4405 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4406 groupOperation = spv::GroupOperationInclusiveScan;
4407 spvGroupOperands.push_back(groupOperation);
4408 break;
4409 case glslang::EOpMinInvocationsExclusiveScan:
4410 case glslang::EOpMaxInvocationsExclusiveScan:
4411 case glslang::EOpAddInvocationsExclusiveScan:
4412 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4413 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4414 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4415 groupOperation = spv::GroupOperationExclusiveScan;
4416 spvGroupOperands.push_back(groupOperation);
4417 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004418 default:
4419 break;
Rex Xu430ef402016-10-14 17:22:23 +08004420 }
Rex Xu9d93a232016-05-05 12:30:44 +08004421#endif
Rex Xu51596642016-09-21 18:56:12 +08004422 }
4423
4424 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4425 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004426
4427 switch (op) {
4428 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004429 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004430 break;
John Kessenich91cef522016-05-05 16:45:40 -06004431 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004432 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004433 break;
John Kessenich91cef522016-05-05 16:45:40 -06004434 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004435 opCode = spv::OpSubgroupAllEqualKHR;
4436 break;
Rex Xu51596642016-09-21 18:56:12 +08004437 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004438 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004439 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004440 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004441 break;
4442 case glslang::EOpReadFirstInvocation:
4443 opCode = spv::OpSubgroupFirstInvocationKHR;
4444 break;
4445 case glslang::EOpBallot:
4446 {
4447 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4448 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4449 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4450 //
4451 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4452 //
4453 spv::Id uintType = builder.makeUintType(32);
4454 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4455 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4456
4457 std::vector<spv::Id> components;
4458 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4459 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4460
4461 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4462 return builder.createUnaryOp(spv::OpBitcast, typeId,
4463 builder.createCompositeConstruct(uvec2Type, components));
4464 }
4465
Rex Xu9d93a232016-05-05 12:30:44 +08004466#ifdef AMD_EXTENSIONS
4467 case glslang::EOpMinInvocations:
4468 case glslang::EOpMaxInvocations:
4469 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004470 case glslang::EOpMinInvocationsInclusiveScan:
4471 case glslang::EOpMaxInvocationsInclusiveScan:
4472 case glslang::EOpAddInvocationsInclusiveScan:
4473 case glslang::EOpMinInvocationsExclusiveScan:
4474 case glslang::EOpMaxInvocationsExclusiveScan:
4475 case glslang::EOpAddInvocationsExclusiveScan:
4476 if (op == glslang::EOpMinInvocations ||
4477 op == glslang::EOpMinInvocationsInclusiveScan ||
4478 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004479 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004480 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004481 else {
4482 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004483 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004484 else
Rex Xu51596642016-09-21 18:56:12 +08004485 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004486 }
Rex Xu430ef402016-10-14 17:22:23 +08004487 } else if (op == glslang::EOpMaxInvocations ||
4488 op == glslang::EOpMaxInvocationsInclusiveScan ||
4489 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004490 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004491 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004492 else {
4493 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004494 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004495 else
Rex Xu51596642016-09-21 18:56:12 +08004496 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004497 }
4498 } else {
4499 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004500 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004501 else
Rex Xu51596642016-09-21 18:56:12 +08004502 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004503 }
4504
Rex Xu2bbbe062016-08-23 15:41:05 +08004505 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004506 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004507
4508 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004509 case glslang::EOpMinInvocationsNonUniform:
4510 case glslang::EOpMaxInvocationsNonUniform:
4511 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004512 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4513 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4514 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4515 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4516 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4517 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4518 if (op == glslang::EOpMinInvocationsNonUniform ||
4519 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4520 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004521 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004522 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004523 else {
4524 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004525 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004526 else
Rex Xu51596642016-09-21 18:56:12 +08004527 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004528 }
4529 }
Rex Xu430ef402016-10-14 17:22:23 +08004530 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4531 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4532 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004533 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004534 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004535 else {
4536 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004537 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004538 else
Rex Xu51596642016-09-21 18:56:12 +08004539 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004540 }
4541 }
4542 else {
4543 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004544 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004545 else
Rex Xu51596642016-09-21 18:56:12 +08004546 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004547 }
4548
Rex Xu2bbbe062016-08-23 15:41:05 +08004549 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004550 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004551
4552 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004553#endif
John Kessenich91cef522016-05-05 16:45:40 -06004554 default:
4555 logger->missingFunctionality("invocation operation");
4556 return spv::NoResult;
4557 }
Rex Xu51596642016-09-21 18:56:12 +08004558
4559 assert(opCode != spv::OpNop);
4560 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004561}
4562
Rex Xu2bbbe062016-08-23 15:41:05 +08004563// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004564spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004565{
Rex Xub7072052016-09-26 15:53:40 +08004566#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004567 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4568 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004569 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004570 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004571 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4572 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4573 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004574#else
4575 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4576 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004577 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4578 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004579#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004580
4581 // Handle group invocation operations scalar by scalar.
4582 // The result type is the same type as the original type.
4583 // The algorithm is to:
4584 // - break the vector into scalars
4585 // - apply the operation to each scalar
4586 // - make a vector out the scalar results
4587
4588 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004589 int numComponents = builder.getNumComponents(operands[0]);
4590 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004591 std::vector<spv::Id> results;
4592
4593 // do each scalar op
4594 for (int comp = 0; comp < numComponents; ++comp) {
4595 std::vector<unsigned int> indexes;
4596 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004597 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004598 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004599 if (op == spv::OpSubgroupReadInvocationKHR) {
4600 spvGroupOperands.push_back(scalar);
4601 spvGroupOperands.push_back(operands[1]);
4602 } else if (op == spv::OpGroupBroadcast) {
4603 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004604 spvGroupOperands.push_back(scalar);
4605 spvGroupOperands.push_back(operands[1]);
4606 } else {
chaocf200da82016-12-20 12:44:35 -08004607 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004608 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004609 spvGroupOperands.push_back(scalar);
4610 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004611
Rex Xub7072052016-09-26 15:53:40 +08004612 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004613 }
4614
4615 // put the pieces together
4616 return builder.createCompositeConstruct(typeId, results);
4617}
Rex Xu2bbbe062016-08-23 15:41:05 +08004618
John Kessenich5e4b1242015-08-06 22:53:06 -06004619spv::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 -06004620{
Rex Xu8ff43de2016-04-22 16:51:45 +08004621 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004622#ifdef AMD_EXTENSIONS
4623 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4624#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004625 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004626#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004627
John Kessenich140f3df2015-06-26 16:58:36 -06004628 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004629 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004630 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004631 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004632 spv::Id typeId0 = 0;
4633 if (consumedOperands > 0)
4634 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08004635 spv::Id typeId1 = 0;
4636 if (consumedOperands > 1)
4637 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07004638 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004639
4640 switch (op) {
4641 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004642 if (isFloat)
4643 libCall = spv::GLSLstd450FMin;
4644 else if (isUnsigned)
4645 libCall = spv::GLSLstd450UMin;
4646 else
4647 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004648 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004649 break;
4650 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004651 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004652 break;
4653 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004654 if (isFloat)
4655 libCall = spv::GLSLstd450FMax;
4656 else if (isUnsigned)
4657 libCall = spv::GLSLstd450UMax;
4658 else
4659 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004660 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004661 break;
4662 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004663 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004664 break;
4665 case glslang::EOpDot:
4666 opCode = spv::OpDot;
4667 break;
4668 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004669 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004670 break;
4671
4672 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004673 if (isFloat)
4674 libCall = spv::GLSLstd450FClamp;
4675 else if (isUnsigned)
4676 libCall = spv::GLSLstd450UClamp;
4677 else
4678 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004679 builder.promoteScalar(precision, operands.front(), operands[1]);
4680 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004681 break;
4682 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004683 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4684 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004685 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004686 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004687 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004688 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004689 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004690 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004691 break;
4692 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004693 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004694 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004695 break;
4696 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004697 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004698 builder.promoteScalar(precision, operands[0], operands[2]);
4699 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004700 break;
4701
4702 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004703 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004704 break;
4705 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004706 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004707 break;
4708 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004709 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004710 break;
4711 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004712 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004713 break;
4714 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004715 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004716 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004717 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004718 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004719 libCall = spv::GLSLstd450InterpolateAtSample;
4720 break;
4721 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004722 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004723 libCall = spv::GLSLstd450InterpolateAtOffset;
4724 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004725 case glslang::EOpAddCarry:
4726 opCode = spv::OpIAddCarry;
4727 typeId = builder.makeStructResultType(typeId0, typeId0);
4728 consumedOperands = 2;
4729 break;
4730 case glslang::EOpSubBorrow:
4731 opCode = spv::OpISubBorrow;
4732 typeId = builder.makeStructResultType(typeId0, typeId0);
4733 consumedOperands = 2;
4734 break;
4735 case glslang::EOpUMulExtended:
4736 opCode = spv::OpUMulExtended;
4737 typeId = builder.makeStructResultType(typeId0, typeId0);
4738 consumedOperands = 2;
4739 break;
4740 case glslang::EOpIMulExtended:
4741 opCode = spv::OpSMulExtended;
4742 typeId = builder.makeStructResultType(typeId0, typeId0);
4743 consumedOperands = 2;
4744 break;
4745 case glslang::EOpBitfieldExtract:
4746 if (isUnsigned)
4747 opCode = spv::OpBitFieldUExtract;
4748 else
4749 opCode = spv::OpBitFieldSExtract;
4750 break;
4751 case glslang::EOpBitfieldInsert:
4752 opCode = spv::OpBitFieldInsert;
4753 break;
4754
4755 case glslang::EOpFma:
4756 libCall = spv::GLSLstd450Fma;
4757 break;
4758 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004759 {
4760 libCall = spv::GLSLstd450FrexpStruct;
4761 assert(builder.isPointerType(typeId1));
4762 typeId1 = builder.getContainedTypeId(typeId1);
4763#ifdef AMD_EXTENSIONS
4764 int width = builder.getScalarTypeWidth(typeId1);
4765#else
4766 int width = 32;
4767#endif
4768 if (builder.getNumComponents(operands[0]) == 1)
4769 frexpIntType = builder.makeIntegerType(width, true);
4770 else
4771 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
4772 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4773 consumedOperands = 1;
4774 }
John Kessenich55e7d112015-11-15 21:33:39 -07004775 break;
4776 case glslang::EOpLdexp:
4777 libCall = spv::GLSLstd450Ldexp;
4778 break;
4779
Rex Xu574ab042016-04-14 16:53:07 +08004780 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004781 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004782
Rex Xu9d93a232016-05-05 12:30:44 +08004783#ifdef AMD_EXTENSIONS
4784 case glslang::EOpSwizzleInvocations:
4785 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4786 libCall = spv::SwizzleInvocationsAMD;
4787 break;
4788 case glslang::EOpSwizzleInvocationsMasked:
4789 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4790 libCall = spv::SwizzleInvocationsMaskedAMD;
4791 break;
4792 case glslang::EOpWriteInvocation:
4793 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4794 libCall = spv::WriteInvocationAMD;
4795 break;
4796
4797 case glslang::EOpMin3:
4798 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4799 if (isFloat)
4800 libCall = spv::FMin3AMD;
4801 else {
4802 if (isUnsigned)
4803 libCall = spv::UMin3AMD;
4804 else
4805 libCall = spv::SMin3AMD;
4806 }
4807 break;
4808 case glslang::EOpMax3:
4809 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4810 if (isFloat)
4811 libCall = spv::FMax3AMD;
4812 else {
4813 if (isUnsigned)
4814 libCall = spv::UMax3AMD;
4815 else
4816 libCall = spv::SMax3AMD;
4817 }
4818 break;
4819 case glslang::EOpMid3:
4820 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4821 if (isFloat)
4822 libCall = spv::FMid3AMD;
4823 else {
4824 if (isUnsigned)
4825 libCall = spv::UMid3AMD;
4826 else
4827 libCall = spv::SMid3AMD;
4828 }
4829 break;
4830
4831 case glslang::EOpInterpolateAtVertex:
4832 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4833 libCall = spv::InterpolateAtVertexAMD;
4834 break;
4835#endif
4836
John Kessenich140f3df2015-06-26 16:58:36 -06004837 default:
4838 return 0;
4839 }
4840
4841 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004842 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004843 // Use an extended instruction from the standard library.
4844 // Construct the call arguments, without modifying the original operands vector.
4845 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4846 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004847 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004848 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004849 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004850 case 0:
4851 // should all be handled by visitAggregate and createNoArgOperation
4852 assert(0);
4853 return 0;
4854 case 1:
4855 // should all be handled by createUnaryOperation
4856 assert(0);
4857 return 0;
4858 case 2:
4859 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4860 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004861 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004862 // anything 3 or over doesn't have l-value operands, so all should be consumed
4863 assert(consumedOperands == operands.size());
4864 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004865 break;
4866 }
4867 }
4868
John Kessenich55e7d112015-11-15 21:33:39 -07004869 // Decode the return types that were structures
4870 switch (op) {
4871 case glslang::EOpAddCarry:
4872 case glslang::EOpSubBorrow:
4873 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4874 id = builder.createCompositeExtract(id, typeId0, 0);
4875 break;
4876 case glslang::EOpUMulExtended:
4877 case glslang::EOpIMulExtended:
4878 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4879 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4880 break;
4881 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004882 {
4883 assert(operands.size() == 2);
4884 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
4885 // "exp" is floating-point type (from HLSL intrinsic)
4886 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
4887 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
4888 builder.createStore(member1, operands[1]);
4889 } else
4890 // "exp" is integer type (from GLSL built-in function)
4891 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4892 id = builder.createCompositeExtract(id, typeId0, 0);
4893 }
John Kessenich55e7d112015-11-15 21:33:39 -07004894 break;
4895 default:
4896 break;
4897 }
4898
John Kessenich32cfd492016-02-02 12:37:46 -07004899 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004900}
4901
Rex Xu9d93a232016-05-05 12:30:44 +08004902// Intrinsics with no arguments (or no return value, and no precision).
4903spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004904{
4905 // TODO: get the barrier operands correct
4906
4907 switch (op) {
4908 case glslang::EOpEmitVertex:
4909 builder.createNoResultOp(spv::OpEmitVertex);
4910 return 0;
4911 case glslang::EOpEndPrimitive:
4912 builder.createNoResultOp(spv::OpEndPrimitive);
4913 return 0;
4914 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004915 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004916 return 0;
4917 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004918 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004919 return 0;
4920 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004921 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004922 return 0;
4923 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004924 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004925 return 0;
4926 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004927 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004928 return 0;
4929 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004930 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004931 return 0;
4932 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004933 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004934 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004935 case glslang::EOpAllMemoryBarrierWithGroupSync:
4936 // Control barrier with non-"None" semantic is also a memory barrier.
4937 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4938 return 0;
4939 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4940 // Control barrier with non-"None" semantic is also a memory barrier.
4941 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4942 return 0;
4943 case glslang::EOpWorkgroupMemoryBarrier:
4944 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4945 return 0;
4946 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4947 // Control barrier with non-"None" semantic is also a memory barrier.
4948 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4949 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004950#ifdef AMD_EXTENSIONS
4951 case glslang::EOpTime:
4952 {
4953 std::vector<spv::Id> args; // Dummy arguments
4954 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4955 return builder.setPrecision(id, precision);
4956 }
4957#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004958 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004959 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004960 return 0;
4961 }
4962}
4963
4964spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4965{
John Kessenich2f273362015-07-18 22:34:27 -06004966 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004967 spv::Id id;
4968 if (symbolValues.end() != iter) {
4969 id = iter->second;
4970 return id;
4971 }
4972
4973 // it was not found, create it
4974 id = createSpvVariable(symbol);
4975 symbolValues[symbol->getId()] = id;
4976
Rex Xuc884b4a2016-06-29 15:03:44 +08004977 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004978 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004979 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004980 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004981 if (symbol->getType().getQualifier().hasSpecConstantId())
4982 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004983 if (symbol->getQualifier().hasIndex())
4984 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4985 if (symbol->getQualifier().hasComponent())
4986 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4987 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004988 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004989 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004990 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004991 if (symbol->getQualifier().hasXfbBuffer())
4992 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4993 if (symbol->getQualifier().hasXfbOffset())
4994 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4995 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004996 // atomic counters use this:
4997 if (symbol->getQualifier().hasOffset())
4998 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004999 }
5000
scygan2c864272016-05-18 18:09:17 +02005001 if (symbol->getQualifier().hasLocation())
5002 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005003 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005004 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005005 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005006 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005007 }
John Kessenich140f3df2015-06-26 16:58:36 -06005008 if (symbol->getQualifier().hasSet())
5009 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005010 else if (IsDescriptorResource(symbol->getType())) {
5011 // default to 0
5012 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5013 }
John Kessenich140f3df2015-06-26 16:58:36 -06005014 if (symbol->getQualifier().hasBinding())
5015 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005016 if (symbol->getQualifier().hasAttachment())
5017 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005018 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005019 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005020 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005021 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005022 if (symbol->getQualifier().hasXfbBuffer())
5023 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5024 }
5025
Rex Xu1da878f2016-02-21 20:59:01 +08005026 if (symbol->getType().isImage()) {
5027 std::vector<spv::Decoration> memory;
5028 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5029 for (unsigned int i = 0; i < memory.size(); ++i)
5030 addDecoration(id, memory[i]);
5031 }
5032
John Kessenich140f3df2015-06-26 16:58:36 -06005033 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005034 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005035 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005036 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005037
John Kessenichecba76f2017-01-06 00:34:48 -07005038#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005039 if (builtIn == spv::BuiltInSampleMask) {
5040 spv::Decoration decoration;
5041 // GL_NV_sample_mask_override_coverage extension
5042 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005043 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005044 else
5045 decoration = (spv::Decoration)spv::DecorationMax;
5046 addDecoration(id, decoration);
5047 if (decoration != spv::DecorationMax) {
5048 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5049 }
5050 }
chaoc771d89f2017-01-13 01:10:53 -08005051 else if (builtIn == spv::BuiltInLayer) {
5052 // SPV_NV_viewport_array2 extension
5053 if (symbol->getQualifier().layoutViewportRelative)
5054 {
5055 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5056 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5057 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5058 }
5059 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5060 {
5061 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5062 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5063 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5064 }
5065 }
5066
chaoc6e5acae2016-12-20 13:28:52 -08005067 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005068 addDecoration(id, spv::DecorationPassthroughNV);
5069 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005070 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5071 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005072#endif
5073
John Kessenich140f3df2015-06-26 16:58:36 -06005074 return id;
5075}
5076
John Kessenich55e7d112015-11-15 21:33:39 -07005077// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005078void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5079{
John Kessenich4016e382016-07-15 11:53:56 -06005080 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005081 builder.addDecoration(id, dec);
5082}
5083
John Kessenich55e7d112015-11-15 21:33:39 -07005084// If 'dec' is valid, add a one-operand decoration to an object
5085void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5086{
John Kessenich4016e382016-07-15 11:53:56 -06005087 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005088 builder.addDecoration(id, dec, value);
5089}
5090
5091// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005092void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5093{
John Kessenich4016e382016-07-15 11:53:56 -06005094 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005095 builder.addMemberDecoration(id, (unsigned)member, dec);
5096}
5097
John Kessenich92187592016-02-01 13:45:25 -07005098// If 'dec' is valid, add a one-operand decoration to a struct member
5099void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5100{
John Kessenich4016e382016-07-15 11:53:56 -06005101 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005102 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5103}
5104
John Kessenich55e7d112015-11-15 21:33:39 -07005105// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005106// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005107//
5108// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5109//
5110// Recursively walk the nodes. The nodes form a tree whose leaves are
5111// regular constants, which themselves are trees that createSpvConstant()
5112// recursively walks. So, this function walks the "top" of the tree:
5113// - emit specialization constant-building instructions for specConstant
5114// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005115spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005116{
John Kessenich7cc0e282016-03-20 00:46:02 -06005117 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005118
qining4f4bb812016-04-03 23:55:17 -04005119 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005120 if (! node.getQualifier().specConstant) {
5121 // hand off to the non-spec-constant path
5122 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5123 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005124 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005125 nextConst, false);
5126 }
5127
5128 // We now know we have a specialization constant to build
5129
John Kessenichd94c0032016-05-30 19:29:40 -06005130 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005131 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5132 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5133 std::vector<spv::Id> dimConstId;
5134 for (int dim = 0; dim < 3; ++dim) {
5135 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5136 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5137 if (specConst)
5138 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5139 }
5140 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5141 }
5142
5143 // An AST node labelled as specialization constant should be a symbol node.
5144 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5145 if (auto* sn = node.getAsSymbolNode()) {
5146 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005147 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5148 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5149 // will set the builder into spec constant op instruction generating mode.
5150 sub_tree->traverse(this);
5151 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005152 } else if (auto* const_union_array = &sn->getConstArray()){
5153 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005154 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5155 builder.addName(id, sn->getName().c_str());
5156 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005157 }
5158 }
qining4f4bb812016-04-03 23:55:17 -04005159
5160 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5161 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005162 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005163 exit(1);
5164 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005165}
5166
John Kessenich140f3df2015-06-26 16:58:36 -06005167// Use 'consts' as the flattened glslang source of scalar constants to recursively
5168// build the aggregate SPIR-V constant.
5169//
5170// If there are not enough elements present in 'consts', 0 will be substituted;
5171// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5172//
qining08408382016-03-21 09:51:37 -04005173spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005174{
5175 // vector of constants for SPIR-V
5176 std::vector<spv::Id> spvConsts;
5177
5178 // Type is used for struct and array constants
5179 spv::Id typeId = convertGlslangToSpvType(glslangType);
5180
5181 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005182 glslang::TType elementType(glslangType, 0);
5183 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005184 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005185 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005186 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005187 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005188 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005189 } else if (glslangType.getStruct()) {
5190 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5191 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005192 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005193 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005194 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5195 bool zero = nextConst >= consts.size();
5196 switch (glslangType.getBasicType()) {
5197 case glslang::EbtInt:
5198 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5199 break;
5200 case glslang::EbtUint:
5201 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5202 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005203 case glslang::EbtInt64:
5204 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5205 break;
5206 case glslang::EbtUint64:
5207 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5208 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005209 case glslang::EbtFloat:
5210 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5211 break;
5212 case glslang::EbtDouble:
5213 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5214 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005215#ifdef AMD_EXTENSIONS
5216 case glslang::EbtFloat16:
5217 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5218 break;
5219#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005220 case glslang::EbtBool:
5221 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5222 break;
5223 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005224 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005225 break;
5226 }
5227 ++nextConst;
5228 }
5229 } else {
5230 // we have a non-aggregate (scalar) constant
5231 bool zero = nextConst >= consts.size();
5232 spv::Id scalar = 0;
5233 switch (glslangType.getBasicType()) {
5234 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005235 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005236 break;
5237 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005238 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005239 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005240 case glslang::EbtInt64:
5241 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5242 break;
5243 case glslang::EbtUint64:
5244 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5245 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005246 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005247 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005248 break;
5249 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005250 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005251 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005252#ifdef AMD_EXTENSIONS
5253 case glslang::EbtFloat16:
5254 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5255 break;
5256#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005257 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005258 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005259 break;
5260 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005261 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005262 break;
5263 }
5264 ++nextConst;
5265 return scalar;
5266 }
5267
5268 return builder.makeCompositeConstant(typeId, spvConsts);
5269}
5270
John Kessenich7c1aa102015-10-15 13:29:11 -06005271// Return true if the node is a constant or symbol whose reading has no
5272// non-trivial observable cost or effect.
5273bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5274{
5275 // don't know what this is
5276 if (node == nullptr)
5277 return false;
5278
5279 // a constant is safe
5280 if (node->getAsConstantUnion() != nullptr)
5281 return true;
5282
5283 // not a symbol means non-trivial
5284 if (node->getAsSymbolNode() == nullptr)
5285 return false;
5286
5287 // a symbol, depends on what's being read
5288 switch (node->getType().getQualifier().storage) {
5289 case glslang::EvqTemporary:
5290 case glslang::EvqGlobal:
5291 case glslang::EvqIn:
5292 case glslang::EvqInOut:
5293 case glslang::EvqConst:
5294 case glslang::EvqConstReadOnly:
5295 case glslang::EvqUniform:
5296 return true;
5297 default:
5298 return false;
5299 }
qining25262b32016-05-06 17:25:16 -04005300}
John Kessenich7c1aa102015-10-15 13:29:11 -06005301
5302// A node is trivial if it is a single operation with no side effects.
5303// Error on the side of saying non-trivial.
5304// Return true if trivial.
5305bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5306{
5307 if (node == nullptr)
5308 return false;
5309
5310 // symbols and constants are trivial
5311 if (isTrivialLeaf(node))
5312 return true;
5313
5314 // otherwise, it needs to be a simple operation or one or two leaf nodes
5315
5316 // not a simple operation
5317 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5318 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5319 if (binaryNode == nullptr && unaryNode == nullptr)
5320 return false;
5321
5322 // not on leaf nodes
5323 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5324 return false;
5325
5326 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5327 return false;
5328 }
5329
5330 switch (node->getAsOperator()->getOp()) {
5331 case glslang::EOpLogicalNot:
5332 case glslang::EOpConvIntToBool:
5333 case glslang::EOpConvUintToBool:
5334 case glslang::EOpConvFloatToBool:
5335 case glslang::EOpConvDoubleToBool:
5336 case glslang::EOpEqual:
5337 case glslang::EOpNotEqual:
5338 case glslang::EOpLessThan:
5339 case glslang::EOpGreaterThan:
5340 case glslang::EOpLessThanEqual:
5341 case glslang::EOpGreaterThanEqual:
5342 case glslang::EOpIndexDirect:
5343 case glslang::EOpIndexDirectStruct:
5344 case glslang::EOpLogicalXor:
5345 case glslang::EOpAny:
5346 case glslang::EOpAll:
5347 return true;
5348 default:
5349 return false;
5350 }
5351}
5352
5353// Emit short-circuiting code, where 'right' is never evaluated unless
5354// the left side is true (for &&) or false (for ||).
5355spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5356{
5357 spv::Id boolTypeId = builder.makeBoolType();
5358
5359 // emit left operand
5360 builder.clearAccessChain();
5361 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005362 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005363
5364 // Operands to accumulate OpPhi operands
5365 std::vector<spv::Id> phiOperands;
5366 // accumulate left operand's phi information
5367 phiOperands.push_back(leftId);
5368 phiOperands.push_back(builder.getBuildPoint()->getId());
5369
5370 // Make the two kinds of operation symmetric with a "!"
5371 // || => emit "if (! left) result = right"
5372 // && => emit "if ( left) result = right"
5373 //
5374 // TODO: this runtime "not" for || could be avoided by adding functionality
5375 // to 'builder' to have an "else" without an "then"
5376 if (op == glslang::EOpLogicalOr)
5377 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5378
5379 // make an "if" based on the left value
5380 spv::Builder::If ifBuilder(leftId, builder);
5381
5382 // emit right operand as the "then" part of the "if"
5383 builder.clearAccessChain();
5384 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005385 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005386
5387 // accumulate left operand's phi information
5388 phiOperands.push_back(rightId);
5389 phiOperands.push_back(builder.getBuildPoint()->getId());
5390
5391 // finish the "if"
5392 ifBuilder.makeEndIf();
5393
5394 // phi together the two results
5395 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5396}
5397
Rex Xu9d93a232016-05-05 12:30:44 +08005398// Return type Id of the imported set of extended instructions corresponds to the name.
5399// Import this set if it has not been imported yet.
5400spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5401{
5402 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5403 return extBuiltinMap[name];
5404 else {
Rex Xu51596642016-09-21 18:56:12 +08005405 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005406 spv::Id extBuiltins = builder.import(name);
5407 extBuiltinMap[name] = extBuiltins;
5408 return extBuiltins;
5409 }
5410}
5411
John Kessenich140f3df2015-06-26 16:58:36 -06005412}; // end anonymous namespace
5413
5414namespace glslang {
5415
John Kessenich68d78fd2015-07-12 19:28:10 -06005416void GetSpirvVersion(std::string& version)
5417{
John Kessenich9e55f632015-07-15 10:03:39 -06005418 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005419 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005420 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005421 version = buf;
5422}
5423
John Kessenich140f3df2015-06-26 16:58:36 -06005424// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005425void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005426{
5427 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005428 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005429 if (out.fail())
5430 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005431 for (int i = 0; i < (int)spirv.size(); ++i) {
5432 unsigned int word = spirv[i];
5433 out.write((const char*)&word, 4);
5434 }
5435 out.close();
5436}
5437
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005438// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005439void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005440{
5441 std::ofstream out;
5442 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005443 if (out.fail())
5444 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005445 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005446 if (varName != nullptr) {
5447 out << "\t #pragma once" << std::endl;
5448 out << "const uint32_t " << varName << "[] = {" << std::endl;
5449 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005450 const int WORDS_PER_LINE = 8;
5451 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5452 out << "\t";
5453 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5454 const unsigned int word = spirv[i + j];
5455 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5456 if (i + j + 1 < (int)spirv.size()) {
5457 out << ",";
5458 }
5459 }
5460 out << std::endl;
5461 }
Flavio15017db2017-02-15 14:29:33 -08005462 if (varName != nullptr) {
5463 out << "};";
5464 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005465 out.close();
5466}
5467
John Kessenich140f3df2015-06-26 16:58:36 -06005468//
5469// Set up the glslang traversal
5470//
5471void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5472{
Lei Zhang17535f72016-05-04 15:55:59 -04005473 spv::SpvBuildLogger logger;
5474 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005475}
5476
Lei Zhang17535f72016-05-04 15:55:59 -04005477void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005478{
John Kessenich140f3df2015-06-26 16:58:36 -06005479 TIntermNode* root = intermediate.getTreeRoot();
5480
5481 if (root == 0)
5482 return;
5483
5484 glslang::GetThreadPoolAllocator().push();
5485
Lei Zhang17535f72016-05-04 15:55:59 -04005486 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005487 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005488 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005489 it.dumpSpv(spirv);
5490
5491 glslang::GetThreadPoolAllocator().pop();
5492}
5493
5494}; // end namespace glslang