blob: d2a9085daa8ec7ab34045dbe12d810526ca00092 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
John Kessenich927608b2017-01-06 12:34:14 -070023// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060035
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080050#ifdef NV_EXTENSIONS
51 #include "GLSL.ext.NV.h"
52#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
John Kessenich55e7d112015-11-15 21:33:39 -070071// For low-order part of the generator's magic number. Bump up
72// when there is a change in the style (e.g., if SSA form changes,
73// or a different instruction sequence to do something gets used).
74const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060075
qining4c912612016-04-01 10:35:16 -040076namespace {
77class SpecConstantOpModeGuard {
78public:
79 SpecConstantOpModeGuard(spv::Builder* builder)
80 : builder_(builder) {
81 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040082 }
83 ~SpecConstantOpModeGuard() {
84 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
85 : builder_->setToNormalCodeGenMode();
86 }
qining40887662016-04-03 22:20:42 -040087 void turnOnSpecConstantOpMode() {
88 builder_->setToSpecConstCodeGenMode();
89 }
qining4c912612016-04-01 10:35:16 -040090
91private:
92 spv::Builder* builder_;
93 bool previous_flag_;
94};
95}
96
John Kessenich140f3df2015-06-26 16:58:36 -060097//
98// The main holder of information for translating glslang to SPIR-V.
99//
100// Derives from the AST walking base class.
101//
102class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
103public:
Lei Zhang17535f72016-05-04 15:55:59 -0400104 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenichfca82622016-11-26 13:23:20 -0700105 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600106
107 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
108 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
109 void visitConstantUnion(glslang::TIntermConstantUnion*);
110 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
111 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
112 void visitSymbol(glslang::TIntermSymbol* symbol);
113 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
114 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
115 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
116
John Kessenichfca82622016-11-26 13:23:20 -0700117 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700118 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600119
120protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800121 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800122 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100123 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700124 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600125 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
126 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600127 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
128 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
129 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600130 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700131 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600132 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600133 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
134 glslang::TLayoutPacking, const glslang::TQualifier&);
135 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
136 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700137 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700138 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800139 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600140 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700141 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700142 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
143 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
144 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100145 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600146
John Kessenich6fccb3c2016-09-19 16:01:41 -0600147 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600148 void makeFunctions(const glslang::TIntermSequence&);
149 void makeGlobalInitializers(const glslang::TIntermSequence&);
150 void visitFunctions(const glslang::TIntermSequence&);
151 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800152 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600153 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
154 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600155 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
156
qining25262b32016-05-06 17:25:16 -0400157 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
158 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
159 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800160 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800161 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600162 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800163 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800164 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800165 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600166 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800167 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600168 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
169 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700170 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600171 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700172 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400173 spv::Id createSpvConstant(const glslang::TIntermTyped&);
174 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600175 bool isTrivialLeaf(const glslang::TIntermTyped* node);
176 bool isTrivial(const glslang::TIntermTyped* node);
177 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800178 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600179
180 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600181 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700182 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600183 int sequenceDepth;
184
Lei Zhang17535f72016-05-04 15:55:59 -0400185 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400186
John Kessenich140f3df2015-06-26 16:58:36 -0600187 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
188 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700189 bool inEntryPoint;
190 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700191 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700192 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600193 const glslang::TIntermediate* glslangIntermediate;
194 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800195 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600196
John Kessenich2f273362015-07-18 22:34:27 -0600197 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600198 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600199 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700200 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600201 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600202 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600203};
204
205//
206// Helper functions for translating glslang representations to SPIR-V enumerants.
207//
208
209// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700210spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600211{
John Kessenich66e2faf2016-03-12 18:34:36 -0700212 switch (source) {
213 case glslang::EShSourceGlsl:
214 switch (profile) {
215 case ENoProfile:
216 case ECoreProfile:
217 case ECompatibilityProfile:
218 return spv::SourceLanguageGLSL;
219 case EEsProfile:
220 return spv::SourceLanguageESSL;
221 default:
222 return spv::SourceLanguageUnknown;
223 }
224 case glslang::EShSourceHlsl:
John Kessenich927608b2017-01-06 12:34:14 -0700225 // Use SourceLanguageUnknown instead of SourceLanguageHLSL for now, until Vulkan knows what HLSL is
Dan Baker55d5f2d2016-08-15 16:05:45 -0400226 return spv::SourceLanguageUnknown;
John Kessenich140f3df2015-06-26 16:58:36 -0600227 default:
228 return spv::SourceLanguageUnknown;
229 }
230}
231
232// Translate glslang language (stage) to SPIR-V execution model.
233spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
234{
235 switch (stage) {
236 case EShLangVertex: return spv::ExecutionModelVertex;
237 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
238 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
239 case EShLangGeometry: return spv::ExecutionModelGeometry;
240 case EShLangFragment: return spv::ExecutionModelFragment;
241 case EShLangCompute: return spv::ExecutionModelGLCompute;
242 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700243 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600244 return spv::ExecutionModelFragment;
245 }
246}
247
248// Translate glslang type to SPIR-V storage class.
249spv::StorageClass TranslateStorageClass(const glslang::TType& type)
250{
251 if (type.getQualifier().isPipeInput())
252 return spv::StorageClassInput;
253 else if (type.getQualifier().isPipeOutput())
254 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700255 else if (type.getBasicType() == glslang::EbtAtomicUint)
256 return spv::StorageClassAtomicCounter;
John Kessenich4a57dce2017-02-24 19:15:46 -0700257 else if (type.containsOpaque())
258 return spv::StorageClassUniformConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600259 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700260 if (type.getQualifier().layoutPushConstant)
261 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600262 if (type.getBasicType() == glslang::EbtBlock)
263 return spv::StorageClassUniform;
264 else
265 return spv::StorageClassUniformConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600266 } else {
267 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700268 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
269 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600270 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
271 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400272 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700273 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600274 return spv::StorageClassFunction;
275 }
276 }
277}
278
279// Translate glslang sampler type to SPIR-V dimensionality.
280spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
281{
282 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700283 case glslang::Esd1D: return spv::Dim1D;
284 case glslang::Esd2D: return spv::Dim2D;
285 case glslang::Esd3D: return spv::Dim3D;
286 case glslang::EsdCube: return spv::DimCube;
287 case glslang::EsdRect: return spv::DimRect;
288 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700289 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600290 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700291 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600292 return spv::Dim2D;
293 }
294}
295
John Kessenichf6640762016-08-01 19:44:00 -0600296// Translate glslang precision to SPIR-V precision decorations.
297spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600298{
John Kessenichf6640762016-08-01 19:44:00 -0600299 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700300 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600301 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600302 default:
303 return spv::NoPrecision;
304 }
305}
306
John Kessenichf6640762016-08-01 19:44:00 -0600307// Translate glslang type to SPIR-V precision decorations.
308spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
309{
310 return TranslatePrecisionDecoration(type.getQualifier().precision);
311}
312
John Kessenich140f3df2015-06-26 16:58:36 -0600313// Translate glslang type to SPIR-V block decorations.
314spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
315{
316 if (type.getBasicType() == glslang::EbtBlock) {
317 switch (type.getQualifier().storage) {
318 case glslang::EvqUniform: return spv::DecorationBlock;
319 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
320 case glslang::EvqVaryingIn: return spv::DecorationBlock;
321 case glslang::EvqVaryingOut: return spv::DecorationBlock;
322 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700323 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600324 break;
325 }
326 }
327
John Kessenich4016e382016-07-15 11:53:56 -0600328 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600329}
330
Rex Xu1da878f2016-02-21 20:59:01 +0800331// Translate glslang type to SPIR-V memory decorations.
332void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
333{
334 if (qualifier.coherent)
335 memory.push_back(spv::DecorationCoherent);
336 if (qualifier.volatil)
337 memory.push_back(spv::DecorationVolatile);
338 if (qualifier.restrict)
339 memory.push_back(spv::DecorationRestrict);
340 if (qualifier.readonly)
341 memory.push_back(spv::DecorationNonWritable);
342 if (qualifier.writeonly)
343 memory.push_back(spv::DecorationNonReadable);
344}
345
John Kessenich140f3df2015-06-26 16:58:36 -0600346// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700347spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600348{
349 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700350 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600351 case glslang::ElmRowMajor:
352 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700353 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600354 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700355 default:
356 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600357 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600358 }
359 } else {
360 switch (type.getBasicType()) {
361 default:
John Kessenich4016e382016-07-15 11:53:56 -0600362 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600363 break;
364 case glslang::EbtBlock:
365 switch (type.getQualifier().storage) {
366 case glslang::EvqUniform:
367 case glslang::EvqBuffer:
368 switch (type.getQualifier().layoutPacking) {
369 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600370 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
371 default:
John Kessenich4016e382016-07-15 11:53:56 -0600372 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600373 }
374 case glslang::EvqVaryingIn:
375 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700376 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600378 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700379 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600380 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600381 }
382 }
383 }
384}
385
386// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600387// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700388// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800389spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600390{
Rex Xubbceed72016-05-21 09:40:44 +0800391 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700392 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600393 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800394 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700395 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700396 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600397 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800398#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800399 else if (qualifier.explicitInterp) {
400 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800401 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800402 }
Rex Xu9d93a232016-05-05 12:30:44 +0800403#endif
Rex Xubbceed72016-05-21 09:40:44 +0800404 else
John Kessenich4016e382016-07-15 11:53:56 -0600405 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800406}
407
408// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600409// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800410// should be applied.
411spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
412{
413 if (qualifier.patch)
414 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700415 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600416 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700417 else if (qualifier.sample) {
418 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600419 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700420 } else
John Kessenich4016e382016-07-15 11:53:56 -0600421 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600422}
423
John Kessenich92187592016-02-01 13:45:25 -0700424// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700425spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600426{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700427 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600428 return spv::DecorationInvariant;
429 else
John Kessenich4016e382016-07-15 11:53:56 -0600430 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600431}
432
qining9220dbb2016-05-04 17:34:38 -0400433// If glslang type is noContraction, return SPIR-V NoContraction decoration.
434spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
435{
436 if (qualifier.noContraction)
437 return spv::DecorationNoContraction;
438 else
John Kessenich4016e382016-07-15 11:53:56 -0600439 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400440}
441
David Netoa901ffe2016-06-08 14:11:40 +0100442// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
443// associated capabilities when required. For some built-in variables, a capability
444// is generated only when using the variable in an executable instruction, but not when
445// just declaring a struct member variable with it. This is true for PointSize,
446// ClipDistance, and CullDistance.
447spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600448{
449 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700450 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600451 // Defer adding the capability until the built-in is actually used.
452 if (! memberDeclaration) {
453 switch (glslangIntermediate->getStage()) {
454 case EShLangGeometry:
455 builder.addCapability(spv::CapabilityGeometryPointSize);
456 break;
457 case EShLangTessControl:
458 case EShLangTessEvaluation:
459 builder.addCapability(spv::CapabilityTessellationPointSize);
460 break;
461 default:
462 break;
463 }
John Kessenich92187592016-02-01 13:45:25 -0700464 }
465 return spv::BuiltInPointSize;
466
John Kessenichebb50532016-05-16 19:22:05 -0600467 // These *Distance capabilities logically belong here, but if the member is declared and
468 // then never used, consumers of SPIR-V prefer the capability not be declared.
469 // They are now generated when used, rather than here when declared.
470 // Potentially, the specification should be more clear what the minimum
471 // use needed is to trigger the capability.
472 //
John Kessenich92187592016-02-01 13:45:25 -0700473 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100474 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800475 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700476 return spv::BuiltInClipDistance;
477
478 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100479 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800480 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700481 return spv::BuiltInCullDistance;
482
483 case glslang::EbvViewportIndex:
Rex Xu5e317ff2017-03-16 23:02:39 +0800484 if (!memberDeclaration) {
485 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800486#ifdef NV_EXTENSIONS
Rex Xu5e317ff2017-03-16 23:02:39 +0800487 if (glslangIntermediate->getStage() == EShLangVertex ||
488 glslangIntermediate->getStage() == EShLangTessControl ||
489 glslangIntermediate->getStage() == EShLangTessEvaluation) {
490
491 builder.addExtension(spv::E_SPV_NV_viewport_array2);
492 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
493 }
chaoc771d89f2017-01-13 01:10:53 -0800494#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800495 }
John Kessenich92187592016-02-01 13:45:25 -0700496 return spv::BuiltInViewportIndex;
497
John Kessenich5e801132016-02-15 11:09:46 -0700498 case glslang::EbvSampleId:
499 builder.addCapability(spv::CapabilitySampleRateShading);
500 return spv::BuiltInSampleId;
501
502 case glslang::EbvSamplePosition:
503 builder.addCapability(spv::CapabilitySampleRateShading);
504 return spv::BuiltInSamplePosition;
505
506 case glslang::EbvSampleMask:
507 builder.addCapability(spv::CapabilitySampleRateShading);
508 return spv::BuiltInSampleMask;
509
John Kessenich78a45572016-07-08 14:05:15 -0600510 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800511 if (!memberDeclaration) {
512 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800513#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -0800514 if (glslangIntermediate->getStage() == EShLangVertex ||
515 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800516 glslangIntermediate->getStage() == EShLangTessEvaluation) {
517
chaoc771d89f2017-01-13 01:10:53 -0800518 builder.addExtension(spv::E_SPV_NV_viewport_array2);
519 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
520 }
chaoc771d89f2017-01-13 01:10:53 -0800521#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800522 }
523
John Kessenich78a45572016-07-08 14:05:15 -0600524 return spv::BuiltInLayer;
525
John Kessenich140f3df2015-06-26 16:58:36 -0600526 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600527 case glslang::EbvVertexId: return spv::BuiltInVertexId;
528 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700529 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
530 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800531
John Kessenichda581a22015-10-14 14:10:30 -0600532 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800533 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
534 builder.addCapability(spv::CapabilityDrawParameters);
535 return spv::BuiltInBaseVertex;
536
John Kessenichda581a22015-10-14 14:10:30 -0600537 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800538 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
539 builder.addCapability(spv::CapabilityDrawParameters);
540 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200541
John Kessenichda581a22015-10-14 14:10:30 -0600542 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800543 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
544 builder.addCapability(spv::CapabilityDrawParameters);
545 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200546
547 case glslang::EbvPrimitiveId:
548 if (glslangIntermediate->getStage() == EShLangFragment)
549 builder.addCapability(spv::CapabilityGeometry);
550 return spv::BuiltInPrimitiveId;
551
John Kessenich140f3df2015-06-26 16:58:36 -0600552 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600553 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
554 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
555 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
556 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
557 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
558 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
559 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600560 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
561 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
562 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
563 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
564 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
565 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
566 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
567 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800568
Rex Xu574ab042016-04-14 16:53:07 +0800569 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800570 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800571 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
572 return spv::BuiltInSubgroupSize;
573
Rex Xu574ab042016-04-14 16:53:07 +0800574 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800575 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800576 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
577 return spv::BuiltInSubgroupLocalInvocationId;
578
Rex Xu574ab042016-04-14 16:53:07 +0800579 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800580 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
581 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
582 return spv::BuiltInSubgroupEqMaskKHR;
583
Rex Xu574ab042016-04-14 16:53:07 +0800584 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800585 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
586 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
587 return spv::BuiltInSubgroupGeMaskKHR;
588
Rex Xu574ab042016-04-14 16:53:07 +0800589 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800590 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
591 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
592 return spv::BuiltInSubgroupGtMaskKHR;
593
Rex Xu574ab042016-04-14 16:53:07 +0800594 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800595 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
596 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
597 return spv::BuiltInSubgroupLeMaskKHR;
598
Rex Xu574ab042016-04-14 16:53:07 +0800599 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800600 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
601 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
602 return spv::BuiltInSubgroupLtMaskKHR;
603
Rex Xu9d93a232016-05-05 12:30:44 +0800604#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800605 case glslang::EbvBaryCoordNoPersp:
606 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
607 return spv::BuiltInBaryCoordNoPerspAMD;
608
609 case glslang::EbvBaryCoordNoPerspCentroid:
610 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
611 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
612
613 case glslang::EbvBaryCoordNoPerspSample:
614 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
615 return spv::BuiltInBaryCoordNoPerspSampleAMD;
616
617 case glslang::EbvBaryCoordSmooth:
618 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
619 return spv::BuiltInBaryCoordSmoothAMD;
620
621 case glslang::EbvBaryCoordSmoothCentroid:
622 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
623 return spv::BuiltInBaryCoordSmoothCentroidAMD;
624
625 case glslang::EbvBaryCoordSmoothSample:
626 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
627 return spv::BuiltInBaryCoordSmoothSampleAMD;
628
629 case glslang::EbvBaryCoordPullModel:
630 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
631 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800632#endif
chaoc771d89f2017-01-13 01:10:53 -0800633
John Kessenich6c8aaac2017-02-27 01:20:51 -0700634 case glslang::EbvDeviceIndex:
635 builder.addExtension(spv::E_SPV_KHR_device_group);
636 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700637 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700638
639 case glslang::EbvViewIndex:
640 builder.addExtension(spv::E_SPV_KHR_multiview);
641 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700642 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700643
chaoc771d89f2017-01-13 01:10:53 -0800644#ifdef NV_EXTENSIONS
645 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800646 if (!memberDeclaration) {
647 builder.addExtension(spv::E_SPV_NV_viewport_array2);
648 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
649 }
chaoc771d89f2017-01-13 01:10:53 -0800650 return spv::BuiltInViewportMaskNV;
651 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800652 if (!memberDeclaration) {
653 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
654 builder.addCapability(spv::CapabilityShaderStereoViewNV);
655 }
chaoc771d89f2017-01-13 01:10:53 -0800656 return spv::BuiltInSecondaryPositionNV;
657 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800658 if (!memberDeclaration) {
659 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
660 builder.addCapability(spv::CapabilityShaderStereoViewNV);
661 }
chaoc771d89f2017-01-13 01:10:53 -0800662 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800663 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800664 if (!memberDeclaration) {
665 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
666 builder.addCapability(spv::CapabilityPerViewAttributesNV);
667 }
chaocdf3956c2017-02-14 14:52:34 -0800668 return spv::BuiltInPositionPerViewNV;
669 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800670 if (!memberDeclaration) {
671 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
672 builder.addCapability(spv::CapabilityPerViewAttributesNV);
673 }
chaocdf3956c2017-02-14 14:52:34 -0800674 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800675#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800676 default:
677 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600678 }
679}
680
Rex Xufc618912015-09-09 16:42:49 +0800681// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700682spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800683{
684 assert(type.getBasicType() == glslang::EbtSampler);
685
John Kessenich5d0fa972016-02-15 11:57:00 -0700686 // Check for capabilities
687 switch (type.getQualifier().layoutFormat) {
688 case glslang::ElfRg32f:
689 case glslang::ElfRg16f:
690 case glslang::ElfR11fG11fB10f:
691 case glslang::ElfR16f:
692 case glslang::ElfRgba16:
693 case glslang::ElfRgb10A2:
694 case glslang::ElfRg16:
695 case glslang::ElfRg8:
696 case glslang::ElfR16:
697 case glslang::ElfR8:
698 case glslang::ElfRgba16Snorm:
699 case glslang::ElfRg16Snorm:
700 case glslang::ElfRg8Snorm:
701 case glslang::ElfR16Snorm:
702 case glslang::ElfR8Snorm:
703
704 case glslang::ElfRg32i:
705 case glslang::ElfRg16i:
706 case glslang::ElfRg8i:
707 case glslang::ElfR16i:
708 case glslang::ElfR8i:
709
710 case glslang::ElfRgb10a2ui:
711 case glslang::ElfRg32ui:
712 case glslang::ElfRg16ui:
713 case glslang::ElfRg8ui:
714 case glslang::ElfR16ui:
715 case glslang::ElfR8ui:
716 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
717 break;
718
719 default:
720 break;
721 }
722
723 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800724 switch (type.getQualifier().layoutFormat) {
725 case glslang::ElfNone: return spv::ImageFormatUnknown;
726 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
727 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
728 case glslang::ElfR32f: return spv::ImageFormatR32f;
729 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
730 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
731 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
732 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
733 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
734 case glslang::ElfR16f: return spv::ImageFormatR16f;
735 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
736 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
737 case glslang::ElfRg16: return spv::ImageFormatRg16;
738 case glslang::ElfRg8: return spv::ImageFormatRg8;
739 case glslang::ElfR16: return spv::ImageFormatR16;
740 case glslang::ElfR8: return spv::ImageFormatR8;
741 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
742 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
743 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
744 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
745 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
746 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
747 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
748 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
749 case glslang::ElfR32i: return spv::ImageFormatR32i;
750 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
751 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
752 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
753 case glslang::ElfR16i: return spv::ImageFormatR16i;
754 case glslang::ElfR8i: return spv::ImageFormatR8i;
755 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
756 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
757 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
758 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
759 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
760 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
761 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
762 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
763 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
764 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600765 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800766 }
767}
768
qining25262b32016-05-06 17:25:16 -0400769// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700770// descriptor set.
771bool IsDescriptorResource(const glslang::TType& type)
772{
John Kessenichf7497e22016-03-08 21:36:22 -0700773 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700774 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700775 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700776
777 // non block...
778 // basically samplerXXX/subpass/sampler/texture are all included
779 // if they are the global-scope-class, not the function parameter
780 // (or local, if they ever exist) class.
781 if (type.getBasicType() == glslang::EbtSampler)
782 return type.getQualifier().isUniformOrBuffer();
783
784 // None of the above.
785 return false;
786}
787
John Kesseniche0b6cad2015-12-24 10:30:13 -0700788void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
789{
790 if (child.layoutMatrix == glslang::ElmNone)
791 child.layoutMatrix = parent.layoutMatrix;
792
793 if (parent.invariant)
794 child.invariant = true;
795 if (parent.nopersp)
796 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800797#ifdef AMD_EXTENSIONS
798 if (parent.explicitInterp)
799 child.explicitInterp = true;
800#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700801 if (parent.flat)
802 child.flat = true;
803 if (parent.centroid)
804 child.centroid = true;
805 if (parent.patch)
806 child.patch = true;
807 if (parent.sample)
808 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800809 if (parent.coherent)
810 child.coherent = true;
811 if (parent.volatil)
812 child.volatil = true;
813 if (parent.restrict)
814 child.restrict = true;
815 if (parent.readonly)
816 child.readonly = true;
817 if (parent.writeonly)
818 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700819}
820
John Kessenichf2b7f332016-09-01 17:05:23 -0600821bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700822{
John Kessenich7b9fa252016-01-21 18:56:57 -0700823 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600824 // - struct members might inherit from a struct declaration
825 // (note that non-block structs don't explicitly inherit,
826 // only implicitly, meaning no decoration involved)
827 // - affect decorations on the struct members
828 // (note smooth does not, and expecting something like volatile
829 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700830 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600831 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700832}
833
John Kessenich140f3df2015-06-26 16:58:36 -0600834//
835// Implement the TGlslangToSpvTraverser class.
836//
837
Lei Zhang17535f72016-05-04 15:55:59 -0400838TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600839 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
840 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400841 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700842 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600843 glslangIntermediate(glslangIntermediate)
844{
845 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
846
847 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700848 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600849 stdBuiltins = builder.import("GLSL.std.450");
850 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600851 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
852 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600853
854 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600855 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
856 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600857 builder.addSourceExtension(it->c_str());
858
859 // Add the top-level modes for this shader.
860
John Kessenich92187592016-02-01 13:45:25 -0700861 if (glslangIntermediate->getXfbMode()) {
862 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600863 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700864 }
John Kessenich140f3df2015-06-26 16:58:36 -0600865
866 unsigned int mode;
867 switch (glslangIntermediate->getStage()) {
868 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600869 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600870 break;
871
872 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600873 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600874 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
875 break;
876
877 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600878 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600879 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700880 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
881 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
882 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600883 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600884 }
John Kessenich4016e382016-07-15 11:53:56 -0600885 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600886 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
887
John Kesseniche6903322015-10-13 16:29:02 -0600888 switch (glslangIntermediate->getVertexSpacing()) {
889 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
890 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
891 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600892 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600893 }
John Kessenich4016e382016-07-15 11:53:56 -0600894 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600895 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
896
897 switch (glslangIntermediate->getVertexOrder()) {
898 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
899 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600900 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600901 }
John Kessenich4016e382016-07-15 11:53:56 -0600902 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600903 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
904
905 if (glslangIntermediate->getPointMode())
906 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600907 break;
908
909 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600910 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600911 switch (glslangIntermediate->getInputPrimitive()) {
912 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
913 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
914 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700915 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600916 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600917 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600918 }
John Kessenich4016e382016-07-15 11:53:56 -0600919 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600920 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600921
John Kessenich140f3df2015-06-26 16:58:36 -0600922 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
923
924 switch (glslangIntermediate->getOutputPrimitive()) {
925 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
926 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
927 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600928 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600929 }
John Kessenich4016e382016-07-15 11:53:56 -0600930 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600931 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
932 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
933 break;
934
935 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600936 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600937 if (glslangIntermediate->getPixelCenterInteger())
938 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600939
John Kessenich140f3df2015-06-26 16:58:36 -0600940 if (glslangIntermediate->getOriginUpperLeft())
941 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600942 else
943 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600944
945 if (glslangIntermediate->getEarlyFragmentTests())
946 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
947
948 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600949 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
950 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600951 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600952 }
John Kessenich4016e382016-07-15 11:53:56 -0600953 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600954 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
955
956 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
957 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600958 break;
959
960 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600961 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600962 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
963 glslangIntermediate->getLocalSize(1),
964 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600965 break;
966
967 default:
968 break;
969 }
John Kessenich140f3df2015-06-26 16:58:36 -0600970}
971
John Kessenichfca82622016-11-26 13:23:20 -0700972// Finish creating SPV, after the traversal is complete.
973void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700974{
John Kessenich517fe7a2016-11-26 13:31:47 -0700975 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700976 builder.setBuildPoint(shaderEntry->getLastBlock());
977 builder.leaveFunction();
978 }
979
John Kessenich7ba63412015-12-20 17:37:07 -0700980 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100981 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
982 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700983
qiningda397332016-03-09 19:54:03 -0500984 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700985}
986
John Kessenichfca82622016-11-26 13:23:20 -0700987// Write the SPV into 'out'.
988void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -0600989{
John Kessenichfca82622016-11-26 13:23:20 -0700990 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -0600991}
992
993//
994// Implement the traversal functions.
995//
996// Return true from interior nodes to have the external traversal
997// continue on to children. Return false if children were
998// already processed.
999//
1000
1001//
qining25262b32016-05-06 17:25:16 -04001002// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001003// - uniform/input reads
1004// - output writes
1005// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1006// - something simple that degenerates into the last bullet
1007//
1008void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1009{
qining75d1d802016-04-06 14:42:01 -04001010 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1011 if (symbol->getType().getQualifier().isSpecConstant())
1012 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1013
John Kessenich140f3df2015-06-26 16:58:36 -06001014 // getSymbolId() will set up all the IO decorations on the first call.
1015 // Formal function parameters were mapped during makeFunctions().
1016 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001017
1018 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1019 if (builder.isPointer(id)) {
1020 spv::StorageClass sc = builder.getStorageClass(id);
1021 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1022 iOSet.insert(id);
1023 }
1024
1025 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001026 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001027 // Prepare to generate code for the access
1028
1029 // L-value chains will be computed left to right. We're on the symbol now,
1030 // which is the left-most part of the access chain, so now is "clear" time,
1031 // followed by setting the base.
1032 builder.clearAccessChain();
1033
1034 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001035 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001036 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001037 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001038 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001039 // These are also pure R-values.
1040 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001041 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001042 builder.setAccessChainRValue(id);
1043 else
1044 builder.setAccessChainLValue(id);
1045 }
1046}
1047
1048bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1049{
qining40887662016-04-03 22:20:42 -04001050 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1051 if (node->getType().getQualifier().isSpecConstant())
1052 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1053
John Kessenich140f3df2015-06-26 16:58:36 -06001054 // First, handle special cases
1055 switch (node->getOp()) {
1056 case glslang::EOpAssign:
1057 case glslang::EOpAddAssign:
1058 case glslang::EOpSubAssign:
1059 case glslang::EOpMulAssign:
1060 case glslang::EOpVectorTimesMatrixAssign:
1061 case glslang::EOpVectorTimesScalarAssign:
1062 case glslang::EOpMatrixTimesScalarAssign:
1063 case glslang::EOpMatrixTimesMatrixAssign:
1064 case glslang::EOpDivAssign:
1065 case glslang::EOpModAssign:
1066 case glslang::EOpAndAssign:
1067 case glslang::EOpInclusiveOrAssign:
1068 case glslang::EOpExclusiveOrAssign:
1069 case glslang::EOpLeftShiftAssign:
1070 case glslang::EOpRightShiftAssign:
1071 // A bin-op assign "a += b" means the same thing as "a = a + b"
1072 // where a is evaluated before b. For a simple assignment, GLSL
1073 // says to evaluate the left before the right. So, always, left
1074 // node then right node.
1075 {
1076 // get the left l-value, save it away
1077 builder.clearAccessChain();
1078 node->getLeft()->traverse(this);
1079 spv::Builder::AccessChain lValue = builder.getAccessChain();
1080
1081 // evaluate the right
1082 builder.clearAccessChain();
1083 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001084 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001085
1086 if (node->getOp() != glslang::EOpAssign) {
1087 // the left is also an r-value
1088 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001089 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001090
1091 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001092 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001093 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001094 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1095 node->getType().getBasicType());
1096
1097 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001098 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001099 }
1100
1101 // store the result
1102 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001103 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001104
1105 // assignments are expressions having an rValue after they are evaluated...
1106 builder.clearAccessChain();
1107 builder.setAccessChainRValue(rValue);
1108 }
1109 return false;
1110 case glslang::EOpIndexDirect:
1111 case glslang::EOpIndexDirectStruct:
1112 {
1113 // Get the left part of the access chain.
1114 node->getLeft()->traverse(this);
1115
1116 // Add the next element in the chain
1117
David Netoa901ffe2016-06-08 14:11:40 +01001118 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001119 if (! node->getLeft()->getType().isArray() &&
1120 node->getLeft()->getType().isVector() &&
1121 node->getOp() == glslang::EOpIndexDirect) {
1122 // This is essentially a hard-coded vector swizzle of size 1,
1123 // so short circuit the access-chain stuff with a swizzle.
1124 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001125 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001126 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001127 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001128 int spvIndex = glslangIndex;
1129 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1130 node->getOp() == glslang::EOpIndexDirectStruct)
1131 {
1132 // This may be, e.g., an anonymous block-member selection, which generally need
1133 // index remapping due to hidden members in anonymous blocks.
1134 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1135 assert(remapper.size() > 0);
1136 spvIndex = remapper[glslangIndex];
1137 }
John Kessenichebb50532016-05-16 19:22:05 -06001138
David Netoa901ffe2016-06-08 14:11:40 +01001139 // normal case for indexing array or structure or block
1140 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1141
1142 // Add capabilities here for accessing PointSize and clip/cull distance.
1143 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001144 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001145 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001146 }
1147 }
1148 return false;
1149 case glslang::EOpIndexIndirect:
1150 {
1151 // Structure or array or vector indirection.
1152 // Will use native SPIR-V access-chain for struct and array indirection;
1153 // matrices are arrays of vectors, so will also work for a matrix.
1154 // Will use the access chain's 'component' for variable index into a vector.
1155
1156 // This adapter is building access chains left to right.
1157 // Set up the access chain to the left.
1158 node->getLeft()->traverse(this);
1159
1160 // save it so that computing the right side doesn't trash it
1161 spv::Builder::AccessChain partial = builder.getAccessChain();
1162
1163 // compute the next index in the chain
1164 builder.clearAccessChain();
1165 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001166 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001167
1168 // restore the saved access chain
1169 builder.setAccessChain(partial);
1170
1171 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001172 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001173 else
John Kessenichfa668da2015-09-13 14:46:30 -06001174 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001175 }
1176 return false;
1177 case glslang::EOpVectorSwizzle:
1178 {
1179 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001180 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001181 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001182 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001183 }
1184 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001185 case glslang::EOpMatrixSwizzle:
1186 logger->missingFunctionality("matrix swizzle");
1187 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001188 case glslang::EOpLogicalOr:
1189 case glslang::EOpLogicalAnd:
1190 {
1191
1192 // These may require short circuiting, but can sometimes be done as straight
1193 // binary operations. The right operand must be short circuited if it has
1194 // side effects, and should probably be if it is complex.
1195 if (isTrivial(node->getRight()->getAsTyped()))
1196 break; // handle below as a normal binary operation
1197 // otherwise, we need to do dynamic short circuiting on the right operand
1198 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1199 builder.clearAccessChain();
1200 builder.setAccessChainRValue(result);
1201 }
1202 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001203 default:
1204 break;
1205 }
1206
1207 // Assume generic binary op...
1208
John Kessenich32cfd492016-02-02 12:37:46 -07001209 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001210 builder.clearAccessChain();
1211 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001212 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001213
John Kessenich32cfd492016-02-02 12:37:46 -07001214 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001215 builder.clearAccessChain();
1216 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001217 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001218
John Kessenich32cfd492016-02-02 12:37:46 -07001219 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001220 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001221 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001222 convertGlslangToSpvType(node->getType()), left, right,
1223 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001224
John Kessenich50e57562015-12-21 21:21:11 -07001225 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001226 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001227 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001228 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001229 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001230 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001231 return false;
1232 }
John Kessenich140f3df2015-06-26 16:58:36 -06001233}
1234
1235bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1236{
qining40887662016-04-03 22:20:42 -04001237 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1238 if (node->getType().getQualifier().isSpecConstant())
1239 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1240
John Kessenichfc51d282015-08-19 13:34:18 -06001241 spv::Id result = spv::NoResult;
1242
1243 // try texturing first
1244 result = createImageTextureFunctionCall(node);
1245 if (result != spv::NoResult) {
1246 builder.clearAccessChain();
1247 builder.setAccessChainRValue(result);
1248
1249 return false; // done with this node
1250 }
1251
1252 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001253
1254 if (node->getOp() == glslang::EOpArrayLength) {
1255 // Quite special; won't want to evaluate the operand.
1256
1257 // Normal .length() would have been constant folded by the front-end.
1258 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001259 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001260 assert(node->getOperand()->getType().isRuntimeSizedArray());
1261 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1262 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001263 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1264 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001265
1266 builder.clearAccessChain();
1267 builder.setAccessChainRValue(length);
1268
1269 return false;
1270 }
1271
John Kessenichfc51d282015-08-19 13:34:18 -06001272 // Start by evaluating the operand
1273
John Kessenich8c8505c2016-07-26 12:50:38 -06001274 // Does it need a swizzle inversion? If so, evaluation is inverted;
1275 // operate first on the swizzle base, then apply the swizzle.
1276 spv::Id invertedType = spv::NoType;
1277 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1278 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1279 invertedType = getInvertedSwizzleType(*node->getOperand());
1280
John Kessenich140f3df2015-06-26 16:58:36 -06001281 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001282 if (invertedType != spv::NoType)
1283 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1284 else
1285 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001286
Rex Xufc618912015-09-09 16:42:49 +08001287 spv::Id operand = spv::NoResult;
1288
1289 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1290 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001291 node->getOp() == glslang::EOpAtomicCounter ||
1292 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001293 operand = builder.accessChainGetLValue(); // Special case l-value operands
1294 else
John Kessenich32cfd492016-02-02 12:37:46 -07001295 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001296
John Kessenichf6640762016-08-01 19:44:00 -06001297 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001298 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001299
1300 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001301 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001302 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001303
1304 // if not, then possibly an operation
1305 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001306 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001307
1308 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001309 if (invertedType)
1310 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1311
John Kessenich140f3df2015-06-26 16:58:36 -06001312 builder.clearAccessChain();
1313 builder.setAccessChainRValue(result);
1314
1315 return false; // done with this node
1316 }
1317
1318 // it must be a special case, check...
1319 switch (node->getOp()) {
1320 case glslang::EOpPostIncrement:
1321 case glslang::EOpPostDecrement:
1322 case glslang::EOpPreIncrement:
1323 case glslang::EOpPreDecrement:
1324 {
1325 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001326 spv::Id one = 0;
1327 if (node->getBasicType() == glslang::EbtFloat)
1328 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001329 else if (node->getBasicType() == glslang::EbtDouble)
1330 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001331#ifdef AMD_EXTENSIONS
1332 else if (node->getBasicType() == glslang::EbtFloat16)
1333 one = builder.makeFloat16Constant(1.0F);
1334#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001335 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1336 one = builder.makeInt64Constant(1);
1337 else
1338 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001339 glslang::TOperator op;
1340 if (node->getOp() == glslang::EOpPreIncrement ||
1341 node->getOp() == glslang::EOpPostIncrement)
1342 op = glslang::EOpAdd;
1343 else
1344 op = glslang::EOpSub;
1345
John Kessenichf6640762016-08-01 19:44:00 -06001346 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001347 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001348 convertGlslangToSpvType(node->getType()), operand, one,
1349 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001350 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001351
1352 // The result of operation is always stored, but conditionally the
1353 // consumed result. The consumed result is always an r-value.
1354 builder.accessChainStore(result);
1355 builder.clearAccessChain();
1356 if (node->getOp() == glslang::EOpPreIncrement ||
1357 node->getOp() == glslang::EOpPreDecrement)
1358 builder.setAccessChainRValue(result);
1359 else
1360 builder.setAccessChainRValue(operand);
1361 }
1362
1363 return false;
1364
1365 case glslang::EOpEmitStreamVertex:
1366 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1367 return false;
1368 case glslang::EOpEndStreamPrimitive:
1369 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1370 return false;
1371
1372 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001373 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001374 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001375 }
John Kessenich140f3df2015-06-26 16:58:36 -06001376}
1377
1378bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1379{
qining27e04a02016-04-14 16:40:20 -04001380 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1381 if (node->getType().getQualifier().isSpecConstant())
1382 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1383
John Kessenichfc51d282015-08-19 13:34:18 -06001384 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001385 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1386 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001387
1388 // try texturing
1389 result = createImageTextureFunctionCall(node);
1390 if (result != spv::NoResult) {
1391 builder.clearAccessChain();
1392 builder.setAccessChainRValue(result);
1393
1394 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001395 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001396 // "imageStore" is a special case, which has no result
1397 return false;
1398 }
John Kessenichfc51d282015-08-19 13:34:18 -06001399
John Kessenich140f3df2015-06-26 16:58:36 -06001400 glslang::TOperator binOp = glslang::EOpNull;
1401 bool reduceComparison = true;
1402 bool isMatrix = false;
1403 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001404 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001405
1406 assert(node->getOp());
1407
John Kessenichf6640762016-08-01 19:44:00 -06001408 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001409
1410 switch (node->getOp()) {
1411 case glslang::EOpSequence:
1412 {
1413 if (preVisit)
1414 ++sequenceDepth;
1415 else
1416 --sequenceDepth;
1417
1418 if (sequenceDepth == 1) {
1419 // If this is the parent node of all the functions, we want to see them
1420 // early, so all call points have actual SPIR-V functions to reference.
1421 // In all cases, still let the traverser visit the children for us.
1422 makeFunctions(node->getAsAggregate()->getSequence());
1423
John Kessenich6fccb3c2016-09-19 16:01:41 -06001424 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001425 // anything else gets there, so visit out of order, doing them all now.
1426 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1427
John Kessenich6a60c2f2016-12-08 21:01:59 -07001428 // Initializers are done, don't want to visit again, but functions and link objects need to be processed,
John Kessenich140f3df2015-06-26 16:58:36 -06001429 // so do them manually.
1430 visitFunctions(node->getAsAggregate()->getSequence());
1431
1432 return false;
1433 }
1434
1435 return true;
1436 }
1437 case glslang::EOpLinkerObjects:
1438 {
1439 if (visit == glslang::EvPreVisit)
1440 linkageOnly = true;
1441 else
1442 linkageOnly = false;
1443
1444 return true;
1445 }
1446 case glslang::EOpComma:
1447 {
1448 // processing from left to right naturally leaves the right-most
1449 // lying around in the access chain
1450 glslang::TIntermSequence& glslangOperands = node->getSequence();
1451 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1452 glslangOperands[i]->traverse(this);
1453
1454 return false;
1455 }
1456 case glslang::EOpFunction:
1457 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001458 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001459 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001460 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001461 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001462 } else {
1463 handleFunctionEntry(node);
1464 }
1465 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001466 if (inEntryPoint)
1467 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001468 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001469 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001470 }
1471
1472 return true;
1473 case glslang::EOpParameters:
1474 // Parameters will have been consumed by EOpFunction processing, but not
1475 // the body, so we still visited the function node's children, making this
1476 // child redundant.
1477 return false;
1478 case glslang::EOpFunctionCall:
1479 {
1480 if (node->isUserDefined())
1481 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001482 // assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
John Kessenich6c292d32016-02-15 20:58:50 -07001483 if (result) {
1484 builder.clearAccessChain();
1485 builder.setAccessChainRValue(result);
1486 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001487 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001488
1489 return false;
1490 }
1491 case glslang::EOpConstructMat2x2:
1492 case glslang::EOpConstructMat2x3:
1493 case glslang::EOpConstructMat2x4:
1494 case glslang::EOpConstructMat3x2:
1495 case glslang::EOpConstructMat3x3:
1496 case glslang::EOpConstructMat3x4:
1497 case glslang::EOpConstructMat4x2:
1498 case glslang::EOpConstructMat4x3:
1499 case glslang::EOpConstructMat4x4:
1500 case glslang::EOpConstructDMat2x2:
1501 case glslang::EOpConstructDMat2x3:
1502 case glslang::EOpConstructDMat2x4:
1503 case glslang::EOpConstructDMat3x2:
1504 case glslang::EOpConstructDMat3x3:
1505 case glslang::EOpConstructDMat3x4:
1506 case glslang::EOpConstructDMat4x2:
1507 case glslang::EOpConstructDMat4x3:
1508 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001509#ifdef AMD_EXTENSIONS
1510 case glslang::EOpConstructF16Mat2x2:
1511 case glslang::EOpConstructF16Mat2x3:
1512 case glslang::EOpConstructF16Mat2x4:
1513 case glslang::EOpConstructF16Mat3x2:
1514 case glslang::EOpConstructF16Mat3x3:
1515 case glslang::EOpConstructF16Mat3x4:
1516 case glslang::EOpConstructF16Mat4x2:
1517 case glslang::EOpConstructF16Mat4x3:
1518 case glslang::EOpConstructF16Mat4x4:
1519#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001520 isMatrix = true;
1521 // fall through
1522 case glslang::EOpConstructFloat:
1523 case glslang::EOpConstructVec2:
1524 case glslang::EOpConstructVec3:
1525 case glslang::EOpConstructVec4:
1526 case glslang::EOpConstructDouble:
1527 case glslang::EOpConstructDVec2:
1528 case glslang::EOpConstructDVec3:
1529 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001530#ifdef AMD_EXTENSIONS
1531 case glslang::EOpConstructFloat16:
1532 case glslang::EOpConstructF16Vec2:
1533 case glslang::EOpConstructF16Vec3:
1534 case glslang::EOpConstructF16Vec4:
1535#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001536 case glslang::EOpConstructBool:
1537 case glslang::EOpConstructBVec2:
1538 case glslang::EOpConstructBVec3:
1539 case glslang::EOpConstructBVec4:
1540 case glslang::EOpConstructInt:
1541 case glslang::EOpConstructIVec2:
1542 case glslang::EOpConstructIVec3:
1543 case glslang::EOpConstructIVec4:
1544 case glslang::EOpConstructUint:
1545 case glslang::EOpConstructUVec2:
1546 case glslang::EOpConstructUVec3:
1547 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001548 case glslang::EOpConstructInt64:
1549 case glslang::EOpConstructI64Vec2:
1550 case glslang::EOpConstructI64Vec3:
1551 case glslang::EOpConstructI64Vec4:
1552 case glslang::EOpConstructUint64:
1553 case glslang::EOpConstructU64Vec2:
1554 case glslang::EOpConstructU64Vec3:
1555 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001556 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001557 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001558 {
1559 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001560 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001561 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001562 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001563 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001564 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001565 std::vector<spv::Id> constituents;
1566 for (int c = 0; c < (int)arguments.size(); ++c)
1567 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001568 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001569 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001570 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001571 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001572 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001573
1574 builder.clearAccessChain();
1575 builder.setAccessChainRValue(constructed);
1576
1577 return false;
1578 }
1579
1580 // These six are component-wise compares with component-wise results.
1581 // Forward on to createBinaryOperation(), requesting a vector result.
1582 case glslang::EOpLessThan:
1583 case glslang::EOpGreaterThan:
1584 case glslang::EOpLessThanEqual:
1585 case glslang::EOpGreaterThanEqual:
1586 case glslang::EOpVectorEqual:
1587 case glslang::EOpVectorNotEqual:
1588 {
1589 // Map the operation to a binary
1590 binOp = node->getOp();
1591 reduceComparison = false;
1592 switch (node->getOp()) {
1593 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1594 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1595 default: binOp = node->getOp(); break;
1596 }
1597
1598 break;
1599 }
1600 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001601 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001602 binOp = glslang::EOpMul;
1603 break;
1604 case glslang::EOpOuterProduct:
1605 // two vectors multiplied to make a matrix
1606 binOp = glslang::EOpOuterProduct;
1607 break;
1608 case glslang::EOpDot:
1609 {
qining25262b32016-05-06 17:25:16 -04001610 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001611 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001612 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001613 binOp = glslang::EOpMul;
1614 break;
1615 }
1616 case glslang::EOpMod:
1617 // when an aggregate, this is the floating-point mod built-in function,
1618 // which can be emitted by the one in createBinaryOperation()
1619 binOp = glslang::EOpMod;
1620 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001621 case glslang::EOpEmitVertex:
1622 case glslang::EOpEndPrimitive:
1623 case glslang::EOpBarrier:
1624 case glslang::EOpMemoryBarrier:
1625 case glslang::EOpMemoryBarrierAtomicCounter:
1626 case glslang::EOpMemoryBarrierBuffer:
1627 case glslang::EOpMemoryBarrierImage:
1628 case glslang::EOpMemoryBarrierShared:
1629 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001630 case glslang::EOpAllMemoryBarrierWithGroupSync:
1631 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1632 case glslang::EOpWorkgroupMemoryBarrier:
1633 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001634 noReturnValue = true;
1635 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1636 break;
1637
John Kessenich426394d2015-07-23 10:22:48 -06001638 case glslang::EOpAtomicAdd:
1639 case glslang::EOpAtomicMin:
1640 case glslang::EOpAtomicMax:
1641 case glslang::EOpAtomicAnd:
1642 case glslang::EOpAtomicOr:
1643 case glslang::EOpAtomicXor:
1644 case glslang::EOpAtomicExchange:
1645 case glslang::EOpAtomicCompSwap:
1646 atomic = true;
1647 break;
1648
John Kessenich140f3df2015-06-26 16:58:36 -06001649 default:
1650 break;
1651 }
1652
1653 //
1654 // See if it maps to a regular operation.
1655 //
John Kessenich140f3df2015-06-26 16:58:36 -06001656 if (binOp != glslang::EOpNull) {
1657 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1658 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1659 assert(left && right);
1660
1661 builder.clearAccessChain();
1662 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001663 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001664
1665 builder.clearAccessChain();
1666 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001667 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001668
qining25262b32016-05-06 17:25:16 -04001669 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001670 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001671 left->getType().getBasicType(), reduceComparison);
1672
1673 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001674 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001675 builder.clearAccessChain();
1676 builder.setAccessChainRValue(result);
1677
1678 return false;
1679 }
1680
John Kessenich426394d2015-07-23 10:22:48 -06001681 //
1682 // Create the list of operands.
1683 //
John Kessenich140f3df2015-06-26 16:58:36 -06001684 glslang::TIntermSequence& glslangOperands = node->getSequence();
1685 std::vector<spv::Id> operands;
1686 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001687 // special case l-value operands; there are just a few
1688 bool lvalue = false;
1689 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001690 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001691 case glslang::EOpModf:
1692 if (arg == 1)
1693 lvalue = true;
1694 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001695 case glslang::EOpInterpolateAtSample:
1696 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001697#ifdef AMD_EXTENSIONS
1698 case glslang::EOpInterpolateAtVertex:
1699#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001700 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001701 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001702
1703 // Does it need a swizzle inversion? If so, evaluation is inverted;
1704 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001705 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001706 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1707 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1708 }
Rex Xu7a26c172015-12-08 17:12:09 +08001709 break;
Rex Xud4782c12015-09-06 16:30:11 +08001710 case glslang::EOpAtomicAdd:
1711 case glslang::EOpAtomicMin:
1712 case glslang::EOpAtomicMax:
1713 case glslang::EOpAtomicAnd:
1714 case glslang::EOpAtomicOr:
1715 case glslang::EOpAtomicXor:
1716 case glslang::EOpAtomicExchange:
1717 case glslang::EOpAtomicCompSwap:
1718 if (arg == 0)
1719 lvalue = true;
1720 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001721 case glslang::EOpAddCarry:
1722 case glslang::EOpSubBorrow:
1723 if (arg == 2)
1724 lvalue = true;
1725 break;
1726 case glslang::EOpUMulExtended:
1727 case glslang::EOpIMulExtended:
1728 if (arg >= 2)
1729 lvalue = true;
1730 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001731 default:
1732 break;
1733 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001734 builder.clearAccessChain();
1735 if (invertedType != spv::NoType && arg == 0)
1736 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1737 else
1738 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001739 if (lvalue)
1740 operands.push_back(builder.accessChainGetLValue());
1741 else
John Kessenich32cfd492016-02-02 12:37:46 -07001742 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001743 }
John Kessenich426394d2015-07-23 10:22:48 -06001744
1745 if (atomic) {
1746 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001747 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001748 } else {
1749 // Pass through to generic operations.
1750 switch (glslangOperands.size()) {
1751 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001752 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001753 break;
1754 case 1:
qining25262b32016-05-06 17:25:16 -04001755 result = createUnaryOperation(
1756 node->getOp(), precision,
1757 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001758 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001759 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001760 break;
1761 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001762 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001763 break;
1764 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001765 if (invertedType)
1766 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001767 }
1768
1769 if (noReturnValue)
1770 return false;
1771
1772 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001773 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001774 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001775 } else {
1776 builder.clearAccessChain();
1777 builder.setAccessChainRValue(result);
1778 return false;
1779 }
1780}
1781
John Kessenich433e9ff2017-01-26 20:31:11 -07001782// This path handles both if-then-else and ?:
1783// The if-then-else has a node type of void, while
1784// ?: has either a void or a non-void node type
1785//
1786// Leaving the result, when not void:
1787// GLSL only has r-values as the result of a :?, but
1788// if we have an l-value, that can be more efficient if it will
1789// become the base of a complex r-value expression, because the
1790// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001791bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1792{
John Kessenich433e9ff2017-01-26 20:31:11 -07001793 // See if it simple and safe to generate OpSelect instead of using control flow.
1794 // Crucially, side effects must be avoided, and there are performance trade-offs.
1795 // Return true if good idea (and safe) for OpSelect, false otherwise.
1796 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001797 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1798 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001799 return false;
1800
1801 if (node->getTrueBlock() == nullptr ||
1802 node->getFalseBlock() == nullptr)
1803 return false;
1804
1805 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1806 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1807
1808 // return true if a single operand to ? : is okay for OpSelect
1809 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001810 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001811 };
1812
1813 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1814 operandOkay(node->getFalseBlock()->getAsTyped());
1815 };
1816
1817 // Emit OpSelect for this selection.
1818 const auto handleAsOpSelect = [&]() {
1819 node->getCondition()->traverse(this);
1820 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1821 node->getTrueBlock()->traverse(this);
1822 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1823 node->getFalseBlock()->traverse(this);
1824 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1825
John Kesseniche434ad92017-03-30 10:09:28 -06001826 // smear condition to vector, if necessary (AST is always scalar)
1827 if (builder.isVector(trueValue))
1828 condition = builder.smearScalar(spv::NoPrecision, condition,
1829 builder.makeVectorType(builder.makeBoolType(),
1830 builder.getNumComponents(trueValue)));
1831
1832 spv::Id select = builder.createTriOp(spv::OpSelect,
1833 convertGlslangToSpvType(node->getType()), condition,
1834 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001835 builder.clearAccessChain();
1836 builder.setAccessChainRValue(select);
1837 };
1838
1839 // Try for OpSelect
1840
1841 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001842 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1843 if (node->getType().getQualifier().isSpecConstant())
1844 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1845
John Kessenich433e9ff2017-01-26 20:31:11 -07001846 handleAsOpSelect();
1847 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001848 }
1849
John Kessenich433e9ff2017-01-26 20:31:11 -07001850 // Instead, emit control flow...
1851
1852 // Don't handle results as temporaries, because there will be two names
1853 // and better to leave SSA to later passes.
1854 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1855 ? spv::NoResult
1856 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1857
John Kessenich140f3df2015-06-26 16:58:36 -06001858 // emit the condition before doing anything with selection
1859 node->getCondition()->traverse(this);
1860
1861 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001862 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001863
John Kessenich433e9ff2017-01-26 20:31:11 -07001864 // emit the "then" statement
1865 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001866 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001867 if (result != spv::NoResult)
1868 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001869 }
1870
John Kessenich433e9ff2017-01-26 20:31:11 -07001871 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001872 ifBuilder.makeBeginElse();
1873 // emit the "else" statement
1874 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001875 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001876 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001877 }
1878
John Kessenich433e9ff2017-01-26 20:31:11 -07001879 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001880 ifBuilder.makeEndIf();
1881
John Kessenich433e9ff2017-01-26 20:31:11 -07001882 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001883 // GLSL only has r-values as the result of a :?, but
1884 // if we have an l-value, that can be more efficient if it will
1885 // become the base of a complex r-value expression, because the
1886 // next layer copies r-values into memory to use the access-chain mechanism
1887 builder.clearAccessChain();
1888 builder.setAccessChainLValue(result);
1889 }
1890
1891 return false;
1892}
1893
1894bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1895{
1896 // emit and get the condition before doing anything with switch
1897 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001898 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001899
1900 // browse the children to sort out code segments
1901 int defaultSegment = -1;
1902 std::vector<TIntermNode*> codeSegments;
1903 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1904 std::vector<int> caseValues;
1905 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1906 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1907 TIntermNode* child = *c;
1908 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001909 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001910 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001911 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001912 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1913 } else
1914 codeSegments.push_back(child);
1915 }
1916
qining25262b32016-05-06 17:25:16 -04001917 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001918 // statements between the last case and the end of the switch statement
1919 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1920 (int)codeSegments.size() == defaultSegment)
1921 codeSegments.push_back(nullptr);
1922
1923 // make the switch statement
1924 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001925 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001926
1927 // emit all the code in the segments
1928 breakForLoop.push(false);
1929 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1930 builder.nextSwitchSegment(segmentBlocks, s);
1931 if (codeSegments[s])
1932 codeSegments[s]->traverse(this);
1933 else
1934 builder.addSwitchBreak();
1935 }
1936 breakForLoop.pop();
1937
1938 builder.endSwitch(segmentBlocks);
1939
1940 return false;
1941}
1942
1943void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1944{
1945 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001946 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001947
1948 builder.clearAccessChain();
1949 builder.setAccessChainRValue(constant);
1950}
1951
1952bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1953{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001954 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001955 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001956 // Spec requires back edges to target header blocks, and every header block
1957 // must dominate its merge block. Make a header block first to ensure these
1958 // conditions are met. By definition, it will contain OpLoopMerge, followed
1959 // by a block-ending branch. But we don't want to put any other body/test
1960 // instructions in it, since the body/test may have arbitrary instructions,
1961 // including merges of its own.
1962 builder.setBuildPoint(&blocks.head);
1963 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001964 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001965 spv::Block& test = builder.makeNewBlock();
1966 builder.createBranch(&test);
1967
1968 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001969 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001970 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001971 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001972 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1973
1974 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001975 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001976 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001977 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001978 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001979 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001980
1981 builder.setBuildPoint(&blocks.continue_target);
1982 if (node->getTerminal())
1983 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001984 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001985 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001986 builder.createBranch(&blocks.body);
1987
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001988 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001989 builder.setBuildPoint(&blocks.body);
1990 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001991 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001992 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001993 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001994
1995 builder.setBuildPoint(&blocks.continue_target);
1996 if (node->getTerminal())
1997 node->getTerminal()->traverse(this);
1998 if (node->getTest()) {
1999 node->getTest()->traverse(this);
2000 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002001 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002002 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002003 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002004 // TODO: unless there was a break/return/discard instruction
2005 // somewhere in the body, this is an infinite loop, so we should
2006 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002007 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002008 }
John Kessenich140f3df2015-06-26 16:58:36 -06002009 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002010 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002011 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002012 return false;
2013}
2014
2015bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2016{
2017 if (node->getExpression())
2018 node->getExpression()->traverse(this);
2019
2020 switch (node->getFlowOp()) {
2021 case glslang::EOpKill:
2022 builder.makeDiscard();
2023 break;
2024 case glslang::EOpBreak:
2025 if (breakForLoop.top())
2026 builder.createLoopExit();
2027 else
2028 builder.addSwitchBreak();
2029 break;
2030 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002031 builder.createLoopContinue();
2032 break;
2033 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002034 if (node->getExpression()) {
2035 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2036 spv::Id returnId = accessChainLoad(glslangReturnType);
2037 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2038 builder.clearAccessChain();
2039 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2040 builder.setAccessChainLValue(copyId);
2041 multiTypeStore(glslangReturnType, returnId);
2042 returnId = builder.createLoad(copyId);
2043 }
2044 builder.makeReturn(false, returnId);
2045 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002046 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002047
2048 builder.clearAccessChain();
2049 break;
2050
2051 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002052 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002053 break;
2054 }
2055
2056 return false;
2057}
2058
2059spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2060{
qining25262b32016-05-06 17:25:16 -04002061 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002062 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002063 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002064 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002065 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002066 }
2067
2068 // Now, handle actual variables
2069 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
2070 spv::Id spvType = convertGlslangToSpvType(node->getType());
2071
2072 const char* name = node->getName().c_str();
2073 if (glslang::IsAnonymous(name))
2074 name = "";
2075
2076 return builder.createVariable(storageClass, spvType, name);
2077}
2078
2079// Return type Id of the sampled type.
2080spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2081{
2082 switch (sampler.type) {
2083 case glslang::EbtFloat: return builder.makeFloatType(32);
2084 case glslang::EbtInt: return builder.makeIntType(32);
2085 case glslang::EbtUint: return builder.makeUintType(32);
2086 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002087 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002088 return builder.makeFloatType(32);
2089 }
2090}
2091
John Kessenich8c8505c2016-07-26 12:50:38 -06002092// If node is a swizzle operation, return the type that should be used if
2093// the swizzle base is first consumed by another operation, before the swizzle
2094// is applied.
2095spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2096{
John Kessenichecba76f2017-01-06 00:34:48 -07002097 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002098 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2099 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2100 else
2101 return spv::NoType;
2102}
2103
2104// When inverting a swizzle with a parent op, this function
2105// will apply the swizzle operation to a completed parent operation.
2106spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2107{
2108 std::vector<unsigned> swizzle;
2109 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2110 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2111}
2112
John Kessenich8c8505c2016-07-26 12:50:38 -06002113// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2114void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2115{
2116 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2117 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2118 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2119}
2120
John Kessenich3ac051e2015-12-20 11:29:16 -07002121// Convert from a glslang type to an SPV type, by calling into a
2122// recursive version of this function. This establishes the inherited
2123// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002124spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2125{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002126 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002127}
2128
2129// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002130// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002131// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002132spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002133{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002134 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002135
2136 switch (type.getBasicType()) {
2137 case glslang::EbtVoid:
2138 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002139 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002140 break;
2141 case glslang::EbtFloat:
2142 spvType = builder.makeFloatType(32);
2143 break;
2144 case glslang::EbtDouble:
2145 spvType = builder.makeFloatType(64);
2146 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002147#ifdef AMD_EXTENSIONS
2148 case glslang::EbtFloat16:
2149 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002150 spvType = builder.makeFloatType(16);
2151 break;
2152#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002153 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002154 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2155 // a 32-bit int where non-0 means true.
2156 if (explicitLayout != glslang::ElpNone)
2157 spvType = builder.makeUintType(32);
2158 else
2159 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002160 break;
2161 case glslang::EbtInt:
2162 spvType = builder.makeIntType(32);
2163 break;
2164 case glslang::EbtUint:
2165 spvType = builder.makeUintType(32);
2166 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002167 case glslang::EbtInt64:
2168 builder.addCapability(spv::CapabilityInt64);
2169 spvType = builder.makeIntType(64);
2170 break;
2171 case glslang::EbtUint64:
2172 builder.addCapability(spv::CapabilityInt64);
2173 spvType = builder.makeUintType(64);
2174 break;
John Kessenich426394d2015-07-23 10:22:48 -06002175 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002176 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002177 spvType = builder.makeUintType(32);
2178 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002179 case glslang::EbtSampler:
2180 {
2181 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002182 if (sampler.sampler) {
2183 // pure sampler
2184 spvType = builder.makeSamplerType();
2185 } else {
2186 // an image is present, make its type
2187 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2188 sampler.image ? 2 : 1, TranslateImageFormat(type));
2189 if (sampler.combined) {
2190 // already has both image and sampler, make the combined type
2191 spvType = builder.makeSampledImageType(spvType);
2192 }
John Kessenich55e7d112015-11-15 21:33:39 -07002193 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002194 }
John Kessenich140f3df2015-06-26 16:58:36 -06002195 break;
2196 case glslang::EbtStruct:
2197 case glslang::EbtBlock:
2198 {
2199 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002200 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002201
2202 // Try to share structs for different layouts, but not yet for other
2203 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002204 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002205 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002206 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002207 break;
2208
2209 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002210 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002211 memberRemapper[glslangMembers].resize(glslangMembers->size());
2212 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002213 }
2214 break;
2215 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002216 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002217 break;
2218 }
2219
2220 if (type.isMatrix())
2221 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2222 else {
2223 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2224 if (type.getVectorSize() > 1)
2225 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2226 }
2227
2228 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002229 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2230
John Kessenichc9a80832015-09-12 12:17:44 -06002231 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002232 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002233 // We need to decorate array strides for types needing explicit layout, except blocks.
2234 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002235 // Use a dummy glslang type for querying internal strides of
2236 // arrays of arrays, but using just a one-dimensional array.
2237 glslang::TType simpleArrayType(type, 0); // deference type of the array
2238 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2239 simpleArrayType.getArraySizes().dereference();
2240
2241 // Will compute the higher-order strides here, rather than making a whole
2242 // pile of types and doing repetitive recursion on their contents.
2243 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2244 }
John Kessenichf8842e52016-01-04 19:22:56 -07002245
2246 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002247 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002248 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002249 if (stride > 0)
2250 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002251 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002252 }
2253 } else {
2254 // single-dimensional array, and don't yet have stride
2255
John Kessenichf8842e52016-01-04 19:22:56 -07002256 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002257 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2258 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002259 }
John Kessenich31ed4832015-09-09 17:51:38 -06002260
John Kessenichc9a80832015-09-12 12:17:44 -06002261 // Do the outer dimension, which might not be known for a runtime-sized array
2262 if (type.isRuntimeSizedArray()) {
2263 spvType = builder.makeRuntimeArray(spvType);
2264 } else {
2265 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002266 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002267 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002268 if (stride > 0)
2269 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002270 }
2271
2272 return spvType;
2273}
2274
John Kessenich0e737842017-03-24 18:38:16 -06002275// TODO: this functionality should exist at a higher level, in creating the AST
2276//
2277// Identify interface members that don't have their required extension turned on.
2278//
2279bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2280{
2281 auto& extensions = glslangIntermediate->getRequestedExtensions();
2282
Rex Xubcf291a2017-03-29 23:01:36 +08002283 if (member.getFieldName() == "gl_ViewportMask" &&
2284 extensions.find("GL_NV_viewport_array2") == extensions.end())
2285 return true;
2286 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2287 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2288 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002289 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2290 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2291 return true;
2292 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2293 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2294 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002295 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2296 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2297 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002298
2299 return false;
2300};
2301
John Kessenich6090df02016-06-30 21:18:02 -06002302// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2303// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2304// Mutually recursive with convertGlslangToSpvType().
2305spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2306 const glslang::TTypeList* glslangMembers,
2307 glslang::TLayoutPacking explicitLayout,
2308 const glslang::TQualifier& qualifier)
2309{
2310 // Create a vector of struct types for SPIR-V to consume
2311 std::vector<spv::Id> spvMembers;
2312 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2313 int locationOffset = 0; // for use across struct members, when they are called recursively
2314 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2315 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2316 if (glslangMember.hiddenMember()) {
2317 ++memberDelta;
2318 if (type.getBasicType() == glslang::EbtBlock)
2319 memberRemapper[glslangMembers][i] = -1;
2320 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002321 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002322 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002323 if (filterMember(glslangMember))
2324 continue;
2325 }
John Kessenich6090df02016-06-30 21:18:02 -06002326 // modify just this child's view of the qualifier
2327 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2328 InheritQualifiers(memberQualifier, qualifier);
2329
2330 // manually inherit location; it's more complex
2331 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2332 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2333 if (qualifier.hasLocation())
2334 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2335
2336 // recurse
2337 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2338 }
2339 }
2340
2341 // Make the SPIR-V type
2342 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002343 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002344 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2345
2346 // Decorate it
2347 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2348
2349 return spvType;
2350}
2351
2352void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2353 const glslang::TTypeList* glslangMembers,
2354 glslang::TLayoutPacking explicitLayout,
2355 const glslang::TQualifier& qualifier,
2356 spv::Id spvType)
2357{
2358 // Name and decorate the non-hidden members
2359 int offset = -1;
2360 int locationOffset = 0; // for use within the members of this struct
2361 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2362 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2363 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002364 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002365 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002366 if (filterMember(glslangMember))
2367 continue;
2368 }
John Kessenich6090df02016-06-30 21:18:02 -06002369
2370 // modify just this child's view of the qualifier
2371 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2372 InheritQualifiers(memberQualifier, qualifier);
2373
2374 // using -1 above to indicate a hidden member
2375 if (member >= 0) {
2376 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2377 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2378 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2379 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002380 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2381 type.getQualifier().storage == glslang::EvqVaryingOut) {
2382 if (type.getBasicType() == glslang::EbtBlock ||
2383 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002384 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2385 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2386 }
2387 }
2388 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2389
2390 if (qualifier.storage == glslang::EvqBuffer) {
2391 std::vector<spv::Decoration> memory;
2392 TranslateMemoryDecoration(memberQualifier, memory);
2393 for (unsigned int i = 0; i < memory.size(); ++i)
2394 addMemberDecoration(spvType, member, memory[i]);
2395 }
2396
John Kessenich2f47bc92016-06-30 21:47:35 -06002397 // Compute location decoration; tricky based on whether inheritance is at play and
2398 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002399 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2400 // probably move to the linker stage of the front end proper, and just have the
2401 // answer sitting already distributed throughout the individual member locations.
2402 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002403 // Ignore member locations if the container is an array, as that's
2404 // ill-specified and decisions have been made to not allow this anyway.
2405 // The object itself must have a location, and that comes out from decorating the object,
2406 // not the type (this code decorates types).
2407 if (! type.isArray()) {
2408 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2409 // struct members should not have explicit locations
2410 assert(type.getBasicType() != glslang::EbtStruct);
2411 location = memberQualifier.layoutLocation;
2412 } else if (type.getBasicType() != glslang::EbtBlock) {
2413 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2414 // The members, and their nested types, must not themselves have Location decorations.
2415 } else if (qualifier.hasLocation()) // inheritance
2416 location = qualifier.layoutLocation + locationOffset;
2417 }
John Kessenich6090df02016-06-30 21:18:02 -06002418 if (location >= 0)
2419 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2420
John Kessenich2f47bc92016-06-30 21:47:35 -06002421 if (qualifier.hasLocation()) // track for upcoming inheritance
2422 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2423
John Kessenich6090df02016-06-30 21:18:02 -06002424 // component, XFB, others
2425 if (glslangMember.getQualifier().hasComponent())
2426 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2427 if (glslangMember.getQualifier().hasXfbOffset())
2428 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2429 else if (explicitLayout != glslang::ElpNone) {
2430 // figure out what to do with offset, which is accumulating
2431 int nextOffset;
2432 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2433 if (offset >= 0)
2434 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2435 offset = nextOffset;
2436 }
2437
2438 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2439 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2440
2441 // built-in variable decorations
2442 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002443 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002444 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002445
2446#ifdef NV_EXTENSIONS
2447 if (builtIn == spv::BuiltInLayer) {
2448 // SPV_NV_viewport_array2 extension
2449 if (glslangMember.getQualifier().layoutViewportRelative){
2450 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2451 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2452 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2453 }
2454 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2455 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2456 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2457 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2458 }
2459 }
chaocdf3956c2017-02-14 14:52:34 -08002460 if (glslangMember.getQualifier().layoutPassthrough) {
2461 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2462 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2463 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2464 }
chaoc771d89f2017-01-13 01:10:53 -08002465#endif
John Kessenich6090df02016-06-30 21:18:02 -06002466 }
2467 }
2468
2469 // Decorate the structure
2470 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
2471 addDecoration(spvType, TranslateBlockDecoration(type));
2472 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2473 builder.addCapability(spv::CapabilityGeometryStreams);
2474 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2475 }
2476 if (glslangIntermediate->getXfbMode()) {
2477 builder.addCapability(spv::CapabilityTransformFeedback);
2478 if (type.getQualifier().hasXfbStride())
2479 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2480 if (type.getQualifier().hasXfbBuffer())
2481 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2482 }
2483}
2484
John Kessenich6c292d32016-02-15 20:58:50 -07002485// Turn the expression forming the array size into an id.
2486// This is not quite trivial, because of specialization constants.
2487// Sometimes, a raw constant is turned into an Id, and sometimes
2488// a specialization constant expression is.
2489spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2490{
2491 // First, see if this is sized with a node, meaning a specialization constant:
2492 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2493 if (specNode != nullptr) {
2494 builder.clearAccessChain();
2495 specNode->traverse(this);
2496 return accessChainLoad(specNode->getAsTyped()->getType());
2497 }
qining25262b32016-05-06 17:25:16 -04002498
John Kessenich6c292d32016-02-15 20:58:50 -07002499 // Otherwise, need a compile-time (front end) size, get it:
2500 int size = arraySizes.getDimSize(dim);
2501 assert(size > 0);
2502 return builder.makeUintConstant(size);
2503}
2504
John Kessenich103bef92016-02-08 21:38:15 -07002505// Wrap the builder's accessChainLoad to:
2506// - localize handling of RelaxedPrecision
2507// - use the SPIR-V inferred type instead of another conversion of the glslang type
2508// (avoids unnecessary work and possible type punning for structures)
2509// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002510spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2511{
John Kessenich103bef92016-02-08 21:38:15 -07002512 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2513 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2514
2515 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002516 if (type.getBasicType() == glslang::EbtBool) {
2517 if (builder.isScalarType(nominalTypeId)) {
2518 // Conversion for bool
2519 spv::Id boolType = builder.makeBoolType();
2520 if (nominalTypeId != boolType)
2521 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2522 } else if (builder.isVectorType(nominalTypeId)) {
2523 // Conversion for bvec
2524 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2525 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2526 if (nominalTypeId != bvecType)
2527 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2528 }
2529 }
John Kessenich103bef92016-02-08 21:38:15 -07002530
2531 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002532}
2533
Rex Xu27253232016-02-23 17:51:09 +08002534// Wrap the builder's accessChainStore to:
2535// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002536//
2537// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002538void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2539{
2540 // Need to convert to abstract types when necessary
2541 if (type.getBasicType() == glslang::EbtBool) {
2542 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2543
2544 if (builder.isScalarType(nominalTypeId)) {
2545 // Conversion for bool
2546 spv::Id boolType = builder.makeBoolType();
2547 if (nominalTypeId != boolType) {
2548 spv::Id zero = builder.makeUintConstant(0);
2549 spv::Id one = builder.makeUintConstant(1);
2550 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2551 }
2552 } else if (builder.isVectorType(nominalTypeId)) {
2553 // Conversion for bvec
2554 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2555 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2556 if (nominalTypeId != bvecType) {
2557 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2558 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2559 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2560 }
2561 }
2562 }
2563
2564 builder.accessChainStore(rvalue);
2565}
2566
John Kessenich4bf71552016-09-02 11:20:21 -06002567// For storing when types match at the glslang level, but not might match at the
2568// SPIR-V level.
2569//
2570// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002571// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002572// as in a member-decorated way.
2573//
2574// NOTE: This function can handle any store request; if it's not special it
2575// simplifies to a simple OpStore.
2576//
2577// Implicitly uses the existing builder.accessChain as the storage target.
2578void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2579{
John Kessenichb3e24e42016-09-11 12:33:43 -06002580 // we only do the complex path here if it's an aggregate
2581 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002582 accessChainStore(type, rValue);
2583 return;
2584 }
2585
John Kessenichb3e24e42016-09-11 12:33:43 -06002586 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002587 spv::Id rType = builder.getTypeId(rValue);
2588 spv::Id lValue = builder.accessChainGetLValue();
2589 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2590 if (lType == rType) {
2591 accessChainStore(type, rValue);
2592 return;
2593 }
2594
John Kessenichb3e24e42016-09-11 12:33:43 -06002595 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002596 // where the two types were the same type in GLSL. This requires member
2597 // by member copy, recursively.
2598
John Kessenichb3e24e42016-09-11 12:33:43 -06002599 // If an array, copy element by element.
2600 if (type.isArray()) {
2601 glslang::TType glslangElementType(type, 0);
2602 spv::Id elementRType = builder.getContainedTypeId(rType);
2603 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2604 // get the source member
2605 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002606
John Kessenichb3e24e42016-09-11 12:33:43 -06002607 // set up the target storage
2608 builder.clearAccessChain();
2609 builder.setAccessChainLValue(lValue);
2610 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002611
John Kessenichb3e24e42016-09-11 12:33:43 -06002612 // store the member
2613 multiTypeStore(glslangElementType, elementRValue);
2614 }
2615 } else {
2616 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002617
John Kessenichb3e24e42016-09-11 12:33:43 -06002618 // loop over structure members
2619 const glslang::TTypeList& members = *type.getStruct();
2620 for (int m = 0; m < (int)members.size(); ++m) {
2621 const glslang::TType& glslangMemberType = *members[m].type;
2622
2623 // get the source member
2624 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2625 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2626
2627 // set up the target storage
2628 builder.clearAccessChain();
2629 builder.setAccessChainLValue(lValue);
2630 builder.accessChainPush(builder.makeIntConstant(m));
2631
2632 // store the member
2633 multiTypeStore(glslangMemberType, memberRValue);
2634 }
John Kessenich4bf71552016-09-02 11:20:21 -06002635 }
2636}
2637
John Kessenichf85e8062015-12-19 13:57:10 -07002638// Decide whether or not this type should be
2639// decorated with offsets and strides, and if so
2640// whether std140 or std430 rules should be applied.
2641glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002642{
John Kessenichf85e8062015-12-19 13:57:10 -07002643 // has to be a block
2644 if (type.getBasicType() != glslang::EbtBlock)
2645 return glslang::ElpNone;
2646
2647 // has to be a uniform or buffer block
2648 if (type.getQualifier().storage != glslang::EvqUniform &&
2649 type.getQualifier().storage != glslang::EvqBuffer)
2650 return glslang::ElpNone;
2651
2652 // return the layout to use
2653 switch (type.getQualifier().layoutPacking) {
2654 case glslang::ElpStd140:
2655 case glslang::ElpStd430:
2656 return type.getQualifier().layoutPacking;
2657 default:
2658 return glslang::ElpNone;
2659 }
John Kessenich31ed4832015-09-09 17:51:38 -06002660}
2661
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002662// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002663int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002664{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002665 int size;
John Kessenich49987892015-12-29 17:11:44 -07002666 int stride;
2667 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002668
2669 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002670}
2671
John Kessenich49987892015-12-29 17:11:44 -07002672// 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 -07002673// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002674int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002675{
John Kessenich49987892015-12-29 17:11:44 -07002676 glslang::TType elementType;
2677 elementType.shallowCopy(matrixType);
2678 elementType.clearArraySizes();
2679
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002680 int size;
John Kessenich49987892015-12-29 17:11:44 -07002681 int stride;
2682 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2683
2684 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002685}
2686
John Kessenich5e4b1242015-08-06 22:53:06 -06002687// Given a member type of a struct, realign the current offset for it, and compute
2688// the next (not yet aligned) offset for the next member, which will get aligned
2689// on the next call.
2690// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2691// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2692// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002693void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002694 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002695{
2696 // this will get a positive value when deemed necessary
2697 nextOffset = -1;
2698
John Kessenich5e4b1242015-08-06 22:53:06 -06002699 // override anything in currentOffset with user-set offset
2700 if (memberType.getQualifier().hasOffset())
2701 currentOffset = memberType.getQualifier().layoutOffset;
2702
2703 // It could be that current linker usage in glslang updated all the layoutOffset,
2704 // in which case the following code does not matter. But, that's not quite right
2705 // once cross-compilation unit GLSL validation is done, as the original user
2706 // settings are needed in layoutOffset, and then the following will come into play.
2707
John Kessenichf85e8062015-12-19 13:57:10 -07002708 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002709 if (! memberType.getQualifier().hasOffset())
2710 currentOffset = -1;
2711
2712 return;
2713 }
2714
John Kessenichf85e8062015-12-19 13:57:10 -07002715 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002716 if (currentOffset < 0)
2717 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002718
John Kessenich5e4b1242015-08-06 22:53:06 -06002719 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2720 // but possibly not yet correctly aligned.
2721
2722 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002723 int dummyStride;
2724 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002725 glslang::RoundToPow2(currentOffset, memberAlignment);
2726 nextOffset = currentOffset + memberSize;
2727}
2728
David Netoa901ffe2016-06-08 14:11:40 +01002729void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002730{
David Netoa901ffe2016-06-08 14:11:40 +01002731 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2732 switch (glslangBuiltIn)
2733 {
2734 case glslang::EbvClipDistance:
2735 case glslang::EbvCullDistance:
2736 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002737#ifdef NV_EXTENSIONS
2738 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002739 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002740 case glslang::EbvViewportMaskNV:
2741 case glslang::EbvSecondaryPositionNV:
2742 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002743 case glslang::EbvPositionPerViewNV:
2744 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002745#endif
David Netoa901ffe2016-06-08 14:11:40 +01002746 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2747 // Alternately, we could just call this for any glslang built-in, since the
2748 // capability already guards against duplicates.
2749 TranslateBuiltInDecoration(glslangBuiltIn, false);
2750 break;
2751 default:
2752 // Capabilities were already generated when the struct was declared.
2753 break;
2754 }
John Kessenichebb50532016-05-16 19:22:05 -06002755}
2756
John Kessenich6fccb3c2016-09-19 16:01:41 -06002757bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002758{
John Kessenicheee9d532016-09-19 18:09:30 -06002759 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002760}
2761
2762// Make all the functions, skeletally, without actually visiting their bodies.
2763void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2764{
2765 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2766 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002767 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002768 continue;
2769
2770 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002771 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002772 //
qining25262b32016-05-06 17:25:16 -04002773 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002774 // function. What it is an address of varies:
2775 //
John Kessenich4bf71552016-09-02 11:20:21 -06002776 // - "in" parameters not marked as "const" can be written to without modifying the calling
2777 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002778 //
2779 // - "const in" parameters can just be the r-value, as no writes need occur.
2780 //
John Kessenich4bf71552016-09-02 11:20:21 -06002781 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2782 // 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 -06002783
2784 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002785 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002786 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2787
John Kessenich37789792017-03-21 23:56:40 -06002788 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() == glslangIntermediate->implicitThisName;
2789
John Kessenich140f3df2015-06-26 16:58:36 -06002790 for (int p = 0; p < (int)parameters.size(); ++p) {
2791 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2792 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002793 // can we pass by reference?
2794 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002795 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002796 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002797 (p == 0 && implicitThis)) // implicit 'this'
Jason Ekstranded15ef12016-06-08 13:54:48 -07002798 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
2799 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002800 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2801 else
John Kessenich4bf71552016-09-02 11:20:21 -06002802 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002803 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002804 paramTypes.push_back(typeId);
2805 }
2806
2807 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002808 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2809 convertGlslangToSpvType(glslFunction->getType()),
2810 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06002811 if (implicitThis)
2812 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06002813
2814 // Track function to emit/call later
2815 functionMap[glslFunction->getName().c_str()] = function;
2816
2817 // Set the parameter id's
2818 for (int p = 0; p < (int)parameters.size(); ++p) {
2819 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2820 // give a name too
2821 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2822 }
2823 }
2824}
2825
2826// Process all the initializers, while skipping the functions and link objects
2827void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2828{
2829 builder.setBuildPoint(shaderEntry->getLastBlock());
2830 for (int i = 0; i < (int)initializers.size(); ++i) {
2831 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2832 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2833
2834 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002835 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002836 initializer->traverse(this);
2837 }
2838 }
2839}
2840
2841// Process all the functions, while skipping initializers.
2842void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2843{
2844 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2845 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002846 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002847 node->traverse(this);
2848 }
2849}
2850
2851void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2852{
qining25262b32016-05-06 17:25:16 -04002853 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002854 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002855 currentFunction = functionMap[node->getName().c_str()];
2856 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002857 builder.setBuildPoint(functionBlock);
2858}
2859
Rex Xu04db3f52015-09-16 11:44:02 +08002860void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002861{
Rex Xufc618912015-09-09 16:42:49 +08002862 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002863
2864 glslang::TSampler sampler = {};
2865 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002866 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002867 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2868 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2869 }
2870
John Kessenich140f3df2015-06-26 16:58:36 -06002871 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2872 builder.clearAccessChain();
2873 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002874
2875 // Special case l-value operands
2876 bool lvalue = false;
2877 switch (node.getOp()) {
2878 case glslang::EOpImageAtomicAdd:
2879 case glslang::EOpImageAtomicMin:
2880 case glslang::EOpImageAtomicMax:
2881 case glslang::EOpImageAtomicAnd:
2882 case glslang::EOpImageAtomicOr:
2883 case glslang::EOpImageAtomicXor:
2884 case glslang::EOpImageAtomicExchange:
2885 case glslang::EOpImageAtomicCompSwap:
2886 if (i == 0)
2887 lvalue = true;
2888 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002889 case glslang::EOpSparseImageLoad:
2890 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2891 lvalue = true;
2892 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002893 case glslang::EOpSparseTexture:
2894 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2895 lvalue = true;
2896 break;
2897 case glslang::EOpSparseTextureClamp:
2898 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2899 lvalue = true;
2900 break;
2901 case glslang::EOpSparseTextureLod:
2902 case glslang::EOpSparseTextureOffset:
2903 if (i == 3)
2904 lvalue = true;
2905 break;
2906 case glslang::EOpSparseTextureFetch:
2907 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2908 lvalue = true;
2909 break;
2910 case glslang::EOpSparseTextureFetchOffset:
2911 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2912 lvalue = true;
2913 break;
2914 case glslang::EOpSparseTextureLodOffset:
2915 case glslang::EOpSparseTextureGrad:
2916 case glslang::EOpSparseTextureOffsetClamp:
2917 if (i == 4)
2918 lvalue = true;
2919 break;
2920 case glslang::EOpSparseTextureGradOffset:
2921 case glslang::EOpSparseTextureGradClamp:
2922 if (i == 5)
2923 lvalue = true;
2924 break;
2925 case glslang::EOpSparseTextureGradOffsetClamp:
2926 if (i == 6)
2927 lvalue = true;
2928 break;
2929 case glslang::EOpSparseTextureGather:
2930 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2931 lvalue = true;
2932 break;
2933 case glslang::EOpSparseTextureGatherOffset:
2934 case glslang::EOpSparseTextureGatherOffsets:
2935 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2936 lvalue = true;
2937 break;
Rex Xufc618912015-09-09 16:42:49 +08002938 default:
2939 break;
2940 }
2941
Rex Xu6b86d492015-09-16 17:48:22 +08002942 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002943 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002944 else
John Kessenich32cfd492016-02-02 12:37:46 -07002945 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002946 }
2947}
2948
John Kessenichfc51d282015-08-19 13:34:18 -06002949void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002950{
John Kessenichfc51d282015-08-19 13:34:18 -06002951 builder.clearAccessChain();
2952 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002953 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002954}
John Kessenich140f3df2015-06-26 16:58:36 -06002955
John Kessenichfc51d282015-08-19 13:34:18 -06002956spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2957{
Rex Xufc618912015-09-09 16:42:49 +08002958 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002959 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002960 }
John Kessenich8c8505c2016-07-26 12:50:38 -06002961 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06002962
John Kessenichfc51d282015-08-19 13:34:18 -06002963 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002964 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2965 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2966 std::vector<spv::Id> arguments;
2967 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002968 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002969 else
2970 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06002971 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06002972
2973 spv::Builder::TextureParameters params = { };
2974 params.sampler = arguments[0];
2975
Rex Xu04db3f52015-09-16 11:44:02 +08002976 glslang::TCrackedTextureOp cracked;
2977 node->crackTexture(sampler, cracked);
2978
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002979 const bool isUnsignedResult =
2980 node->getType().getBasicType() == glslang::EbtUint64 ||
2981 node->getType().getBasicType() == glslang::EbtUint;
2982
John Kessenichfc51d282015-08-19 13:34:18 -06002983 // Check for queries
2984 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002985 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
2986 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07002987 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02002988
John Kessenichfc51d282015-08-19 13:34:18 -06002989 switch (node->getOp()) {
2990 case glslang::EOpImageQuerySize:
2991 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002992 if (arguments.size() > 1) {
2993 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002994 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06002995 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002996 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06002997 case glslang::EOpImageQuerySamples:
2998 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07002999 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003000 case glslang::EOpTextureQueryLod:
3001 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003002 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003003 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003004 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003005 case glslang::EOpSparseTexelsResident:
3006 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003007 default:
3008 assert(0);
3009 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003010 }
John Kessenich140f3df2015-06-26 16:58:36 -06003011 }
3012
Rex Xufc618912015-09-09 16:42:49 +08003013 // Check for image functions other than queries
3014 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003015 std::vector<spv::Id> operands;
3016 auto opIt = arguments.begin();
3017 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003018
3019 // Handle subpass operations
3020 // TODO: GLSL should change to have the "MS" only on the type rather than the
3021 // built-in function.
3022 if (cracked.subpass) {
3023 // add on the (0,0) coordinate
3024 spv::Id zero = builder.makeIntConstant(0);
3025 std::vector<spv::Id> comps;
3026 comps.push_back(zero);
3027 comps.push_back(zero);
3028 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3029 if (sampler.ms) {
3030 operands.push_back(spv::ImageOperandsSampleMask);
3031 operands.push_back(*(opIt++));
3032 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003033 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003034 }
3035
John Kessenich56bab042015-09-16 10:54:31 -06003036 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003037 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003038 if (sampler.ms) {
3039 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003040 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003041 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003042 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3043 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003044 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003045 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003046 if (sampler.ms) {
3047 operands.push_back(*(opIt + 1));
3048 operands.push_back(spv::ImageOperandsSampleMask);
3049 operands.push_back(*opIt);
3050 } else
3051 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003052 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003053 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3054 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003055 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003056 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3057 builder.addCapability(spv::CapabilitySparseResidency);
3058 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3059 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3060
3061 if (sampler.ms) {
3062 operands.push_back(spv::ImageOperandsSampleMask);
3063 operands.push_back(*opIt++);
3064 }
3065
3066 // Create the return type that was a special structure
3067 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003068 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003069 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3070 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3071
3072 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3073
3074 // Decode the return type
3075 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3076 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003077 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003078 // Process image atomic operations
3079
3080 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3081 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003082 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003083
John Kessenich8c8505c2016-07-26 12:50:38 -06003084 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003085 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003086
3087 std::vector<spv::Id> operands;
3088 operands.push_back(pointer);
3089 for (; opIt != arguments.end(); ++opIt)
3090 operands.push_back(*opIt);
3091
John Kessenich8c8505c2016-07-26 12:50:38 -06003092 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003093 }
3094 }
3095
3096 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003097 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003098 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3099
John Kessenichfc51d282015-08-19 13:34:18 -06003100 // check for bias argument
3101 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003102 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003103 int nonBiasArgCount = 2;
3104 if (cracked.offset)
3105 ++nonBiasArgCount;
3106 if (cracked.grad)
3107 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003108 if (cracked.lodClamp)
3109 ++nonBiasArgCount;
3110 if (sparse)
3111 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003112
3113 if ((int)arguments.size() > nonBiasArgCount)
3114 bias = true;
3115 }
3116
John Kessenicha5c33d62016-06-02 23:45:21 -06003117 // See if the sampler param should really be just the SPV image part
3118 if (cracked.fetch) {
3119 // a fetch needs to have the image extracted first
3120 if (builder.isSampledImage(params.sampler))
3121 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3122 }
3123
John Kessenichfc51d282015-08-19 13:34:18 -06003124 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003125
John Kessenichfc51d282015-08-19 13:34:18 -06003126 params.coords = arguments[1];
3127 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003128 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003129
3130 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003131 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003132 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003133 ++extraArgs;
3134 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003135 params.Dref = arguments[2];
3136 ++extraArgs;
3137 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003138 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003139 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003140 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003141 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003142 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003143 dRefComp = builder.getNumComponents(params.coords) - 1;
3144 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003145 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3146 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003147
3148 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003149 if (cracked.lod) {
3150 params.lod = arguments[2];
3151 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003152 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3153 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3154 noImplicitLod = true;
3155 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003156
3157 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003158 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003159 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003160 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003161 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003162
3163 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003164 if (cracked.grad) {
3165 params.gradX = arguments[2 + extraArgs];
3166 params.gradY = arguments[3 + extraArgs];
3167 extraArgs += 2;
3168 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003169
3170 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003171 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003172 params.offset = arguments[2 + extraArgs];
3173 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003174 } else if (cracked.offsets) {
3175 params.offsets = arguments[2 + extraArgs];
3176 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003177 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003178
3179 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003180 if (cracked.lodClamp) {
3181 params.lodClamp = arguments[2 + extraArgs];
3182 ++extraArgs;
3183 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003184
3185 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003186 if (sparse) {
3187 params.texelOut = arguments[2 + extraArgs];
3188 ++extraArgs;
3189 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003190
3191 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003192 if (bias) {
3193 params.bias = arguments[2 + extraArgs];
3194 ++extraArgs;
3195 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003196
3197 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003198 if (cracked.gather && ! sampler.shadow) {
3199 // default component is 0, if missing, otherwise an argument
3200 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003201 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003202 ++extraArgs;
3203 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003204 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003205 }
3206 }
John Kessenichfc51d282015-08-19 13:34:18 -06003207
John Kessenich65336482016-06-16 14:06:26 -06003208 // projective component (might not to move)
3209 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3210 // are divided by the last component of P."
3211 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3212 // unused components will appear after all used components."
3213 if (cracked.proj) {
3214 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3215 int projTargetComp;
3216 switch (sampler.dim) {
3217 case glslang::Esd1D: projTargetComp = 1; break;
3218 case glslang::Esd2D: projTargetComp = 2; break;
3219 case glslang::EsdRect: projTargetComp = 2; break;
3220 default: projTargetComp = projSourceComp; break;
3221 }
3222 // copy the projective coordinate if we have to
3223 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003224 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003225 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3226 projSourceComp);
3227 params.coords = builder.createCompositeInsert(projComp, params.coords,
3228 builder.getTypeId(params.coords), projTargetComp);
3229 }
3230 }
3231
John Kessenich8c8505c2016-07-26 12:50:38 -06003232 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003233}
3234
3235spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3236{
3237 // Grab the function's pointer from the previously created function
3238 spv::Function* function = functionMap[node->getName().c_str()];
3239 if (! function)
3240 return 0;
3241
3242 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3243 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3244
3245 // See comments in makeFunctions() for details about the semantics for parameter passing.
3246 //
3247 // These imply we need a four step process:
3248 // 1. Evaluate the arguments
3249 // 2. Allocate and make copies of in, out, and inout arguments
3250 // 3. Make the call
3251 // 4. Copy back the results
3252
3253 // 1. Evaluate the arguments
3254 std::vector<spv::Builder::AccessChain> lValues;
3255 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003256 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003257 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003258 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003259 // build l-value
3260 builder.clearAccessChain();
3261 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003262 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003263 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003264 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003265 // save l-value
3266 lValues.push_back(builder.getAccessChain());
3267 } else {
3268 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003269 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003270 }
3271 }
3272
3273 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3274 // copy the original into that space.
3275 //
3276 // Also, build up the list of actual arguments to pass in for the call
3277 int lValueCount = 0;
3278 int rValueCount = 0;
3279 std::vector<spv::Id> spvArgs;
3280 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003281 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003282 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003283 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003284 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3285 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003286 builder.setAccessChain(lValues[lValueCount]);
3287 arg = builder.accessChainGetLValue();
3288 ++lValueCount;
3289 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003290 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003291 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3292 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3293 // need to copy the input into output space
3294 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003295 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003296 builder.clearAccessChain();
3297 builder.setAccessChainLValue(arg);
3298 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003299 }
3300 ++lValueCount;
3301 } else {
3302 arg = rValues[rValueCount];
3303 ++rValueCount;
3304 }
3305 spvArgs.push_back(arg);
3306 }
3307
3308 // 3. Make the call.
3309 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003310 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003311
3312 // 4. Copy back out an "out" arguments.
3313 lValueCount = 0;
3314 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003315 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003316 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3317 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3318 spv::Id copy = builder.createLoad(spvArgs[a]);
3319 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003320 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003321 }
3322 ++lValueCount;
3323 }
3324 }
3325
3326 return result;
3327}
3328
3329// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003330spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3331 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003332 spv::Id typeId, spv::Id left, spv::Id right,
3333 glslang::TBasicType typeProxy, bool reduceComparison)
3334{
Rex Xu8ff43de2016-04-22 16:51:45 +08003335 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003336#ifdef AMD_EXTENSIONS
3337 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3338#else
John Kessenich140f3df2015-06-26 16:58:36 -06003339 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003340#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003341 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003342
3343 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003344 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003345 bool comparison = false;
3346
3347 switch (op) {
3348 case glslang::EOpAdd:
3349 case glslang::EOpAddAssign:
3350 if (isFloat)
3351 binOp = spv::OpFAdd;
3352 else
3353 binOp = spv::OpIAdd;
3354 break;
3355 case glslang::EOpSub:
3356 case glslang::EOpSubAssign:
3357 if (isFloat)
3358 binOp = spv::OpFSub;
3359 else
3360 binOp = spv::OpISub;
3361 break;
3362 case glslang::EOpMul:
3363 case glslang::EOpMulAssign:
3364 if (isFloat)
3365 binOp = spv::OpFMul;
3366 else
3367 binOp = spv::OpIMul;
3368 break;
3369 case glslang::EOpVectorTimesScalar:
3370 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003371 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003372 if (builder.isVector(right))
3373 std::swap(left, right);
3374 assert(builder.isScalar(right));
3375 needMatchingVectors = false;
3376 binOp = spv::OpVectorTimesScalar;
3377 } else
3378 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003379 break;
3380 case glslang::EOpVectorTimesMatrix:
3381 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003382 binOp = spv::OpVectorTimesMatrix;
3383 break;
3384 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003385 binOp = spv::OpMatrixTimesVector;
3386 break;
3387 case glslang::EOpMatrixTimesScalar:
3388 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003389 binOp = spv::OpMatrixTimesScalar;
3390 break;
3391 case glslang::EOpMatrixTimesMatrix:
3392 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003393 binOp = spv::OpMatrixTimesMatrix;
3394 break;
3395 case glslang::EOpOuterProduct:
3396 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003397 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003398 break;
3399
3400 case glslang::EOpDiv:
3401 case glslang::EOpDivAssign:
3402 if (isFloat)
3403 binOp = spv::OpFDiv;
3404 else if (isUnsigned)
3405 binOp = spv::OpUDiv;
3406 else
3407 binOp = spv::OpSDiv;
3408 break;
3409 case glslang::EOpMod:
3410 case glslang::EOpModAssign:
3411 if (isFloat)
3412 binOp = spv::OpFMod;
3413 else if (isUnsigned)
3414 binOp = spv::OpUMod;
3415 else
3416 binOp = spv::OpSMod;
3417 break;
3418 case glslang::EOpRightShift:
3419 case glslang::EOpRightShiftAssign:
3420 if (isUnsigned)
3421 binOp = spv::OpShiftRightLogical;
3422 else
3423 binOp = spv::OpShiftRightArithmetic;
3424 break;
3425 case glslang::EOpLeftShift:
3426 case glslang::EOpLeftShiftAssign:
3427 binOp = spv::OpShiftLeftLogical;
3428 break;
3429 case glslang::EOpAnd:
3430 case glslang::EOpAndAssign:
3431 binOp = spv::OpBitwiseAnd;
3432 break;
3433 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003434 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003435 binOp = spv::OpLogicalAnd;
3436 break;
3437 case glslang::EOpInclusiveOr:
3438 case glslang::EOpInclusiveOrAssign:
3439 binOp = spv::OpBitwiseOr;
3440 break;
3441 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003442 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003443 binOp = spv::OpLogicalOr;
3444 break;
3445 case glslang::EOpExclusiveOr:
3446 case glslang::EOpExclusiveOrAssign:
3447 binOp = spv::OpBitwiseXor;
3448 break;
3449 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003450 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003451 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003452 break;
3453
3454 case glslang::EOpLessThan:
3455 case glslang::EOpGreaterThan:
3456 case glslang::EOpLessThanEqual:
3457 case glslang::EOpGreaterThanEqual:
3458 case glslang::EOpEqual:
3459 case glslang::EOpNotEqual:
3460 case glslang::EOpVectorEqual:
3461 case glslang::EOpVectorNotEqual:
3462 comparison = true;
3463 break;
3464 default:
3465 break;
3466 }
3467
John Kessenich7c1aa102015-10-15 13:29:11 -06003468 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003469 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003470 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003471 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003472 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003473
3474 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003475 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003476 builder.promoteScalar(precision, left, right);
3477
qining25262b32016-05-06 17:25:16 -04003478 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3479 addDecoration(result, noContraction);
3480 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003481 }
3482
3483 if (! comparison)
3484 return 0;
3485
John Kessenich7c1aa102015-10-15 13:29:11 -06003486 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003487
John Kessenich4583b612016-08-07 19:14:22 -06003488 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3489 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003490 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003491
3492 switch (op) {
3493 case glslang::EOpLessThan:
3494 if (isFloat)
3495 binOp = spv::OpFOrdLessThan;
3496 else if (isUnsigned)
3497 binOp = spv::OpULessThan;
3498 else
3499 binOp = spv::OpSLessThan;
3500 break;
3501 case glslang::EOpGreaterThan:
3502 if (isFloat)
3503 binOp = spv::OpFOrdGreaterThan;
3504 else if (isUnsigned)
3505 binOp = spv::OpUGreaterThan;
3506 else
3507 binOp = spv::OpSGreaterThan;
3508 break;
3509 case glslang::EOpLessThanEqual:
3510 if (isFloat)
3511 binOp = spv::OpFOrdLessThanEqual;
3512 else if (isUnsigned)
3513 binOp = spv::OpULessThanEqual;
3514 else
3515 binOp = spv::OpSLessThanEqual;
3516 break;
3517 case glslang::EOpGreaterThanEqual:
3518 if (isFloat)
3519 binOp = spv::OpFOrdGreaterThanEqual;
3520 else if (isUnsigned)
3521 binOp = spv::OpUGreaterThanEqual;
3522 else
3523 binOp = spv::OpSGreaterThanEqual;
3524 break;
3525 case glslang::EOpEqual:
3526 case glslang::EOpVectorEqual:
3527 if (isFloat)
3528 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003529 else if (isBool)
3530 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003531 else
3532 binOp = spv::OpIEqual;
3533 break;
3534 case glslang::EOpNotEqual:
3535 case glslang::EOpVectorNotEqual:
3536 if (isFloat)
3537 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003538 else if (isBool)
3539 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003540 else
3541 binOp = spv::OpINotEqual;
3542 break;
3543 default:
3544 break;
3545 }
3546
qining25262b32016-05-06 17:25:16 -04003547 if (binOp != spv::OpNop) {
3548 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3549 addDecoration(result, noContraction);
3550 return builder.setPrecision(result, precision);
3551 }
John Kessenich140f3df2015-06-26 16:58:36 -06003552
3553 return 0;
3554}
3555
John Kessenich04bb8a02015-12-12 12:28:14 -07003556//
3557// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3558// These can be any of:
3559//
3560// matrix * scalar
3561// scalar * matrix
3562// matrix * matrix linear algebraic
3563// matrix * vector
3564// vector * matrix
3565// matrix * matrix componentwise
3566// matrix op matrix op in {+, -, /}
3567// matrix op scalar op in {+, -, /}
3568// scalar op matrix op in {+, -, /}
3569//
qining25262b32016-05-06 17:25:16 -04003570spv::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 -07003571{
3572 bool firstClass = true;
3573
3574 // First, handle first-class matrix operations (* and matrix/scalar)
3575 switch (op) {
3576 case spv::OpFDiv:
3577 if (builder.isMatrix(left) && builder.isScalar(right)) {
3578 // turn matrix / scalar into a multiply...
3579 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3580 op = spv::OpMatrixTimesScalar;
3581 } else
3582 firstClass = false;
3583 break;
3584 case spv::OpMatrixTimesScalar:
3585 if (builder.isMatrix(right))
3586 std::swap(left, right);
3587 assert(builder.isScalar(right));
3588 break;
3589 case spv::OpVectorTimesMatrix:
3590 assert(builder.isVector(left));
3591 assert(builder.isMatrix(right));
3592 break;
3593 case spv::OpMatrixTimesVector:
3594 assert(builder.isMatrix(left));
3595 assert(builder.isVector(right));
3596 break;
3597 case spv::OpMatrixTimesMatrix:
3598 assert(builder.isMatrix(left));
3599 assert(builder.isMatrix(right));
3600 break;
3601 default:
3602 firstClass = false;
3603 break;
3604 }
3605
qining25262b32016-05-06 17:25:16 -04003606 if (firstClass) {
3607 spv::Id result = builder.createBinOp(op, typeId, left, right);
3608 addDecoration(result, noContraction);
3609 return builder.setPrecision(result, precision);
3610 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003611
LoopDawg592860c2016-06-09 08:57:35 -06003612 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003613 // The result type of all of them is the same type as the (a) matrix operand.
3614 // The algorithm is to:
3615 // - break the matrix(es) into vectors
3616 // - smear any scalar to a vector
3617 // - do vector operations
3618 // - make a matrix out the vector results
3619 switch (op) {
3620 case spv::OpFAdd:
3621 case spv::OpFSub:
3622 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003623 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003624 case spv::OpFMul:
3625 {
3626 // one time set up...
3627 bool leftMat = builder.isMatrix(left);
3628 bool rightMat = builder.isMatrix(right);
3629 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3630 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3631 spv::Id scalarType = builder.getScalarTypeId(typeId);
3632 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3633 std::vector<spv::Id> results;
3634 spv::Id smearVec = spv::NoResult;
3635 if (builder.isScalar(left))
3636 smearVec = builder.smearScalar(precision, left, vecType);
3637 else if (builder.isScalar(right))
3638 smearVec = builder.smearScalar(precision, right, vecType);
3639
3640 // do each vector op
3641 for (unsigned int c = 0; c < numCols; ++c) {
3642 std::vector<unsigned int> indexes;
3643 indexes.push_back(c);
3644 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3645 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003646 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3647 addDecoration(result, noContraction);
3648 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003649 }
3650
3651 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003652 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003653 }
3654 default:
3655 assert(0);
3656 return spv::NoResult;
3657 }
3658}
3659
qining25262b32016-05-06 17:25:16 -04003660spv::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 -06003661{
3662 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003663 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003664 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003665 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003666#ifdef AMD_EXTENSIONS
3667 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3668#else
Rex Xu04db3f52015-09-16 11:44:02 +08003669 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003670#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003671
3672 switch (op) {
3673 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003674 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003675 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003676 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003677 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003678 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003679 unaryOp = spv::OpSNegate;
3680 break;
3681
3682 case glslang::EOpLogicalNot:
3683 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003684 unaryOp = spv::OpLogicalNot;
3685 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003686 case glslang::EOpBitwiseNot:
3687 unaryOp = spv::OpNot;
3688 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003689
John Kessenich140f3df2015-06-26 16:58:36 -06003690 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003691 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003692 break;
3693 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003694 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003695 break;
3696 case glslang::EOpTranspose:
3697 unaryOp = spv::OpTranspose;
3698 break;
3699
3700 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003701 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003702 break;
3703 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003704 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003705 break;
3706 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003707 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003708 break;
3709 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003710 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003711 break;
3712 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003713 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003714 break;
3715 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003716 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003717 break;
3718 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003719 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003720 break;
3721 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003722 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003723 break;
3724
3725 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003726 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003727 break;
3728 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003729 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003730 break;
3731 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003732 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003733 break;
3734 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003735 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003736 break;
3737 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003738 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003739 break;
3740 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003741 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003742 break;
3743
3744 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003745 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003746 break;
3747 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003748 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003749 break;
3750
3751 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003752 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003753 break;
3754 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003755 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003756 break;
3757 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003758 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003759 break;
3760 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003761 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003762 break;
3763 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003764 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003765 break;
3766 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003767 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003768 break;
3769
3770 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003771 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003772 break;
3773 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003774 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003775 break;
3776 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003777 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003778 break;
3779 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003780 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003781 break;
3782 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003783 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003784 break;
3785 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003786 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003787 break;
3788
3789 case glslang::EOpIsNan:
3790 unaryOp = spv::OpIsNan;
3791 break;
3792 case glslang::EOpIsInf:
3793 unaryOp = spv::OpIsInf;
3794 break;
LoopDawg592860c2016-06-09 08:57:35 -06003795 case glslang::EOpIsFinite:
3796 unaryOp = spv::OpIsFinite;
3797 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003798
Rex Xucbc426e2015-12-15 16:03:10 +08003799 case glslang::EOpFloatBitsToInt:
3800 case glslang::EOpFloatBitsToUint:
3801 case glslang::EOpIntBitsToFloat:
3802 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003803 case glslang::EOpDoubleBitsToInt64:
3804 case glslang::EOpDoubleBitsToUint64:
3805 case glslang::EOpInt64BitsToDouble:
3806 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003807 unaryOp = spv::OpBitcast;
3808 break;
3809
John Kessenich140f3df2015-06-26 16:58:36 -06003810 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003811 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003812 break;
3813 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003814 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003815 break;
3816 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003817 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003818 break;
3819 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003820 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003821 break;
3822 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003823 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003824 break;
3825 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003826 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003827 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003828 case glslang::EOpPackSnorm4x8:
3829 libCall = spv::GLSLstd450PackSnorm4x8;
3830 break;
3831 case glslang::EOpUnpackSnorm4x8:
3832 libCall = spv::GLSLstd450UnpackSnorm4x8;
3833 break;
3834 case glslang::EOpPackUnorm4x8:
3835 libCall = spv::GLSLstd450PackUnorm4x8;
3836 break;
3837 case glslang::EOpUnpackUnorm4x8:
3838 libCall = spv::GLSLstd450UnpackUnorm4x8;
3839 break;
3840 case glslang::EOpPackDouble2x32:
3841 libCall = spv::GLSLstd450PackDouble2x32;
3842 break;
3843 case glslang::EOpUnpackDouble2x32:
3844 libCall = spv::GLSLstd450UnpackDouble2x32;
3845 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003846
Rex Xu8ff43de2016-04-22 16:51:45 +08003847 case glslang::EOpPackInt2x32:
3848 case glslang::EOpUnpackInt2x32:
3849 case glslang::EOpPackUint2x32:
3850 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003851 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003852 break;
3853
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003854#ifdef AMD_EXTENSIONS
3855 case glslang::EOpPackFloat2x16:
3856 case glslang::EOpUnpackFloat2x16:
3857 unaryOp = spv::OpBitcast;
3858 break;
3859#endif
3860
John Kessenich140f3df2015-06-26 16:58:36 -06003861 case glslang::EOpDPdx:
3862 unaryOp = spv::OpDPdx;
3863 break;
3864 case glslang::EOpDPdy:
3865 unaryOp = spv::OpDPdy;
3866 break;
3867 case glslang::EOpFwidth:
3868 unaryOp = spv::OpFwidth;
3869 break;
3870 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003871 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003872 unaryOp = spv::OpDPdxFine;
3873 break;
3874 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003875 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003876 unaryOp = spv::OpDPdyFine;
3877 break;
3878 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003879 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003880 unaryOp = spv::OpFwidthFine;
3881 break;
3882 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003883 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003884 unaryOp = spv::OpDPdxCoarse;
3885 break;
3886 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003887 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003888 unaryOp = spv::OpDPdyCoarse;
3889 break;
3890 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003891 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003892 unaryOp = spv::OpFwidthCoarse;
3893 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003894 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003895 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003896 libCall = spv::GLSLstd450InterpolateAtCentroid;
3897 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003898 case glslang::EOpAny:
3899 unaryOp = spv::OpAny;
3900 break;
3901 case glslang::EOpAll:
3902 unaryOp = spv::OpAll;
3903 break;
3904
3905 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003906 if (isFloat)
3907 libCall = spv::GLSLstd450FAbs;
3908 else
3909 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003910 break;
3911 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003912 if (isFloat)
3913 libCall = spv::GLSLstd450FSign;
3914 else
3915 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003916 break;
3917
John Kessenichfc51d282015-08-19 13:34:18 -06003918 case glslang::EOpAtomicCounterIncrement:
3919 case glslang::EOpAtomicCounterDecrement:
3920 case glslang::EOpAtomicCounter:
3921 {
3922 // Handle all of the atomics in one place, in createAtomicOperation()
3923 std::vector<spv::Id> operands;
3924 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003925 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003926 }
3927
John Kessenichfc51d282015-08-19 13:34:18 -06003928 case glslang::EOpBitFieldReverse:
3929 unaryOp = spv::OpBitReverse;
3930 break;
3931 case glslang::EOpBitCount:
3932 unaryOp = spv::OpBitCount;
3933 break;
3934 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003935 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003936 break;
3937 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003938 if (isUnsigned)
3939 libCall = spv::GLSLstd450FindUMsb;
3940 else
3941 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003942 break;
3943
Rex Xu574ab042016-04-14 16:53:07 +08003944 case glslang::EOpBallot:
3945 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003946 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003947 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003948 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003949#ifdef AMD_EXTENSIONS
3950 case glslang::EOpMinInvocations:
3951 case glslang::EOpMaxInvocations:
3952 case glslang::EOpAddInvocations:
3953 case glslang::EOpMinInvocationsNonUniform:
3954 case glslang::EOpMaxInvocationsNonUniform:
3955 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08003956 case glslang::EOpMinInvocationsInclusiveScan:
3957 case glslang::EOpMaxInvocationsInclusiveScan:
3958 case glslang::EOpAddInvocationsInclusiveScan:
3959 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
3960 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
3961 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
3962 case glslang::EOpMinInvocationsExclusiveScan:
3963 case glslang::EOpMaxInvocationsExclusiveScan:
3964 case glslang::EOpAddInvocationsExclusiveScan:
3965 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
3966 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
3967 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08003968#endif
Rex Xu51596642016-09-21 18:56:12 +08003969 {
3970 std::vector<spv::Id> operands;
3971 operands.push_back(operand);
3972 return createInvocationsOperation(op, typeId, operands, typeProxy);
3973 }
Rex Xu9d93a232016-05-05 12:30:44 +08003974
3975#ifdef AMD_EXTENSIONS
3976 case glslang::EOpMbcnt:
3977 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
3978 libCall = spv::MbcntAMD;
3979 break;
3980
3981 case glslang::EOpCubeFaceIndex:
3982 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3983 libCall = spv::CubeFaceIndexAMD;
3984 break;
3985
3986 case glslang::EOpCubeFaceCoord:
3987 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
3988 libCall = spv::CubeFaceCoordAMD;
3989 break;
3990#endif
Rex Xu338b1852016-05-05 20:38:33 +08003991
John Kessenich140f3df2015-06-26 16:58:36 -06003992 default:
3993 return 0;
3994 }
3995
3996 spv::Id id;
3997 if (libCall >= 0) {
3998 std::vector<spv::Id> args;
3999 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004000 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004001 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004002 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004003 }
John Kessenich140f3df2015-06-26 16:58:36 -06004004
qining25262b32016-05-06 17:25:16 -04004005 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004006 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004007}
4008
John Kessenich7a53f762016-01-20 11:19:27 -07004009// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004010spv::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 -07004011{
4012 // Handle unary operations vector by vector.
4013 // The result type is the same type as the original type.
4014 // The algorithm is to:
4015 // - break the matrix into vectors
4016 // - apply the operation to each vector
4017 // - make a matrix out the vector results
4018
4019 // get the types sorted out
4020 int numCols = builder.getNumColumns(operand);
4021 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004022 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4023 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004024 std::vector<spv::Id> results;
4025
4026 // do each vector op
4027 for (int c = 0; c < numCols; ++c) {
4028 std::vector<unsigned int> indexes;
4029 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004030 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4031 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4032 addDecoration(destVec, noContraction);
4033 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004034 }
4035
4036 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004037 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004038}
4039
Rex Xu73e3ce72016-04-27 18:48:17 +08004040spv::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 -06004041{
4042 spv::Op convOp = spv::OpNop;
4043 spv::Id zero = 0;
4044 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004045 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004046
4047 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4048
4049 switch (op) {
4050 case glslang::EOpConvIntToBool:
4051 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004052 case glslang::EOpConvInt64ToBool:
4053 case glslang::EOpConvUint64ToBool:
4054 zero = (op == glslang::EOpConvInt64ToBool ||
4055 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004056 zero = makeSmearedConstant(zero, vectorSize);
4057 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4058
4059 case glslang::EOpConvFloatToBool:
4060 zero = builder.makeFloatConstant(0.0F);
4061 zero = makeSmearedConstant(zero, vectorSize);
4062 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4063
4064 case glslang::EOpConvDoubleToBool:
4065 zero = builder.makeDoubleConstant(0.0);
4066 zero = makeSmearedConstant(zero, vectorSize);
4067 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4068
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004069#ifdef AMD_EXTENSIONS
4070 case glslang::EOpConvFloat16ToBool:
4071 zero = builder.makeFloat16Constant(0.0F);
4072 zero = makeSmearedConstant(zero, vectorSize);
4073 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4074#endif
4075
John Kessenich140f3df2015-06-26 16:58:36 -06004076 case glslang::EOpConvBoolToFloat:
4077 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004078 zero = builder.makeFloatConstant(0.0F);
4079 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004080 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004081
John Kessenich140f3df2015-06-26 16:58:36 -06004082 case glslang::EOpConvBoolToDouble:
4083 convOp = spv::OpSelect;
4084 zero = builder.makeDoubleConstant(0.0);
4085 one = builder.makeDoubleConstant(1.0);
4086 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004087
4088#ifdef AMD_EXTENSIONS
4089 case glslang::EOpConvBoolToFloat16:
4090 convOp = spv::OpSelect;
4091 zero = builder.makeFloat16Constant(0.0F);
4092 one = builder.makeFloat16Constant(1.0F);
4093 break;
4094#endif
4095
John Kessenich140f3df2015-06-26 16:58:36 -06004096 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004097 case glslang::EOpConvBoolToInt64:
4098 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4099 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004100 convOp = spv::OpSelect;
4101 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004102
John Kessenich140f3df2015-06-26 16:58:36 -06004103 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004104 case glslang::EOpConvBoolToUint64:
4105 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4106 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004107 convOp = spv::OpSelect;
4108 break;
4109
4110 case glslang::EOpConvIntToFloat:
4111 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004112 case glslang::EOpConvInt64ToFloat:
4113 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004114#ifdef AMD_EXTENSIONS
4115 case glslang::EOpConvIntToFloat16:
4116 case glslang::EOpConvInt64ToFloat16:
4117#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004118 convOp = spv::OpConvertSToF;
4119 break;
4120
4121 case glslang::EOpConvUintToFloat:
4122 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004123 case glslang::EOpConvUint64ToFloat:
4124 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004125#ifdef AMD_EXTENSIONS
4126 case glslang::EOpConvUintToFloat16:
4127 case glslang::EOpConvUint64ToFloat16:
4128#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004129 convOp = spv::OpConvertUToF;
4130 break;
4131
4132 case glslang::EOpConvDoubleToFloat:
4133 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004134#ifdef AMD_EXTENSIONS
4135 case glslang::EOpConvDoubleToFloat16:
4136 case glslang::EOpConvFloat16ToDouble:
4137 case glslang::EOpConvFloatToFloat16:
4138 case glslang::EOpConvFloat16ToFloat:
4139#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004140 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004141 if (builder.isMatrixType(destType))
4142 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004143 break;
4144
4145 case glslang::EOpConvFloatToInt:
4146 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004147 case glslang::EOpConvFloatToInt64:
4148 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004149#ifdef AMD_EXTENSIONS
4150 case glslang::EOpConvFloat16ToInt:
4151 case glslang::EOpConvFloat16ToInt64:
4152#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004153 convOp = spv::OpConvertFToS;
4154 break;
4155
4156 case glslang::EOpConvUintToInt:
4157 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004158 case glslang::EOpConvUint64ToInt64:
4159 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004160 if (builder.isInSpecConstCodeGenMode()) {
4161 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004162 zero = (op == glslang::EOpConvUint64ToInt64 ||
4163 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004164 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004165 // Use OpIAdd, instead of OpBitcast to do the conversion when
4166 // generating for OpSpecConstantOp instruction.
4167 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4168 }
4169 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004170 convOp = spv::OpBitcast;
4171 break;
4172
4173 case glslang::EOpConvFloatToUint:
4174 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004175 case glslang::EOpConvFloatToUint64:
4176 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004177#ifdef AMD_EXTENSIONS
4178 case glslang::EOpConvFloat16ToUint:
4179 case glslang::EOpConvFloat16ToUint64:
4180#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004181 convOp = spv::OpConvertFToU;
4182 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004183
4184 case glslang::EOpConvIntToInt64:
4185 case glslang::EOpConvInt64ToInt:
4186 convOp = spv::OpSConvert;
4187 break;
4188
4189 case glslang::EOpConvUintToUint64:
4190 case glslang::EOpConvUint64ToUint:
4191 convOp = spv::OpUConvert;
4192 break;
4193
4194 case glslang::EOpConvIntToUint64:
4195 case glslang::EOpConvInt64ToUint:
4196 case glslang::EOpConvUint64ToInt:
4197 case glslang::EOpConvUintToInt64:
4198 // OpSConvert/OpUConvert + OpBitCast
4199 switch (op) {
4200 case glslang::EOpConvIntToUint64:
4201 convOp = spv::OpSConvert;
4202 type = builder.makeIntType(64);
4203 break;
4204 case glslang::EOpConvInt64ToUint:
4205 convOp = spv::OpSConvert;
4206 type = builder.makeIntType(32);
4207 break;
4208 case glslang::EOpConvUint64ToInt:
4209 convOp = spv::OpUConvert;
4210 type = builder.makeUintType(32);
4211 break;
4212 case glslang::EOpConvUintToInt64:
4213 convOp = spv::OpUConvert;
4214 type = builder.makeUintType(64);
4215 break;
4216 default:
4217 assert(0);
4218 break;
4219 }
4220
4221 if (vectorSize > 0)
4222 type = builder.makeVectorType(type, vectorSize);
4223
4224 operand = builder.createUnaryOp(convOp, type, operand);
4225
4226 if (builder.isInSpecConstCodeGenMode()) {
4227 // Build zero scalar or vector for OpIAdd.
4228 zero = (op == glslang::EOpConvIntToUint64 ||
4229 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4230 zero = makeSmearedConstant(zero, vectorSize);
4231 // Use OpIAdd, instead of OpBitcast to do the conversion when
4232 // generating for OpSpecConstantOp instruction.
4233 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4234 }
4235 // For normal run-time conversion instruction, use OpBitcast.
4236 convOp = spv::OpBitcast;
4237 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004238 default:
4239 break;
4240 }
4241
4242 spv::Id result = 0;
4243 if (convOp == spv::OpNop)
4244 return result;
4245
4246 if (convOp == spv::OpSelect) {
4247 zero = makeSmearedConstant(zero, vectorSize);
4248 one = makeSmearedConstant(one, vectorSize);
4249 result = builder.createTriOp(convOp, destType, operand, one, zero);
4250 } else
4251 result = builder.createUnaryOp(convOp, destType, operand);
4252
John Kessenich32cfd492016-02-02 12:37:46 -07004253 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004254}
4255
4256spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4257{
4258 if (vectorSize == 0)
4259 return constant;
4260
4261 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4262 std::vector<spv::Id> components;
4263 for (int c = 0; c < vectorSize; ++c)
4264 components.push_back(constant);
4265 return builder.makeCompositeConstant(vectorTypeId, components);
4266}
4267
John Kessenich426394d2015-07-23 10:22:48 -06004268// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004269spv::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 -06004270{
4271 spv::Op opCode = spv::OpNop;
4272
4273 switch (op) {
4274 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004275 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004276 opCode = spv::OpAtomicIAdd;
4277 break;
4278 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004279 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004280 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004281 break;
4282 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004283 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004284 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004285 break;
4286 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004287 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004288 opCode = spv::OpAtomicAnd;
4289 break;
4290 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004291 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004292 opCode = spv::OpAtomicOr;
4293 break;
4294 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004295 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004296 opCode = spv::OpAtomicXor;
4297 break;
4298 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004299 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004300 opCode = spv::OpAtomicExchange;
4301 break;
4302 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004303 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004304 opCode = spv::OpAtomicCompareExchange;
4305 break;
4306 case glslang::EOpAtomicCounterIncrement:
4307 opCode = spv::OpAtomicIIncrement;
4308 break;
4309 case glslang::EOpAtomicCounterDecrement:
4310 opCode = spv::OpAtomicIDecrement;
4311 break;
4312 case glslang::EOpAtomicCounter:
4313 opCode = spv::OpAtomicLoad;
4314 break;
4315 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004316 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004317 break;
4318 }
4319
4320 // Sort out the operands
4321 // - mapping from glslang -> SPV
4322 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004323 // - compare-exchange swaps the value and comparator
4324 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004325 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4326 auto opIt = operands.begin(); // walk the glslang operands
4327 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004328 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4329 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4330 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004331 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4332 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004333 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004334 spvAtomicOperands.push_back(*(opIt + 1));
4335 spvAtomicOperands.push_back(*opIt);
4336 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004337 }
John Kessenich426394d2015-07-23 10:22:48 -06004338
John Kessenich3e60a6f2015-09-14 22:45:16 -06004339 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004340 for (; opIt != operands.end(); ++opIt)
4341 spvAtomicOperands.push_back(*opIt);
4342
4343 return builder.createOp(opCode, typeId, spvAtomicOperands);
4344}
4345
John Kessenich91cef522016-05-05 16:45:40 -06004346// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004347spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004348{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004349#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004350 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004351 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004352#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004353
Rex Xu51596642016-09-21 18:56:12 +08004354 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004355 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004356 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4357
chaocf200da82016-12-20 12:44:35 -08004358 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4359 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004360 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4361 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004362 } else if (op == glslang::EOpAnyInvocation ||
4363 op == glslang::EOpAllInvocations ||
4364 op == glslang::EOpAllInvocationsEqual) {
4365 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4366 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004367 } else {
4368 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004369#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004370 if (op == glslang::EOpMinInvocationsNonUniform ||
4371 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004372 op == glslang::EOpAddInvocationsNonUniform ||
4373 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4374 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4375 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4376 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4377 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4378 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004379 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004380#endif
Rex Xu51596642016-09-21 18:56:12 +08004381
4382 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004383#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004384 switch (op) {
4385 case glslang::EOpMinInvocations:
4386 case glslang::EOpMaxInvocations:
4387 case glslang::EOpAddInvocations:
4388 case glslang::EOpMinInvocationsNonUniform:
4389 case glslang::EOpMaxInvocationsNonUniform:
4390 case glslang::EOpAddInvocationsNonUniform:
4391 groupOperation = spv::GroupOperationReduce;
4392 spvGroupOperands.push_back(groupOperation);
4393 break;
4394 case glslang::EOpMinInvocationsInclusiveScan:
4395 case glslang::EOpMaxInvocationsInclusiveScan:
4396 case glslang::EOpAddInvocationsInclusiveScan:
4397 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4398 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4399 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4400 groupOperation = spv::GroupOperationInclusiveScan;
4401 spvGroupOperands.push_back(groupOperation);
4402 break;
4403 case glslang::EOpMinInvocationsExclusiveScan:
4404 case glslang::EOpMaxInvocationsExclusiveScan:
4405 case glslang::EOpAddInvocationsExclusiveScan:
4406 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4407 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4408 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4409 groupOperation = spv::GroupOperationExclusiveScan;
4410 spvGroupOperands.push_back(groupOperation);
4411 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004412 default:
4413 break;
Rex Xu430ef402016-10-14 17:22:23 +08004414 }
Rex Xu9d93a232016-05-05 12:30:44 +08004415#endif
Rex Xu51596642016-09-21 18:56:12 +08004416 }
4417
4418 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4419 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004420
4421 switch (op) {
4422 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004423 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004424 break;
John Kessenich91cef522016-05-05 16:45:40 -06004425 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004426 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004427 break;
John Kessenich91cef522016-05-05 16:45:40 -06004428 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004429 opCode = spv::OpSubgroupAllEqualKHR;
4430 break;
Rex Xu51596642016-09-21 18:56:12 +08004431 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004432 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004433 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004434 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004435 break;
4436 case glslang::EOpReadFirstInvocation:
4437 opCode = spv::OpSubgroupFirstInvocationKHR;
4438 break;
4439 case glslang::EOpBallot:
4440 {
4441 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4442 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4443 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4444 //
4445 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4446 //
4447 spv::Id uintType = builder.makeUintType(32);
4448 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4449 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4450
4451 std::vector<spv::Id> components;
4452 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4453 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4454
4455 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4456 return builder.createUnaryOp(spv::OpBitcast, typeId,
4457 builder.createCompositeConstruct(uvec2Type, components));
4458 }
4459
Rex Xu9d93a232016-05-05 12:30:44 +08004460#ifdef AMD_EXTENSIONS
4461 case glslang::EOpMinInvocations:
4462 case glslang::EOpMaxInvocations:
4463 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004464 case glslang::EOpMinInvocationsInclusiveScan:
4465 case glslang::EOpMaxInvocationsInclusiveScan:
4466 case glslang::EOpAddInvocationsInclusiveScan:
4467 case glslang::EOpMinInvocationsExclusiveScan:
4468 case glslang::EOpMaxInvocationsExclusiveScan:
4469 case glslang::EOpAddInvocationsExclusiveScan:
4470 if (op == glslang::EOpMinInvocations ||
4471 op == glslang::EOpMinInvocationsInclusiveScan ||
4472 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004473 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004474 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004475 else {
4476 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004477 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004478 else
Rex Xu51596642016-09-21 18:56:12 +08004479 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004480 }
Rex Xu430ef402016-10-14 17:22:23 +08004481 } else if (op == glslang::EOpMaxInvocations ||
4482 op == glslang::EOpMaxInvocationsInclusiveScan ||
4483 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004484 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004485 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004486 else {
4487 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004488 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004489 else
Rex Xu51596642016-09-21 18:56:12 +08004490 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004491 }
4492 } else {
4493 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004494 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004495 else
Rex Xu51596642016-09-21 18:56:12 +08004496 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004497 }
4498
Rex Xu2bbbe062016-08-23 15:41:05 +08004499 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004500 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004501
4502 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004503 case glslang::EOpMinInvocationsNonUniform:
4504 case glslang::EOpMaxInvocationsNonUniform:
4505 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004506 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4507 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4508 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4509 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4510 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4511 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4512 if (op == glslang::EOpMinInvocationsNonUniform ||
4513 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4514 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004515 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004516 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004517 else {
4518 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004519 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004520 else
Rex Xu51596642016-09-21 18:56:12 +08004521 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004522 }
4523 }
Rex Xu430ef402016-10-14 17:22:23 +08004524 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4525 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4526 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004527 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004528 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004529 else {
4530 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004531 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004532 else
Rex Xu51596642016-09-21 18:56:12 +08004533 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004534 }
4535 }
4536 else {
4537 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004538 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004539 else
Rex Xu51596642016-09-21 18:56:12 +08004540 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004541 }
4542
Rex Xu2bbbe062016-08-23 15:41:05 +08004543 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004544 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004545
4546 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004547#endif
John Kessenich91cef522016-05-05 16:45:40 -06004548 default:
4549 logger->missingFunctionality("invocation operation");
4550 return spv::NoResult;
4551 }
Rex Xu51596642016-09-21 18:56:12 +08004552
4553 assert(opCode != spv::OpNop);
4554 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004555}
4556
Rex Xu2bbbe062016-08-23 15:41:05 +08004557// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004558spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004559{
Rex Xub7072052016-09-26 15:53:40 +08004560#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004561 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4562 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004563 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004564 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004565 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4566 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4567 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004568#else
4569 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4570 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004571 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4572 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004573#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004574
4575 // Handle group invocation operations scalar by scalar.
4576 // The result type is the same type as the original type.
4577 // The algorithm is to:
4578 // - break the vector into scalars
4579 // - apply the operation to each scalar
4580 // - make a vector out the scalar results
4581
4582 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004583 int numComponents = builder.getNumComponents(operands[0]);
4584 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004585 std::vector<spv::Id> results;
4586
4587 // do each scalar op
4588 for (int comp = 0; comp < numComponents; ++comp) {
4589 std::vector<unsigned int> indexes;
4590 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004591 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004592 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004593 if (op == spv::OpSubgroupReadInvocationKHR) {
4594 spvGroupOperands.push_back(scalar);
4595 spvGroupOperands.push_back(operands[1]);
4596 } else if (op == spv::OpGroupBroadcast) {
4597 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004598 spvGroupOperands.push_back(scalar);
4599 spvGroupOperands.push_back(operands[1]);
4600 } else {
chaocf200da82016-12-20 12:44:35 -08004601 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004602 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004603 spvGroupOperands.push_back(scalar);
4604 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004605
Rex Xub7072052016-09-26 15:53:40 +08004606 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004607 }
4608
4609 // put the pieces together
4610 return builder.createCompositeConstruct(typeId, results);
4611}
Rex Xu2bbbe062016-08-23 15:41:05 +08004612
John Kessenich5e4b1242015-08-06 22:53:06 -06004613spv::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 -06004614{
Rex Xu8ff43de2016-04-22 16:51:45 +08004615 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004616#ifdef AMD_EXTENSIONS
4617 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4618#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004619 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004620#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004621
John Kessenich140f3df2015-06-26 16:58:36 -06004622 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004623 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004624 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004625 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004626 spv::Id typeId0 = 0;
4627 if (consumedOperands > 0)
4628 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08004629 spv::Id typeId1 = 0;
4630 if (consumedOperands > 1)
4631 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07004632 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004633
4634 switch (op) {
4635 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004636 if (isFloat)
4637 libCall = spv::GLSLstd450FMin;
4638 else if (isUnsigned)
4639 libCall = spv::GLSLstd450UMin;
4640 else
4641 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004642 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004643 break;
4644 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004645 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004646 break;
4647 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004648 if (isFloat)
4649 libCall = spv::GLSLstd450FMax;
4650 else if (isUnsigned)
4651 libCall = spv::GLSLstd450UMax;
4652 else
4653 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004654 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004655 break;
4656 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004657 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004658 break;
4659 case glslang::EOpDot:
4660 opCode = spv::OpDot;
4661 break;
4662 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004663 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004664 break;
4665
4666 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004667 if (isFloat)
4668 libCall = spv::GLSLstd450FClamp;
4669 else if (isUnsigned)
4670 libCall = spv::GLSLstd450UClamp;
4671 else
4672 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004673 builder.promoteScalar(precision, operands.front(), operands[1]);
4674 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004675 break;
4676 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004677 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4678 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004679 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004680 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004681 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004682 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004683 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004684 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004685 break;
4686 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004687 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004688 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004689 break;
4690 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004691 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004692 builder.promoteScalar(precision, operands[0], operands[2]);
4693 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004694 break;
4695
4696 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004697 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004698 break;
4699 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004700 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004701 break;
4702 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004703 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004704 break;
4705 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004706 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004707 break;
4708 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004709 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004710 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004711 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004712 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004713 libCall = spv::GLSLstd450InterpolateAtSample;
4714 break;
4715 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004716 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004717 libCall = spv::GLSLstd450InterpolateAtOffset;
4718 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004719 case glslang::EOpAddCarry:
4720 opCode = spv::OpIAddCarry;
4721 typeId = builder.makeStructResultType(typeId0, typeId0);
4722 consumedOperands = 2;
4723 break;
4724 case glslang::EOpSubBorrow:
4725 opCode = spv::OpISubBorrow;
4726 typeId = builder.makeStructResultType(typeId0, typeId0);
4727 consumedOperands = 2;
4728 break;
4729 case glslang::EOpUMulExtended:
4730 opCode = spv::OpUMulExtended;
4731 typeId = builder.makeStructResultType(typeId0, typeId0);
4732 consumedOperands = 2;
4733 break;
4734 case glslang::EOpIMulExtended:
4735 opCode = spv::OpSMulExtended;
4736 typeId = builder.makeStructResultType(typeId0, typeId0);
4737 consumedOperands = 2;
4738 break;
4739 case glslang::EOpBitfieldExtract:
4740 if (isUnsigned)
4741 opCode = spv::OpBitFieldUExtract;
4742 else
4743 opCode = spv::OpBitFieldSExtract;
4744 break;
4745 case glslang::EOpBitfieldInsert:
4746 opCode = spv::OpBitFieldInsert;
4747 break;
4748
4749 case glslang::EOpFma:
4750 libCall = spv::GLSLstd450Fma;
4751 break;
4752 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004753 {
4754 libCall = spv::GLSLstd450FrexpStruct;
4755 assert(builder.isPointerType(typeId1));
4756 typeId1 = builder.getContainedTypeId(typeId1);
4757#ifdef AMD_EXTENSIONS
4758 int width = builder.getScalarTypeWidth(typeId1);
4759#else
4760 int width = 32;
4761#endif
4762 if (builder.getNumComponents(operands[0]) == 1)
4763 frexpIntType = builder.makeIntegerType(width, true);
4764 else
4765 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
4766 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4767 consumedOperands = 1;
4768 }
John Kessenich55e7d112015-11-15 21:33:39 -07004769 break;
4770 case glslang::EOpLdexp:
4771 libCall = spv::GLSLstd450Ldexp;
4772 break;
4773
Rex Xu574ab042016-04-14 16:53:07 +08004774 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004775 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004776
Rex Xu9d93a232016-05-05 12:30:44 +08004777#ifdef AMD_EXTENSIONS
4778 case glslang::EOpSwizzleInvocations:
4779 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4780 libCall = spv::SwizzleInvocationsAMD;
4781 break;
4782 case glslang::EOpSwizzleInvocationsMasked:
4783 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4784 libCall = spv::SwizzleInvocationsMaskedAMD;
4785 break;
4786 case glslang::EOpWriteInvocation:
4787 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4788 libCall = spv::WriteInvocationAMD;
4789 break;
4790
4791 case glslang::EOpMin3:
4792 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4793 if (isFloat)
4794 libCall = spv::FMin3AMD;
4795 else {
4796 if (isUnsigned)
4797 libCall = spv::UMin3AMD;
4798 else
4799 libCall = spv::SMin3AMD;
4800 }
4801 break;
4802 case glslang::EOpMax3:
4803 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4804 if (isFloat)
4805 libCall = spv::FMax3AMD;
4806 else {
4807 if (isUnsigned)
4808 libCall = spv::UMax3AMD;
4809 else
4810 libCall = spv::SMax3AMD;
4811 }
4812 break;
4813 case glslang::EOpMid3:
4814 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4815 if (isFloat)
4816 libCall = spv::FMid3AMD;
4817 else {
4818 if (isUnsigned)
4819 libCall = spv::UMid3AMD;
4820 else
4821 libCall = spv::SMid3AMD;
4822 }
4823 break;
4824
4825 case glslang::EOpInterpolateAtVertex:
4826 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4827 libCall = spv::InterpolateAtVertexAMD;
4828 break;
4829#endif
4830
John Kessenich140f3df2015-06-26 16:58:36 -06004831 default:
4832 return 0;
4833 }
4834
4835 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004836 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004837 // Use an extended instruction from the standard library.
4838 // Construct the call arguments, without modifying the original operands vector.
4839 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4840 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004841 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004842 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004843 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004844 case 0:
4845 // should all be handled by visitAggregate and createNoArgOperation
4846 assert(0);
4847 return 0;
4848 case 1:
4849 // should all be handled by createUnaryOperation
4850 assert(0);
4851 return 0;
4852 case 2:
4853 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4854 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004855 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004856 // anything 3 or over doesn't have l-value operands, so all should be consumed
4857 assert(consumedOperands == operands.size());
4858 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004859 break;
4860 }
4861 }
4862
John Kessenich55e7d112015-11-15 21:33:39 -07004863 // Decode the return types that were structures
4864 switch (op) {
4865 case glslang::EOpAddCarry:
4866 case glslang::EOpSubBorrow:
4867 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4868 id = builder.createCompositeExtract(id, typeId0, 0);
4869 break;
4870 case glslang::EOpUMulExtended:
4871 case glslang::EOpIMulExtended:
4872 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4873 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4874 break;
4875 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004876 {
4877 assert(operands.size() == 2);
4878 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
4879 // "exp" is floating-point type (from HLSL intrinsic)
4880 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
4881 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
4882 builder.createStore(member1, operands[1]);
4883 } else
4884 // "exp" is integer type (from GLSL built-in function)
4885 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4886 id = builder.createCompositeExtract(id, typeId0, 0);
4887 }
John Kessenich55e7d112015-11-15 21:33:39 -07004888 break;
4889 default:
4890 break;
4891 }
4892
John Kessenich32cfd492016-02-02 12:37:46 -07004893 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004894}
4895
Rex Xu9d93a232016-05-05 12:30:44 +08004896// Intrinsics with no arguments (or no return value, and no precision).
4897spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004898{
4899 // TODO: get the barrier operands correct
4900
4901 switch (op) {
4902 case glslang::EOpEmitVertex:
4903 builder.createNoResultOp(spv::OpEmitVertex);
4904 return 0;
4905 case glslang::EOpEndPrimitive:
4906 builder.createNoResultOp(spv::OpEndPrimitive);
4907 return 0;
4908 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004909 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004910 return 0;
4911 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004912 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004913 return 0;
4914 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004915 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004916 return 0;
4917 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004918 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004919 return 0;
4920 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004921 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004922 return 0;
4923 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004924 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004925 return 0;
4926 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004927 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004928 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004929 case glslang::EOpAllMemoryBarrierWithGroupSync:
4930 // Control barrier with non-"None" semantic is also a memory barrier.
4931 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4932 return 0;
4933 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4934 // Control barrier with non-"None" semantic is also a memory barrier.
4935 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4936 return 0;
4937 case glslang::EOpWorkgroupMemoryBarrier:
4938 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4939 return 0;
4940 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4941 // Control barrier with non-"None" semantic is also a memory barrier.
4942 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4943 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004944#ifdef AMD_EXTENSIONS
4945 case glslang::EOpTime:
4946 {
4947 std::vector<spv::Id> args; // Dummy arguments
4948 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4949 return builder.setPrecision(id, precision);
4950 }
4951#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004952 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004953 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004954 return 0;
4955 }
4956}
4957
4958spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
4959{
John Kessenich2f273362015-07-18 22:34:27 -06004960 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06004961 spv::Id id;
4962 if (symbolValues.end() != iter) {
4963 id = iter->second;
4964 return id;
4965 }
4966
4967 // it was not found, create it
4968 id = createSpvVariable(symbol);
4969 symbolValues[symbol->getId()] = id;
4970
Rex Xuc884b4a2016-06-29 15:03:44 +08004971 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06004972 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07004973 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08004974 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07004975 if (symbol->getType().getQualifier().hasSpecConstantId())
4976 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06004977 if (symbol->getQualifier().hasIndex())
4978 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
4979 if (symbol->getQualifier().hasComponent())
4980 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
4981 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07004982 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06004983 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06004984 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06004985 if (symbol->getQualifier().hasXfbBuffer())
4986 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
4987 if (symbol->getQualifier().hasXfbOffset())
4988 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
4989 }
John Kessenich91e4aa52016-07-07 17:46:42 -06004990 // atomic counters use this:
4991 if (symbol->getQualifier().hasOffset())
4992 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06004993 }
4994
scygan2c864272016-05-18 18:09:17 +02004995 if (symbol->getQualifier().hasLocation())
4996 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07004997 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07004998 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07004999 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005000 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005001 }
John Kessenich140f3df2015-06-26 16:58:36 -06005002 if (symbol->getQualifier().hasSet())
5003 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005004 else if (IsDescriptorResource(symbol->getType())) {
5005 // default to 0
5006 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5007 }
John Kessenich140f3df2015-06-26 16:58:36 -06005008 if (symbol->getQualifier().hasBinding())
5009 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005010 if (symbol->getQualifier().hasAttachment())
5011 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005012 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005013 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005014 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005015 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005016 if (symbol->getQualifier().hasXfbBuffer())
5017 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5018 }
5019
Rex Xu1da878f2016-02-21 20:59:01 +08005020 if (symbol->getType().isImage()) {
5021 std::vector<spv::Decoration> memory;
5022 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5023 for (unsigned int i = 0; i < memory.size(); ++i)
5024 addDecoration(id, memory[i]);
5025 }
5026
John Kessenich140f3df2015-06-26 16:58:36 -06005027 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005028 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005029 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005030 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005031
John Kessenichecba76f2017-01-06 00:34:48 -07005032#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005033 if (builtIn == spv::BuiltInSampleMask) {
5034 spv::Decoration decoration;
5035 // GL_NV_sample_mask_override_coverage extension
5036 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005037 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005038 else
5039 decoration = (spv::Decoration)spv::DecorationMax;
5040 addDecoration(id, decoration);
5041 if (decoration != spv::DecorationMax) {
5042 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5043 }
5044 }
chaoc771d89f2017-01-13 01:10:53 -08005045 else if (builtIn == spv::BuiltInLayer) {
5046 // SPV_NV_viewport_array2 extension
5047 if (symbol->getQualifier().layoutViewportRelative)
5048 {
5049 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5050 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5051 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5052 }
5053 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5054 {
5055 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5056 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5057 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5058 }
5059 }
5060
chaoc6e5acae2016-12-20 13:28:52 -08005061 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005062 addDecoration(id, spv::DecorationPassthroughNV);
5063 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005064 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5065 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005066#endif
5067
John Kessenich140f3df2015-06-26 16:58:36 -06005068 return id;
5069}
5070
John Kessenich55e7d112015-11-15 21:33:39 -07005071// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005072void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5073{
John Kessenich4016e382016-07-15 11:53:56 -06005074 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005075 builder.addDecoration(id, dec);
5076}
5077
John Kessenich55e7d112015-11-15 21:33:39 -07005078// If 'dec' is valid, add a one-operand decoration to an object
5079void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5080{
John Kessenich4016e382016-07-15 11:53:56 -06005081 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005082 builder.addDecoration(id, dec, value);
5083}
5084
5085// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005086void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5087{
John Kessenich4016e382016-07-15 11:53:56 -06005088 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005089 builder.addMemberDecoration(id, (unsigned)member, dec);
5090}
5091
John Kessenich92187592016-02-01 13:45:25 -07005092// If 'dec' is valid, add a one-operand decoration to a struct member
5093void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5094{
John Kessenich4016e382016-07-15 11:53:56 -06005095 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005096 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5097}
5098
John Kessenich55e7d112015-11-15 21:33:39 -07005099// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005100// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005101//
5102// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5103//
5104// Recursively walk the nodes. The nodes form a tree whose leaves are
5105// regular constants, which themselves are trees that createSpvConstant()
5106// recursively walks. So, this function walks the "top" of the tree:
5107// - emit specialization constant-building instructions for specConstant
5108// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005109spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005110{
John Kessenich7cc0e282016-03-20 00:46:02 -06005111 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005112
qining4f4bb812016-04-03 23:55:17 -04005113 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005114 if (! node.getQualifier().specConstant) {
5115 // hand off to the non-spec-constant path
5116 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5117 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005118 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005119 nextConst, false);
5120 }
5121
5122 // We now know we have a specialization constant to build
5123
John Kessenichd94c0032016-05-30 19:29:40 -06005124 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005125 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5126 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5127 std::vector<spv::Id> dimConstId;
5128 for (int dim = 0; dim < 3; ++dim) {
5129 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5130 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5131 if (specConst)
5132 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5133 }
5134 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5135 }
5136
5137 // An AST node labelled as specialization constant should be a symbol node.
5138 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5139 if (auto* sn = node.getAsSymbolNode()) {
5140 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005141 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5142 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5143 // will set the builder into spec constant op instruction generating mode.
5144 sub_tree->traverse(this);
5145 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005146 } else if (auto* const_union_array = &sn->getConstArray()){
5147 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005148 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5149 builder.addName(id, sn->getName().c_str());
5150 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005151 }
5152 }
qining4f4bb812016-04-03 23:55:17 -04005153
5154 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5155 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005156 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005157 exit(1);
5158 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005159}
5160
John Kessenich140f3df2015-06-26 16:58:36 -06005161// Use 'consts' as the flattened glslang source of scalar constants to recursively
5162// build the aggregate SPIR-V constant.
5163//
5164// If there are not enough elements present in 'consts', 0 will be substituted;
5165// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5166//
qining08408382016-03-21 09:51:37 -04005167spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005168{
5169 // vector of constants for SPIR-V
5170 std::vector<spv::Id> spvConsts;
5171
5172 // Type is used for struct and array constants
5173 spv::Id typeId = convertGlslangToSpvType(glslangType);
5174
5175 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005176 glslang::TType elementType(glslangType, 0);
5177 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005178 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005179 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005180 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005181 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005182 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005183 } else if (glslangType.getStruct()) {
5184 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5185 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005186 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005187 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005188 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5189 bool zero = nextConst >= consts.size();
5190 switch (glslangType.getBasicType()) {
5191 case glslang::EbtInt:
5192 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5193 break;
5194 case glslang::EbtUint:
5195 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5196 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005197 case glslang::EbtInt64:
5198 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5199 break;
5200 case glslang::EbtUint64:
5201 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5202 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005203 case glslang::EbtFloat:
5204 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5205 break;
5206 case glslang::EbtDouble:
5207 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5208 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005209#ifdef AMD_EXTENSIONS
5210 case glslang::EbtFloat16:
5211 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5212 break;
5213#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005214 case glslang::EbtBool:
5215 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5216 break;
5217 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005218 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005219 break;
5220 }
5221 ++nextConst;
5222 }
5223 } else {
5224 // we have a non-aggregate (scalar) constant
5225 bool zero = nextConst >= consts.size();
5226 spv::Id scalar = 0;
5227 switch (glslangType.getBasicType()) {
5228 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005229 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005230 break;
5231 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005232 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005233 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005234 case glslang::EbtInt64:
5235 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5236 break;
5237 case glslang::EbtUint64:
5238 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5239 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005240 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005241 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005242 break;
5243 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005244 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005245 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005246#ifdef AMD_EXTENSIONS
5247 case glslang::EbtFloat16:
5248 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5249 break;
5250#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005251 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005252 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005253 break;
5254 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005255 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005256 break;
5257 }
5258 ++nextConst;
5259 return scalar;
5260 }
5261
5262 return builder.makeCompositeConstant(typeId, spvConsts);
5263}
5264
John Kessenich7c1aa102015-10-15 13:29:11 -06005265// Return true if the node is a constant or symbol whose reading has no
5266// non-trivial observable cost or effect.
5267bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5268{
5269 // don't know what this is
5270 if (node == nullptr)
5271 return false;
5272
5273 // a constant is safe
5274 if (node->getAsConstantUnion() != nullptr)
5275 return true;
5276
5277 // not a symbol means non-trivial
5278 if (node->getAsSymbolNode() == nullptr)
5279 return false;
5280
5281 // a symbol, depends on what's being read
5282 switch (node->getType().getQualifier().storage) {
5283 case glslang::EvqTemporary:
5284 case glslang::EvqGlobal:
5285 case glslang::EvqIn:
5286 case glslang::EvqInOut:
5287 case glslang::EvqConst:
5288 case glslang::EvqConstReadOnly:
5289 case glslang::EvqUniform:
5290 return true;
5291 default:
5292 return false;
5293 }
qining25262b32016-05-06 17:25:16 -04005294}
John Kessenich7c1aa102015-10-15 13:29:11 -06005295
5296// A node is trivial if it is a single operation with no side effects.
5297// Error on the side of saying non-trivial.
5298// Return true if trivial.
5299bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5300{
5301 if (node == nullptr)
5302 return false;
5303
5304 // symbols and constants are trivial
5305 if (isTrivialLeaf(node))
5306 return true;
5307
5308 // otherwise, it needs to be a simple operation or one or two leaf nodes
5309
5310 // not a simple operation
5311 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5312 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5313 if (binaryNode == nullptr && unaryNode == nullptr)
5314 return false;
5315
5316 // not on leaf nodes
5317 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5318 return false;
5319
5320 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5321 return false;
5322 }
5323
5324 switch (node->getAsOperator()->getOp()) {
5325 case glslang::EOpLogicalNot:
5326 case glslang::EOpConvIntToBool:
5327 case glslang::EOpConvUintToBool:
5328 case glslang::EOpConvFloatToBool:
5329 case glslang::EOpConvDoubleToBool:
5330 case glslang::EOpEqual:
5331 case glslang::EOpNotEqual:
5332 case glslang::EOpLessThan:
5333 case glslang::EOpGreaterThan:
5334 case glslang::EOpLessThanEqual:
5335 case glslang::EOpGreaterThanEqual:
5336 case glslang::EOpIndexDirect:
5337 case glslang::EOpIndexDirectStruct:
5338 case glslang::EOpLogicalXor:
5339 case glslang::EOpAny:
5340 case glslang::EOpAll:
5341 return true;
5342 default:
5343 return false;
5344 }
5345}
5346
5347// Emit short-circuiting code, where 'right' is never evaluated unless
5348// the left side is true (for &&) or false (for ||).
5349spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5350{
5351 spv::Id boolTypeId = builder.makeBoolType();
5352
5353 // emit left operand
5354 builder.clearAccessChain();
5355 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005356 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005357
5358 // Operands to accumulate OpPhi operands
5359 std::vector<spv::Id> phiOperands;
5360 // accumulate left operand's phi information
5361 phiOperands.push_back(leftId);
5362 phiOperands.push_back(builder.getBuildPoint()->getId());
5363
5364 // Make the two kinds of operation symmetric with a "!"
5365 // || => emit "if (! left) result = right"
5366 // && => emit "if ( left) result = right"
5367 //
5368 // TODO: this runtime "not" for || could be avoided by adding functionality
5369 // to 'builder' to have an "else" without an "then"
5370 if (op == glslang::EOpLogicalOr)
5371 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5372
5373 // make an "if" based on the left value
5374 spv::Builder::If ifBuilder(leftId, builder);
5375
5376 // emit right operand as the "then" part of the "if"
5377 builder.clearAccessChain();
5378 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005379 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005380
5381 // accumulate left operand's phi information
5382 phiOperands.push_back(rightId);
5383 phiOperands.push_back(builder.getBuildPoint()->getId());
5384
5385 // finish the "if"
5386 ifBuilder.makeEndIf();
5387
5388 // phi together the two results
5389 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5390}
5391
Rex Xu9d93a232016-05-05 12:30:44 +08005392// Return type Id of the imported set of extended instructions corresponds to the name.
5393// Import this set if it has not been imported yet.
5394spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5395{
5396 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5397 return extBuiltinMap[name];
5398 else {
Rex Xu51596642016-09-21 18:56:12 +08005399 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005400 spv::Id extBuiltins = builder.import(name);
5401 extBuiltinMap[name] = extBuiltins;
5402 return extBuiltins;
5403 }
5404}
5405
John Kessenich140f3df2015-06-26 16:58:36 -06005406}; // end anonymous namespace
5407
5408namespace glslang {
5409
John Kessenich68d78fd2015-07-12 19:28:10 -06005410void GetSpirvVersion(std::string& version)
5411{
John Kessenich9e55f632015-07-15 10:03:39 -06005412 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005413 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005414 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005415 version = buf;
5416}
5417
John Kessenich140f3df2015-06-26 16:58:36 -06005418// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005419void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005420{
5421 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005422 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005423 if (out.fail())
5424 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005425 for (int i = 0; i < (int)spirv.size(); ++i) {
5426 unsigned int word = spirv[i];
5427 out.write((const char*)&word, 4);
5428 }
5429 out.close();
5430}
5431
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005432// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005433void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005434{
5435 std::ofstream out;
5436 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005437 if (out.fail())
5438 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005439 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005440 if (varName != nullptr) {
5441 out << "\t #pragma once" << std::endl;
5442 out << "const uint32_t " << varName << "[] = {" << std::endl;
5443 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005444 const int WORDS_PER_LINE = 8;
5445 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5446 out << "\t";
5447 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5448 const unsigned int word = spirv[i + j];
5449 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5450 if (i + j + 1 < (int)spirv.size()) {
5451 out << ",";
5452 }
5453 }
5454 out << std::endl;
5455 }
Flavio15017db2017-02-15 14:29:33 -08005456 if (varName != nullptr) {
5457 out << "};";
5458 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005459 out.close();
5460}
5461
John Kessenich140f3df2015-06-26 16:58:36 -06005462//
5463// Set up the glslang traversal
5464//
5465void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5466{
Lei Zhang17535f72016-05-04 15:55:59 -04005467 spv::SpvBuildLogger logger;
5468 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005469}
5470
Lei Zhang17535f72016-05-04 15:55:59 -04005471void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005472{
John Kessenich140f3df2015-06-26 16:58:36 -06005473 TIntermNode* root = intermediate.getTreeRoot();
5474
5475 if (root == 0)
5476 return;
5477
5478 glslang::GetThreadPoolAllocator().push();
5479
Lei Zhang17535f72016-05-04 15:55:59 -04005480 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005481 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005482 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005483 it.dumpSpv(spirv);
5484
5485 glslang::GetThreadPoolAllocator().pop();
5486}
5487
5488}; // end namespace glslang