blob: 9e5676d7cb5b0feeca7f432210fb69ac4cd21568 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
John Kessenich927608b2017-01-06 12:34:14 -070023// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34// POSSIBILITY OF SUCH DAMAGE.
John Kessenich140f3df2015-06-26 16:58:36 -060035
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080050#ifdef NV_EXTENSIONS
51 #include "GLSL.ext.NV.h"
52#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
John Kessenich55e7d112015-11-15 21:33:39 -070071// For low-order part of the generator's magic number. Bump up
72// when there is a change in the style (e.g., if SSA form changes,
73// or a different instruction sequence to do something gets used).
74const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060075
qining4c912612016-04-01 10:35:16 -040076namespace {
77class SpecConstantOpModeGuard {
78public:
79 SpecConstantOpModeGuard(spv::Builder* builder)
80 : builder_(builder) {
81 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040082 }
83 ~SpecConstantOpModeGuard() {
84 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
85 : builder_->setToNormalCodeGenMode();
86 }
qining40887662016-04-03 22:20:42 -040087 void turnOnSpecConstantOpMode() {
88 builder_->setToSpecConstCodeGenMode();
89 }
qining4c912612016-04-01 10:35:16 -040090
91private:
92 spv::Builder* builder_;
93 bool previous_flag_;
94};
95}
96
John Kessenich140f3df2015-06-26 16:58:36 -060097//
98// The main holder of information for translating glslang to SPIR-V.
99//
100// Derives from the AST walking base class.
101//
102class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
103public:
Lei Zhang17535f72016-05-04 15:55:59 -0400104 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenichfca82622016-11-26 13:23:20 -0700105 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600106
107 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
108 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
109 void visitConstantUnion(glslang::TIntermConstantUnion*);
110 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
111 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
112 void visitSymbol(glslang::TIntermSymbol* symbol);
113 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
114 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
115 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
116
John Kessenichfca82622016-11-26 13:23:20 -0700117 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700118 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600119
120protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800121 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800122 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100123 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700124 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600125 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
126 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600127 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
128 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
129 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600130 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700131 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600132 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600133 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
134 glslang::TLayoutPacking, const glslang::TQualifier&);
135 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
136 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700137 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700138 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800139 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600140 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700141 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700142 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
143 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
144 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100145 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600146
John Kessenich6fccb3c2016-09-19 16:01:41 -0600147 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600148 void makeFunctions(const glslang::TIntermSequence&);
149 void makeGlobalInitializers(const glslang::TIntermSequence&);
150 void visitFunctions(const glslang::TIntermSequence&);
151 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800152 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600153 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
154 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600155 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
156
qining25262b32016-05-06 17:25:16 -0400157 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
158 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
159 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800160 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800161 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600162 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800163 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800164 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800165 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600166 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800167 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600168 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
169 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700170 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600171 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700172 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400173 spv::Id createSpvConstant(const glslang::TIntermTyped&);
174 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600175 bool isTrivialLeaf(const glslang::TIntermTyped* node);
176 bool isTrivial(const glslang::TIntermTyped* node);
177 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800178 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600179
180 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600181 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700182 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600183 int sequenceDepth;
184
Lei Zhang17535f72016-05-04 15:55:59 -0400185 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400186
John Kessenich140f3df2015-06-26 16:58:36 -0600187 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
188 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700189 bool inEntryPoint;
190 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700191 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700192 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600193 const glslang::TIntermediate* glslangIntermediate;
194 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800195 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600196
John Kessenich2f273362015-07-18 22:34:27 -0600197 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600198 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600199 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700200 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600201 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600202 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600203};
204
205//
206// Helper functions for translating glslang representations to SPIR-V enumerants.
207//
208
209// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700210spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600211{
John Kessenich66e2faf2016-03-12 18:34:36 -0700212 switch (source) {
213 case glslang::EShSourceGlsl:
214 switch (profile) {
215 case ENoProfile:
216 case ECoreProfile:
217 case ECompatibilityProfile:
218 return spv::SourceLanguageGLSL;
219 case EEsProfile:
220 return spv::SourceLanguageESSL;
221 default:
222 return spv::SourceLanguageUnknown;
223 }
224 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600225 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600226 default:
227 return spv::SourceLanguageUnknown;
228 }
229}
230
231// Translate glslang language (stage) to SPIR-V execution model.
232spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
233{
234 switch (stage) {
235 case EShLangVertex: return spv::ExecutionModelVertex;
236 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
237 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
238 case EShLangGeometry: return spv::ExecutionModelGeometry;
239 case EShLangFragment: return spv::ExecutionModelFragment;
240 case EShLangCompute: return spv::ExecutionModelGLCompute;
241 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700242 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600243 return spv::ExecutionModelFragment;
244 }
245}
246
247// Translate glslang type to SPIR-V storage class.
John Kessenich67027182017-04-19 18:34:49 -0600248spv::StorageClass TranslateStorageClass(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600249{
250 if (type.getQualifier().isPipeInput())
251 return spv::StorageClassInput;
252 else if (type.getQualifier().isPipeOutput())
253 return spv::StorageClassOutput;
Jason Ekstrandc24cc292016-06-08 13:52:36 -0700254 else if (type.getBasicType() == glslang::EbtAtomicUint)
255 return spv::StorageClassAtomicCounter;
John Kessenich4a57dce2017-02-24 19:15:46 -0700256 else if (type.containsOpaque())
257 return spv::StorageClassUniformConstant;
John Kessenich67027182017-04-19 18:34:49 -0600258 else if (useStorageBuffer && type.getQualifier().storage == glslang::EvqBuffer)
259 return spv::StorageClassStorageBuffer;
John Kessenich140f3df2015-06-26 16:58:36 -0600260 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700261 if (type.getQualifier().layoutPushConstant)
262 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600263 if (type.getBasicType() == glslang::EbtBlock)
264 return spv::StorageClassUniform;
265 else
266 return spv::StorageClassUniformConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600267 } else {
268 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700269 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
270 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600271 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
272 case glslang::EvqTemporary: return spv::StorageClassFunction;
qining25262b32016-05-06 17:25:16 -0400273 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700274 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600275 return spv::StorageClassFunction;
276 }
277 }
278}
279
280// Translate glslang sampler type to SPIR-V dimensionality.
281spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
282{
283 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700284 case glslang::Esd1D: return spv::Dim1D;
285 case glslang::Esd2D: return spv::Dim2D;
286 case glslang::Esd3D: return spv::Dim3D;
287 case glslang::EsdCube: return spv::DimCube;
288 case glslang::EsdRect: return spv::DimRect;
289 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700290 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600291 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700292 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600293 return spv::Dim2D;
294 }
295}
296
John Kessenichf6640762016-08-01 19:44:00 -0600297// Translate glslang precision to SPIR-V precision decorations.
298spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600299{
John Kessenichf6640762016-08-01 19:44:00 -0600300 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700301 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600302 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600303 default:
304 return spv::NoPrecision;
305 }
306}
307
John Kessenichf6640762016-08-01 19:44:00 -0600308// Translate glslang type to SPIR-V precision decorations.
309spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
310{
311 return TranslatePrecisionDecoration(type.getQualifier().precision);
312}
313
John Kessenich140f3df2015-06-26 16:58:36 -0600314// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600315spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600316{
317 if (type.getBasicType() == glslang::EbtBlock) {
318 switch (type.getQualifier().storage) {
319 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600320 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600321 case glslang::EvqVaryingIn: return spv::DecorationBlock;
322 case glslang::EvqVaryingOut: return spv::DecorationBlock;
323 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700324 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600325 break;
326 }
327 }
328
John Kessenich4016e382016-07-15 11:53:56 -0600329 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600330}
331
Rex Xu1da878f2016-02-21 20:59:01 +0800332// Translate glslang type to SPIR-V memory decorations.
333void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
334{
335 if (qualifier.coherent)
336 memory.push_back(spv::DecorationCoherent);
337 if (qualifier.volatil)
338 memory.push_back(spv::DecorationVolatile);
339 if (qualifier.restrict)
340 memory.push_back(spv::DecorationRestrict);
341 if (qualifier.readonly)
342 memory.push_back(spv::DecorationNonWritable);
343 if (qualifier.writeonly)
344 memory.push_back(spv::DecorationNonReadable);
345}
346
John Kessenich140f3df2015-06-26 16:58:36 -0600347// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700348spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600349{
350 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700351 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600352 case glslang::ElmRowMajor:
353 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700354 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600355 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700356 default:
357 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600358 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600359 }
360 } else {
361 switch (type.getBasicType()) {
362 default:
John Kessenich4016e382016-07-15 11:53:56 -0600363 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600364 break;
365 case glslang::EbtBlock:
366 switch (type.getQualifier().storage) {
367 case glslang::EvqUniform:
368 case glslang::EvqBuffer:
369 switch (type.getQualifier().layoutPacking) {
370 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600371 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
372 default:
John Kessenich4016e382016-07-15 11:53:56 -0600373 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600374 }
375 case glslang::EvqVaryingIn:
376 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700377 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600378 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600379 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700380 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600381 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600382 }
383 }
384 }
385}
386
387// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600388// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700389// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800390spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600391{
Rex Xubbceed72016-05-21 09:40:44 +0800392 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700393 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600394 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800395 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700396 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700397 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600398 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800399#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800400 else if (qualifier.explicitInterp) {
401 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800402 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800403 }
Rex Xu9d93a232016-05-05 12:30:44 +0800404#endif
Rex Xubbceed72016-05-21 09:40:44 +0800405 else
John Kessenich4016e382016-07-15 11:53:56 -0600406 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800407}
408
409// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600410// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800411// should be applied.
412spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
413{
414 if (qualifier.patch)
415 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700416 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600417 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700418 else if (qualifier.sample) {
419 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600420 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700421 } else
John Kessenich4016e382016-07-15 11:53:56 -0600422 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600423}
424
John Kessenich92187592016-02-01 13:45:25 -0700425// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700426spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600427{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700428 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600429 return spv::DecorationInvariant;
430 else
John Kessenich4016e382016-07-15 11:53:56 -0600431 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600432}
433
qining9220dbb2016-05-04 17:34:38 -0400434// If glslang type is noContraction, return SPIR-V NoContraction decoration.
435spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
436{
437 if (qualifier.noContraction)
438 return spv::DecorationNoContraction;
439 else
John Kessenich4016e382016-07-15 11:53:56 -0600440 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400441}
442
David Netoa901ffe2016-06-08 14:11:40 +0100443// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
444// associated capabilities when required. For some built-in variables, a capability
445// is generated only when using the variable in an executable instruction, but not when
446// just declaring a struct member variable with it. This is true for PointSize,
447// ClipDistance, and CullDistance.
448spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600449{
450 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700451 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600452 // Defer adding the capability until the built-in is actually used.
453 if (! memberDeclaration) {
454 switch (glslangIntermediate->getStage()) {
455 case EShLangGeometry:
456 builder.addCapability(spv::CapabilityGeometryPointSize);
457 break;
458 case EShLangTessControl:
459 case EShLangTessEvaluation:
460 builder.addCapability(spv::CapabilityTessellationPointSize);
461 break;
462 default:
463 break;
464 }
John Kessenich92187592016-02-01 13:45:25 -0700465 }
466 return spv::BuiltInPointSize;
467
John Kessenichebb50532016-05-16 19:22:05 -0600468 // These *Distance capabilities logically belong here, but if the member is declared and
469 // then never used, consumers of SPIR-V prefer the capability not be declared.
470 // They are now generated when used, rather than here when declared.
471 // Potentially, the specification should be more clear what the minimum
472 // use needed is to trigger the capability.
473 //
John Kessenich92187592016-02-01 13:45:25 -0700474 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100475 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800476 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700477 return spv::BuiltInClipDistance;
478
479 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100480 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800481 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700482 return spv::BuiltInCullDistance;
483
484 case glslang::EbvViewportIndex:
Rex Xu5e317ff2017-03-16 23:02:39 +0800485 if (!memberDeclaration) {
486 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800487#ifdef NV_EXTENSIONS
Rex Xu5e317ff2017-03-16 23:02:39 +0800488 if (glslangIntermediate->getStage() == EShLangVertex ||
489 glslangIntermediate->getStage() == EShLangTessControl ||
490 glslangIntermediate->getStage() == EShLangTessEvaluation) {
491
492 builder.addExtension(spv::E_SPV_NV_viewport_array2);
493 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
494 }
chaoc771d89f2017-01-13 01:10:53 -0800495#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800496 }
John Kessenich92187592016-02-01 13:45:25 -0700497 return spv::BuiltInViewportIndex;
498
John Kessenich5e801132016-02-15 11:09:46 -0700499 case glslang::EbvSampleId:
500 builder.addCapability(spv::CapabilitySampleRateShading);
501 return spv::BuiltInSampleId;
502
503 case glslang::EbvSamplePosition:
504 builder.addCapability(spv::CapabilitySampleRateShading);
505 return spv::BuiltInSamplePosition;
506
507 case glslang::EbvSampleMask:
508 builder.addCapability(spv::CapabilitySampleRateShading);
509 return spv::BuiltInSampleMask;
510
John Kessenich78a45572016-07-08 14:05:15 -0600511 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800512 if (!memberDeclaration) {
513 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800514#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -0800515 if (glslangIntermediate->getStage() == EShLangVertex ||
516 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800517 glslangIntermediate->getStage() == EShLangTessEvaluation) {
518
chaoc771d89f2017-01-13 01:10:53 -0800519 builder.addExtension(spv::E_SPV_NV_viewport_array2);
520 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
521 }
chaoc771d89f2017-01-13 01:10:53 -0800522#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800523 }
524
John Kessenich78a45572016-07-08 14:05:15 -0600525 return spv::BuiltInLayer;
526
John Kessenich140f3df2015-06-26 16:58:36 -0600527 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600528 case glslang::EbvVertexId: return spv::BuiltInVertexId;
529 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700530 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
531 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800532
John Kessenichda581a22015-10-14 14:10:30 -0600533 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800534 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
535 builder.addCapability(spv::CapabilityDrawParameters);
536 return spv::BuiltInBaseVertex;
537
John Kessenichda581a22015-10-14 14:10:30 -0600538 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800539 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
540 builder.addCapability(spv::CapabilityDrawParameters);
541 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200542
John Kessenichda581a22015-10-14 14:10:30 -0600543 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800544 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
545 builder.addCapability(spv::CapabilityDrawParameters);
546 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200547
548 case glslang::EbvPrimitiveId:
549 if (glslangIntermediate->getStage() == EShLangFragment)
550 builder.addCapability(spv::CapabilityGeometry);
551 return spv::BuiltInPrimitiveId;
552
John Kessenich140f3df2015-06-26 16:58:36 -0600553 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600554 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
555 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
556 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
557 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
558 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
559 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
560 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600561 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
562 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
563 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
564 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
565 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
566 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
567 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
568 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800569
Rex Xu574ab042016-04-14 16:53:07 +0800570 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800571 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800572 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
573 return spv::BuiltInSubgroupSize;
574
Rex Xu574ab042016-04-14 16:53:07 +0800575 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800576 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800577 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
578 return spv::BuiltInSubgroupLocalInvocationId;
579
Rex Xu574ab042016-04-14 16:53:07 +0800580 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800581 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
582 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
583 return spv::BuiltInSubgroupEqMaskKHR;
584
Rex Xu574ab042016-04-14 16:53:07 +0800585 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800586 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
587 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
588 return spv::BuiltInSubgroupGeMaskKHR;
589
Rex Xu574ab042016-04-14 16:53:07 +0800590 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800591 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
592 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
593 return spv::BuiltInSubgroupGtMaskKHR;
594
Rex Xu574ab042016-04-14 16:53:07 +0800595 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800596 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
597 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
598 return spv::BuiltInSubgroupLeMaskKHR;
599
Rex Xu574ab042016-04-14 16:53:07 +0800600 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800601 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
602 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
603 return spv::BuiltInSubgroupLtMaskKHR;
604
Rex Xu9d93a232016-05-05 12:30:44 +0800605#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800606 case glslang::EbvBaryCoordNoPersp:
607 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
608 return spv::BuiltInBaryCoordNoPerspAMD;
609
610 case glslang::EbvBaryCoordNoPerspCentroid:
611 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
612 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
613
614 case glslang::EbvBaryCoordNoPerspSample:
615 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
616 return spv::BuiltInBaryCoordNoPerspSampleAMD;
617
618 case glslang::EbvBaryCoordSmooth:
619 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
620 return spv::BuiltInBaryCoordSmoothAMD;
621
622 case glslang::EbvBaryCoordSmoothCentroid:
623 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
624 return spv::BuiltInBaryCoordSmoothCentroidAMD;
625
626 case glslang::EbvBaryCoordSmoothSample:
627 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
628 return spv::BuiltInBaryCoordSmoothSampleAMD;
629
630 case glslang::EbvBaryCoordPullModel:
631 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
632 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800633#endif
chaoc771d89f2017-01-13 01:10:53 -0800634
John Kessenich6c8aaac2017-02-27 01:20:51 -0700635 case glslang::EbvDeviceIndex:
636 builder.addExtension(spv::E_SPV_KHR_device_group);
637 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700638 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700639
640 case glslang::EbvViewIndex:
641 builder.addExtension(spv::E_SPV_KHR_multiview);
642 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700643 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700644
chaoc771d89f2017-01-13 01:10:53 -0800645#ifdef NV_EXTENSIONS
646 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800647 if (!memberDeclaration) {
648 builder.addExtension(spv::E_SPV_NV_viewport_array2);
649 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
650 }
chaoc771d89f2017-01-13 01:10:53 -0800651 return spv::BuiltInViewportMaskNV;
652 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800653 if (!memberDeclaration) {
654 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
655 builder.addCapability(spv::CapabilityShaderStereoViewNV);
656 }
chaoc771d89f2017-01-13 01:10:53 -0800657 return spv::BuiltInSecondaryPositionNV;
658 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800659 if (!memberDeclaration) {
660 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
661 builder.addCapability(spv::CapabilityShaderStereoViewNV);
662 }
chaoc771d89f2017-01-13 01:10:53 -0800663 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800664 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800665 if (!memberDeclaration) {
666 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
667 builder.addCapability(spv::CapabilityPerViewAttributesNV);
668 }
chaocdf3956c2017-02-14 14:52:34 -0800669 return spv::BuiltInPositionPerViewNV;
670 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800671 if (!memberDeclaration) {
672 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
673 builder.addCapability(spv::CapabilityPerViewAttributesNV);
674 }
chaocdf3956c2017-02-14 14:52:34 -0800675 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800676#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800677 default:
678 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600679 }
680}
681
Rex Xufc618912015-09-09 16:42:49 +0800682// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700683spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800684{
685 assert(type.getBasicType() == glslang::EbtSampler);
686
John Kessenich5d0fa972016-02-15 11:57:00 -0700687 // Check for capabilities
688 switch (type.getQualifier().layoutFormat) {
689 case glslang::ElfRg32f:
690 case glslang::ElfRg16f:
691 case glslang::ElfR11fG11fB10f:
692 case glslang::ElfR16f:
693 case glslang::ElfRgba16:
694 case glslang::ElfRgb10A2:
695 case glslang::ElfRg16:
696 case glslang::ElfRg8:
697 case glslang::ElfR16:
698 case glslang::ElfR8:
699 case glslang::ElfRgba16Snorm:
700 case glslang::ElfRg16Snorm:
701 case glslang::ElfRg8Snorm:
702 case glslang::ElfR16Snorm:
703 case glslang::ElfR8Snorm:
704
705 case glslang::ElfRg32i:
706 case glslang::ElfRg16i:
707 case glslang::ElfRg8i:
708 case glslang::ElfR16i:
709 case glslang::ElfR8i:
710
711 case glslang::ElfRgb10a2ui:
712 case glslang::ElfRg32ui:
713 case glslang::ElfRg16ui:
714 case glslang::ElfRg8ui:
715 case glslang::ElfR16ui:
716 case glslang::ElfR8ui:
717 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
718 break;
719
720 default:
721 break;
722 }
723
724 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800725 switch (type.getQualifier().layoutFormat) {
726 case glslang::ElfNone: return spv::ImageFormatUnknown;
727 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
728 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
729 case glslang::ElfR32f: return spv::ImageFormatR32f;
730 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
731 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
732 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
733 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
734 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
735 case glslang::ElfR16f: return spv::ImageFormatR16f;
736 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
737 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
738 case glslang::ElfRg16: return spv::ImageFormatRg16;
739 case glslang::ElfRg8: return spv::ImageFormatRg8;
740 case glslang::ElfR16: return spv::ImageFormatR16;
741 case glslang::ElfR8: return spv::ImageFormatR8;
742 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
743 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
744 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
745 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
746 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
747 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
748 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
749 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
750 case glslang::ElfR32i: return spv::ImageFormatR32i;
751 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
752 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
753 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
754 case glslang::ElfR16i: return spv::ImageFormatR16i;
755 case glslang::ElfR8i: return spv::ImageFormatR8i;
756 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
757 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
758 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
759 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
760 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
761 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
762 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
763 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
764 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
765 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600766 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800767 }
768}
769
qining25262b32016-05-06 17:25:16 -0400770// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700771// descriptor set.
772bool IsDescriptorResource(const glslang::TType& type)
773{
John Kessenichf7497e22016-03-08 21:36:22 -0700774 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700775 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700776 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700777
778 // non block...
779 // basically samplerXXX/subpass/sampler/texture are all included
780 // if they are the global-scope-class, not the function parameter
781 // (or local, if they ever exist) class.
782 if (type.getBasicType() == glslang::EbtSampler)
783 return type.getQualifier().isUniformOrBuffer();
784
785 // None of the above.
786 return false;
787}
788
John Kesseniche0b6cad2015-12-24 10:30:13 -0700789void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
790{
791 if (child.layoutMatrix == glslang::ElmNone)
792 child.layoutMatrix = parent.layoutMatrix;
793
794 if (parent.invariant)
795 child.invariant = true;
796 if (parent.nopersp)
797 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800798#ifdef AMD_EXTENSIONS
799 if (parent.explicitInterp)
800 child.explicitInterp = true;
801#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700802 if (parent.flat)
803 child.flat = true;
804 if (parent.centroid)
805 child.centroid = true;
806 if (parent.patch)
807 child.patch = true;
808 if (parent.sample)
809 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800810 if (parent.coherent)
811 child.coherent = true;
812 if (parent.volatil)
813 child.volatil = true;
814 if (parent.restrict)
815 child.restrict = true;
816 if (parent.readonly)
817 child.readonly = true;
818 if (parent.writeonly)
819 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700820}
821
John Kessenichf2b7f332016-09-01 17:05:23 -0600822bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700823{
John Kessenich7b9fa252016-01-21 18:56:57 -0700824 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600825 // - struct members might inherit from a struct declaration
826 // (note that non-block structs don't explicitly inherit,
827 // only implicitly, meaning no decoration involved)
828 // - affect decorations on the struct members
829 // (note smooth does not, and expecting something like volatile
830 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700831 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600832 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700833}
834
John Kessenich140f3df2015-06-26 16:58:36 -0600835//
836// Implement the TGlslangToSpvTraverser class.
837//
838
Lei Zhang17535f72016-05-04 15:55:59 -0400839TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600840 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
841 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400842 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700843 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600844 glslangIntermediate(glslangIntermediate)
845{
846 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
847
848 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700849 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600850 stdBuiltins = builder.import("GLSL.std.450");
851 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600852 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
853 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600854
855 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600856 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
857 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600858 builder.addSourceExtension(it->c_str());
859
860 // Add the top-level modes for this shader.
861
John Kessenich92187592016-02-01 13:45:25 -0700862 if (glslangIntermediate->getXfbMode()) {
863 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600864 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700865 }
John Kessenich140f3df2015-06-26 16:58:36 -0600866
867 unsigned int mode;
868 switch (glslangIntermediate->getStage()) {
869 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600870 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600871 break;
872
steve-lunarge7412492017-03-23 11:56:07 -0600873 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600874 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600875 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600876
steve-lunarge7412492017-03-23 11:56:07 -0600877 glslang::TLayoutGeometry primitive;
878
879 if (glslangIntermediate->getStage() == EShLangTessControl) {
880 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
881 primitive = glslangIntermediate->getOutputPrimitive();
882 } else {
883 primitive = glslangIntermediate->getInputPrimitive();
884 }
885
886 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700887 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
888 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
889 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600890 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600891 }
John Kessenich4016e382016-07-15 11:53:56 -0600892 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600893 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
894
John Kesseniche6903322015-10-13 16:29:02 -0600895 switch (glslangIntermediate->getVertexSpacing()) {
896 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
897 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
898 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600899 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600900 }
John Kessenich4016e382016-07-15 11:53:56 -0600901 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600902 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
903
904 switch (glslangIntermediate->getVertexOrder()) {
905 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
906 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600907 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600908 }
John Kessenich4016e382016-07-15 11:53:56 -0600909 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600910 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
911
912 if (glslangIntermediate->getPointMode())
913 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600914 break;
915
916 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600917 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600918 switch (glslangIntermediate->getInputPrimitive()) {
919 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
920 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
921 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700922 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600923 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600924 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600925 }
John Kessenich4016e382016-07-15 11:53:56 -0600926 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600927 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600928
John Kessenich140f3df2015-06-26 16:58:36 -0600929 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
930
931 switch (glslangIntermediate->getOutputPrimitive()) {
932 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
933 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
934 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600935 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600936 }
John Kessenich4016e382016-07-15 11:53:56 -0600937 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600938 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
939 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
940 break;
941
942 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600943 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600944 if (glslangIntermediate->getPixelCenterInteger())
945 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600946
John Kessenich140f3df2015-06-26 16:58:36 -0600947 if (glslangIntermediate->getOriginUpperLeft())
948 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600949 else
950 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600951
952 if (glslangIntermediate->getEarlyFragmentTests())
953 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
954
955 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600956 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
957 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600958 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600959 }
John Kessenich4016e382016-07-15 11:53:56 -0600960 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600961 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
962
963 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
964 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600965 break;
966
967 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600968 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600969 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
970 glslangIntermediate->getLocalSize(1),
971 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600972 break;
973
974 default:
975 break;
976 }
John Kessenich140f3df2015-06-26 16:58:36 -0600977}
978
John Kessenichfca82622016-11-26 13:23:20 -0700979// Finish creating SPV, after the traversal is complete.
980void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700981{
John Kessenich517fe7a2016-11-26 13:31:47 -0700982 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700983 builder.setBuildPoint(shaderEntry->getLastBlock());
984 builder.leaveFunction();
985 }
986
John Kessenich7ba63412015-12-20 17:37:07 -0700987 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100988 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
989 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700990
qiningda397332016-03-09 19:54:03 -0500991 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700992}
993
John Kessenichfca82622016-11-26 13:23:20 -0700994// Write the SPV into 'out'.
995void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -0600996{
John Kessenichfca82622016-11-26 13:23:20 -0700997 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -0600998}
999
1000//
1001// Implement the traversal functions.
1002//
1003// Return true from interior nodes to have the external traversal
1004// continue on to children. Return false if children were
1005// already processed.
1006//
1007
1008//
qining25262b32016-05-06 17:25:16 -04001009// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001010// - uniform/input reads
1011// - output writes
1012// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1013// - something simple that degenerates into the last bullet
1014//
1015void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1016{
qining75d1d802016-04-06 14:42:01 -04001017 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1018 if (symbol->getType().getQualifier().isSpecConstant())
1019 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1020
John Kessenich140f3df2015-06-26 16:58:36 -06001021 // getSymbolId() will set up all the IO decorations on the first call.
1022 // Formal function parameters were mapped during makeFunctions().
1023 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001024
1025 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1026 if (builder.isPointer(id)) {
1027 spv::StorageClass sc = builder.getStorageClass(id);
1028 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1029 iOSet.insert(id);
1030 }
1031
1032 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001033 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001034 // Prepare to generate code for the access
1035
1036 // L-value chains will be computed left to right. We're on the symbol now,
1037 // which is the left-most part of the access chain, so now is "clear" time,
1038 // followed by setting the base.
1039 builder.clearAccessChain();
1040
1041 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001042 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001043 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001044 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001045 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001046 // These are also pure R-values.
1047 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001048 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001049 builder.setAccessChainRValue(id);
1050 else
1051 builder.setAccessChainLValue(id);
1052 }
1053}
1054
1055bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1056{
qining40887662016-04-03 22:20:42 -04001057 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1058 if (node->getType().getQualifier().isSpecConstant())
1059 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1060
John Kessenich140f3df2015-06-26 16:58:36 -06001061 // First, handle special cases
1062 switch (node->getOp()) {
1063 case glslang::EOpAssign:
1064 case glslang::EOpAddAssign:
1065 case glslang::EOpSubAssign:
1066 case glslang::EOpMulAssign:
1067 case glslang::EOpVectorTimesMatrixAssign:
1068 case glslang::EOpVectorTimesScalarAssign:
1069 case glslang::EOpMatrixTimesScalarAssign:
1070 case glslang::EOpMatrixTimesMatrixAssign:
1071 case glslang::EOpDivAssign:
1072 case glslang::EOpModAssign:
1073 case glslang::EOpAndAssign:
1074 case glslang::EOpInclusiveOrAssign:
1075 case glslang::EOpExclusiveOrAssign:
1076 case glslang::EOpLeftShiftAssign:
1077 case glslang::EOpRightShiftAssign:
1078 // A bin-op assign "a += b" means the same thing as "a = a + b"
1079 // where a is evaluated before b. For a simple assignment, GLSL
1080 // says to evaluate the left before the right. So, always, left
1081 // node then right node.
1082 {
1083 // get the left l-value, save it away
1084 builder.clearAccessChain();
1085 node->getLeft()->traverse(this);
1086 spv::Builder::AccessChain lValue = builder.getAccessChain();
1087
1088 // evaluate the right
1089 builder.clearAccessChain();
1090 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001091 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001092
1093 if (node->getOp() != glslang::EOpAssign) {
1094 // the left is also an r-value
1095 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001096 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001097
1098 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001099 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001100 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001101 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1102 node->getType().getBasicType());
1103
1104 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001105 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001106 }
1107
1108 // store the result
1109 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001110 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001111
1112 // assignments are expressions having an rValue after they are evaluated...
1113 builder.clearAccessChain();
1114 builder.setAccessChainRValue(rValue);
1115 }
1116 return false;
1117 case glslang::EOpIndexDirect:
1118 case glslang::EOpIndexDirectStruct:
1119 {
1120 // Get the left part of the access chain.
1121 node->getLeft()->traverse(this);
1122
1123 // Add the next element in the chain
1124
David Netoa901ffe2016-06-08 14:11:40 +01001125 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001126 if (! node->getLeft()->getType().isArray() &&
1127 node->getLeft()->getType().isVector() &&
1128 node->getOp() == glslang::EOpIndexDirect) {
1129 // This is essentially a hard-coded vector swizzle of size 1,
1130 // so short circuit the access-chain stuff with a swizzle.
1131 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001132 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001133 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001134 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001135 int spvIndex = glslangIndex;
1136 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1137 node->getOp() == glslang::EOpIndexDirectStruct)
1138 {
1139 // This may be, e.g., an anonymous block-member selection, which generally need
1140 // index remapping due to hidden members in anonymous blocks.
1141 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1142 assert(remapper.size() > 0);
1143 spvIndex = remapper[glslangIndex];
1144 }
John Kessenichebb50532016-05-16 19:22:05 -06001145
David Netoa901ffe2016-06-08 14:11:40 +01001146 // normal case for indexing array or structure or block
1147 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1148
1149 // Add capabilities here for accessing PointSize and clip/cull distance.
1150 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001151 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001152 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001153 }
1154 }
1155 return false;
1156 case glslang::EOpIndexIndirect:
1157 {
1158 // Structure or array or vector indirection.
1159 // Will use native SPIR-V access-chain for struct and array indirection;
1160 // matrices are arrays of vectors, so will also work for a matrix.
1161 // Will use the access chain's 'component' for variable index into a vector.
1162
1163 // This adapter is building access chains left to right.
1164 // Set up the access chain to the left.
1165 node->getLeft()->traverse(this);
1166
1167 // save it so that computing the right side doesn't trash it
1168 spv::Builder::AccessChain partial = builder.getAccessChain();
1169
1170 // compute the next index in the chain
1171 builder.clearAccessChain();
1172 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001173 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001174
1175 // restore the saved access chain
1176 builder.setAccessChain(partial);
1177
1178 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001179 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001180 else
John Kessenichfa668da2015-09-13 14:46:30 -06001181 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001182 }
1183 return false;
1184 case glslang::EOpVectorSwizzle:
1185 {
1186 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001187 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001188 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001189 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001190 }
1191 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001192 case glslang::EOpMatrixSwizzle:
1193 logger->missingFunctionality("matrix swizzle");
1194 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001195 case glslang::EOpLogicalOr:
1196 case glslang::EOpLogicalAnd:
1197 {
1198
1199 // These may require short circuiting, but can sometimes be done as straight
1200 // binary operations. The right operand must be short circuited if it has
1201 // side effects, and should probably be if it is complex.
1202 if (isTrivial(node->getRight()->getAsTyped()))
1203 break; // handle below as a normal binary operation
1204 // otherwise, we need to do dynamic short circuiting on the right operand
1205 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1206 builder.clearAccessChain();
1207 builder.setAccessChainRValue(result);
1208 }
1209 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001210 default:
1211 break;
1212 }
1213
1214 // Assume generic binary op...
1215
John Kessenich32cfd492016-02-02 12:37:46 -07001216 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001217 builder.clearAccessChain();
1218 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001219 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001220
John Kessenich32cfd492016-02-02 12:37:46 -07001221 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001222 builder.clearAccessChain();
1223 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001224 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001225
John Kessenich32cfd492016-02-02 12:37:46 -07001226 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001227 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001228 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001229 convertGlslangToSpvType(node->getType()), left, right,
1230 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001231
John Kessenich50e57562015-12-21 21:21:11 -07001232 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001233 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001234 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001235 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001236 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001237 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001238 return false;
1239 }
John Kessenich140f3df2015-06-26 16:58:36 -06001240}
1241
1242bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1243{
qining40887662016-04-03 22:20:42 -04001244 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1245 if (node->getType().getQualifier().isSpecConstant())
1246 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1247
John Kessenichfc51d282015-08-19 13:34:18 -06001248 spv::Id result = spv::NoResult;
1249
1250 // try texturing first
1251 result = createImageTextureFunctionCall(node);
1252 if (result != spv::NoResult) {
1253 builder.clearAccessChain();
1254 builder.setAccessChainRValue(result);
1255
1256 return false; // done with this node
1257 }
1258
1259 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001260
1261 if (node->getOp() == glslang::EOpArrayLength) {
1262 // Quite special; won't want to evaluate the operand.
1263
1264 // Normal .length() would have been constant folded by the front-end.
1265 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001266 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001267 assert(node->getOperand()->getType().isRuntimeSizedArray());
1268 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1269 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001270 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1271 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001272
1273 builder.clearAccessChain();
1274 builder.setAccessChainRValue(length);
1275
1276 return false;
1277 }
1278
John Kessenichfc51d282015-08-19 13:34:18 -06001279 // Start by evaluating the operand
1280
John Kessenich8c8505c2016-07-26 12:50:38 -06001281 // Does it need a swizzle inversion? If so, evaluation is inverted;
1282 // operate first on the swizzle base, then apply the swizzle.
1283 spv::Id invertedType = spv::NoType;
1284 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1285 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1286 invertedType = getInvertedSwizzleType(*node->getOperand());
1287
John Kessenich140f3df2015-06-26 16:58:36 -06001288 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001289 if (invertedType != spv::NoType)
1290 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1291 else
1292 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001293
Rex Xufc618912015-09-09 16:42:49 +08001294 spv::Id operand = spv::NoResult;
1295
1296 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1297 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001298 node->getOp() == glslang::EOpAtomicCounter ||
1299 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001300 operand = builder.accessChainGetLValue(); // Special case l-value operands
1301 else
John Kessenich32cfd492016-02-02 12:37:46 -07001302 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001303
John Kessenichf6640762016-08-01 19:44:00 -06001304 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001305 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001306
1307 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001308 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001309 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001310
1311 // if not, then possibly an operation
1312 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001313 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001314
1315 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001316 if (invertedType)
1317 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1318
John Kessenich140f3df2015-06-26 16:58:36 -06001319 builder.clearAccessChain();
1320 builder.setAccessChainRValue(result);
1321
1322 return false; // done with this node
1323 }
1324
1325 // it must be a special case, check...
1326 switch (node->getOp()) {
1327 case glslang::EOpPostIncrement:
1328 case glslang::EOpPostDecrement:
1329 case glslang::EOpPreIncrement:
1330 case glslang::EOpPreDecrement:
1331 {
1332 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001333 spv::Id one = 0;
1334 if (node->getBasicType() == glslang::EbtFloat)
1335 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001336 else if (node->getBasicType() == glslang::EbtDouble)
1337 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001338#ifdef AMD_EXTENSIONS
1339 else if (node->getBasicType() == glslang::EbtFloat16)
1340 one = builder.makeFloat16Constant(1.0F);
1341#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001342 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1343 one = builder.makeInt64Constant(1);
1344 else
1345 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001346 glslang::TOperator op;
1347 if (node->getOp() == glslang::EOpPreIncrement ||
1348 node->getOp() == glslang::EOpPostIncrement)
1349 op = glslang::EOpAdd;
1350 else
1351 op = glslang::EOpSub;
1352
John Kessenichf6640762016-08-01 19:44:00 -06001353 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001354 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001355 convertGlslangToSpvType(node->getType()), operand, one,
1356 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001357 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001358
1359 // The result of operation is always stored, but conditionally the
1360 // consumed result. The consumed result is always an r-value.
1361 builder.accessChainStore(result);
1362 builder.clearAccessChain();
1363 if (node->getOp() == glslang::EOpPreIncrement ||
1364 node->getOp() == glslang::EOpPreDecrement)
1365 builder.setAccessChainRValue(result);
1366 else
1367 builder.setAccessChainRValue(operand);
1368 }
1369
1370 return false;
1371
1372 case glslang::EOpEmitStreamVertex:
1373 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1374 return false;
1375 case glslang::EOpEndStreamPrimitive:
1376 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1377 return false;
1378
1379 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001380 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001381 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001382 }
John Kessenich140f3df2015-06-26 16:58:36 -06001383}
1384
1385bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1386{
qining27e04a02016-04-14 16:40:20 -04001387 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1388 if (node->getType().getQualifier().isSpecConstant())
1389 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1390
John Kessenichfc51d282015-08-19 13:34:18 -06001391 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001392 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1393 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001394
1395 // try texturing
1396 result = createImageTextureFunctionCall(node);
1397 if (result != spv::NoResult) {
1398 builder.clearAccessChain();
1399 builder.setAccessChainRValue(result);
1400
1401 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001402 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001403 // "imageStore" is a special case, which has no result
1404 return false;
1405 }
John Kessenichfc51d282015-08-19 13:34:18 -06001406
John Kessenich140f3df2015-06-26 16:58:36 -06001407 glslang::TOperator binOp = glslang::EOpNull;
1408 bool reduceComparison = true;
1409 bool isMatrix = false;
1410 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001411 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001412
1413 assert(node->getOp());
1414
John Kessenichf6640762016-08-01 19:44:00 -06001415 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001416
1417 switch (node->getOp()) {
1418 case glslang::EOpSequence:
1419 {
1420 if (preVisit)
1421 ++sequenceDepth;
1422 else
1423 --sequenceDepth;
1424
1425 if (sequenceDepth == 1) {
1426 // If this is the parent node of all the functions, we want to see them
1427 // early, so all call points have actual SPIR-V functions to reference.
1428 // In all cases, still let the traverser visit the children for us.
1429 makeFunctions(node->getAsAggregate()->getSequence());
1430
John Kessenich6fccb3c2016-09-19 16:01:41 -06001431 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001432 // anything else gets there, so visit out of order, doing them all now.
1433 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1434
John Kessenich6a60c2f2016-12-08 21:01:59 -07001435 // 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 -06001436 // so do them manually.
1437 visitFunctions(node->getAsAggregate()->getSequence());
1438
1439 return false;
1440 }
1441
1442 return true;
1443 }
1444 case glslang::EOpLinkerObjects:
1445 {
1446 if (visit == glslang::EvPreVisit)
1447 linkageOnly = true;
1448 else
1449 linkageOnly = false;
1450
1451 return true;
1452 }
1453 case glslang::EOpComma:
1454 {
1455 // processing from left to right naturally leaves the right-most
1456 // lying around in the access chain
1457 glslang::TIntermSequence& glslangOperands = node->getSequence();
1458 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1459 glslangOperands[i]->traverse(this);
1460
1461 return false;
1462 }
1463 case glslang::EOpFunction:
1464 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001465 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001466 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001467 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001468 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001469 } else {
1470 handleFunctionEntry(node);
1471 }
1472 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001473 if (inEntryPoint)
1474 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001475 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001476 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001477 }
1478
1479 return true;
1480 case glslang::EOpParameters:
1481 // Parameters will have been consumed by EOpFunction processing, but not
1482 // the body, so we still visited the function node's children, making this
1483 // child redundant.
1484 return false;
1485 case glslang::EOpFunctionCall:
1486 {
1487 if (node->isUserDefined())
1488 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001489 // 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 -07001490 if (result) {
1491 builder.clearAccessChain();
1492 builder.setAccessChainRValue(result);
1493 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001494 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001495
1496 return false;
1497 }
1498 case glslang::EOpConstructMat2x2:
1499 case glslang::EOpConstructMat2x3:
1500 case glslang::EOpConstructMat2x4:
1501 case glslang::EOpConstructMat3x2:
1502 case glslang::EOpConstructMat3x3:
1503 case glslang::EOpConstructMat3x4:
1504 case glslang::EOpConstructMat4x2:
1505 case glslang::EOpConstructMat4x3:
1506 case glslang::EOpConstructMat4x4:
1507 case glslang::EOpConstructDMat2x2:
1508 case glslang::EOpConstructDMat2x3:
1509 case glslang::EOpConstructDMat2x4:
1510 case glslang::EOpConstructDMat3x2:
1511 case glslang::EOpConstructDMat3x3:
1512 case glslang::EOpConstructDMat3x4:
1513 case glslang::EOpConstructDMat4x2:
1514 case glslang::EOpConstructDMat4x3:
1515 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001516#ifdef AMD_EXTENSIONS
1517 case glslang::EOpConstructF16Mat2x2:
1518 case glslang::EOpConstructF16Mat2x3:
1519 case glslang::EOpConstructF16Mat2x4:
1520 case glslang::EOpConstructF16Mat3x2:
1521 case glslang::EOpConstructF16Mat3x3:
1522 case glslang::EOpConstructF16Mat3x4:
1523 case glslang::EOpConstructF16Mat4x2:
1524 case glslang::EOpConstructF16Mat4x3:
1525 case glslang::EOpConstructF16Mat4x4:
1526#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001527 isMatrix = true;
1528 // fall through
1529 case glslang::EOpConstructFloat:
1530 case glslang::EOpConstructVec2:
1531 case glslang::EOpConstructVec3:
1532 case glslang::EOpConstructVec4:
1533 case glslang::EOpConstructDouble:
1534 case glslang::EOpConstructDVec2:
1535 case glslang::EOpConstructDVec3:
1536 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001537#ifdef AMD_EXTENSIONS
1538 case glslang::EOpConstructFloat16:
1539 case glslang::EOpConstructF16Vec2:
1540 case glslang::EOpConstructF16Vec3:
1541 case glslang::EOpConstructF16Vec4:
1542#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001543 case glslang::EOpConstructBool:
1544 case glslang::EOpConstructBVec2:
1545 case glslang::EOpConstructBVec3:
1546 case glslang::EOpConstructBVec4:
1547 case glslang::EOpConstructInt:
1548 case glslang::EOpConstructIVec2:
1549 case glslang::EOpConstructIVec3:
1550 case glslang::EOpConstructIVec4:
1551 case glslang::EOpConstructUint:
1552 case glslang::EOpConstructUVec2:
1553 case glslang::EOpConstructUVec3:
1554 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001555 case glslang::EOpConstructInt64:
1556 case glslang::EOpConstructI64Vec2:
1557 case glslang::EOpConstructI64Vec3:
1558 case glslang::EOpConstructI64Vec4:
1559 case glslang::EOpConstructUint64:
1560 case glslang::EOpConstructU64Vec2:
1561 case glslang::EOpConstructU64Vec3:
1562 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001563 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001564 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001565 {
1566 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001567 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001568 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001569 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001570 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001571 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001572 std::vector<spv::Id> constituents;
1573 for (int c = 0; c < (int)arguments.size(); ++c)
1574 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001575 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001576 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001577 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001578 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001579 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001580
1581 builder.clearAccessChain();
1582 builder.setAccessChainRValue(constructed);
1583
1584 return false;
1585 }
1586
1587 // These six are component-wise compares with component-wise results.
1588 // Forward on to createBinaryOperation(), requesting a vector result.
1589 case glslang::EOpLessThan:
1590 case glslang::EOpGreaterThan:
1591 case glslang::EOpLessThanEqual:
1592 case glslang::EOpGreaterThanEqual:
1593 case glslang::EOpVectorEqual:
1594 case glslang::EOpVectorNotEqual:
1595 {
1596 // Map the operation to a binary
1597 binOp = node->getOp();
1598 reduceComparison = false;
1599 switch (node->getOp()) {
1600 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1601 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1602 default: binOp = node->getOp(); break;
1603 }
1604
1605 break;
1606 }
1607 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001608 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001609 binOp = glslang::EOpMul;
1610 break;
1611 case glslang::EOpOuterProduct:
1612 // two vectors multiplied to make a matrix
1613 binOp = glslang::EOpOuterProduct;
1614 break;
1615 case glslang::EOpDot:
1616 {
qining25262b32016-05-06 17:25:16 -04001617 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001618 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001619 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001620 binOp = glslang::EOpMul;
1621 break;
1622 }
1623 case glslang::EOpMod:
1624 // when an aggregate, this is the floating-point mod built-in function,
1625 // which can be emitted by the one in createBinaryOperation()
1626 binOp = glslang::EOpMod;
1627 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001628 case glslang::EOpEmitVertex:
1629 case glslang::EOpEndPrimitive:
1630 case glslang::EOpBarrier:
1631 case glslang::EOpMemoryBarrier:
1632 case glslang::EOpMemoryBarrierAtomicCounter:
1633 case glslang::EOpMemoryBarrierBuffer:
1634 case glslang::EOpMemoryBarrierImage:
1635 case glslang::EOpMemoryBarrierShared:
1636 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001637 case glslang::EOpAllMemoryBarrierWithGroupSync:
1638 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1639 case glslang::EOpWorkgroupMemoryBarrier:
1640 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001641 noReturnValue = true;
1642 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1643 break;
1644
John Kessenich426394d2015-07-23 10:22:48 -06001645 case glslang::EOpAtomicAdd:
1646 case glslang::EOpAtomicMin:
1647 case glslang::EOpAtomicMax:
1648 case glslang::EOpAtomicAnd:
1649 case glslang::EOpAtomicOr:
1650 case glslang::EOpAtomicXor:
1651 case glslang::EOpAtomicExchange:
1652 case glslang::EOpAtomicCompSwap:
1653 atomic = true;
1654 break;
1655
John Kessenich140f3df2015-06-26 16:58:36 -06001656 default:
1657 break;
1658 }
1659
1660 //
1661 // See if it maps to a regular operation.
1662 //
John Kessenich140f3df2015-06-26 16:58:36 -06001663 if (binOp != glslang::EOpNull) {
1664 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1665 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1666 assert(left && right);
1667
1668 builder.clearAccessChain();
1669 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001670 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001671
1672 builder.clearAccessChain();
1673 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001674 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001675
qining25262b32016-05-06 17:25:16 -04001676 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001677 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001678 left->getType().getBasicType(), reduceComparison);
1679
1680 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001681 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001682 builder.clearAccessChain();
1683 builder.setAccessChainRValue(result);
1684
1685 return false;
1686 }
1687
John Kessenich426394d2015-07-23 10:22:48 -06001688 //
1689 // Create the list of operands.
1690 //
John Kessenich140f3df2015-06-26 16:58:36 -06001691 glslang::TIntermSequence& glslangOperands = node->getSequence();
1692 std::vector<spv::Id> operands;
1693 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001694 // special case l-value operands; there are just a few
1695 bool lvalue = false;
1696 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001697 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001698 case glslang::EOpModf:
1699 if (arg == 1)
1700 lvalue = true;
1701 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001702 case glslang::EOpInterpolateAtSample:
1703 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001704#ifdef AMD_EXTENSIONS
1705 case glslang::EOpInterpolateAtVertex:
1706#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001707 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001708 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001709
1710 // Does it need a swizzle inversion? If so, evaluation is inverted;
1711 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001712 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001713 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1714 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1715 }
Rex Xu7a26c172015-12-08 17:12:09 +08001716 break;
Rex Xud4782c12015-09-06 16:30:11 +08001717 case glslang::EOpAtomicAdd:
1718 case glslang::EOpAtomicMin:
1719 case glslang::EOpAtomicMax:
1720 case glslang::EOpAtomicAnd:
1721 case glslang::EOpAtomicOr:
1722 case glslang::EOpAtomicXor:
1723 case glslang::EOpAtomicExchange:
1724 case glslang::EOpAtomicCompSwap:
1725 if (arg == 0)
1726 lvalue = true;
1727 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001728 case glslang::EOpAddCarry:
1729 case glslang::EOpSubBorrow:
1730 if (arg == 2)
1731 lvalue = true;
1732 break;
1733 case glslang::EOpUMulExtended:
1734 case glslang::EOpIMulExtended:
1735 if (arg >= 2)
1736 lvalue = true;
1737 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001738 default:
1739 break;
1740 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001741 builder.clearAccessChain();
1742 if (invertedType != spv::NoType && arg == 0)
1743 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1744 else
1745 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001746 if (lvalue)
1747 operands.push_back(builder.accessChainGetLValue());
1748 else
John Kessenich32cfd492016-02-02 12:37:46 -07001749 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001750 }
John Kessenich426394d2015-07-23 10:22:48 -06001751
1752 if (atomic) {
1753 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001754 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001755 } else {
1756 // Pass through to generic operations.
1757 switch (glslangOperands.size()) {
1758 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001759 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001760 break;
1761 case 1:
qining25262b32016-05-06 17:25:16 -04001762 result = createUnaryOperation(
1763 node->getOp(), precision,
1764 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001765 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001766 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001767 break;
1768 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001769 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001770 break;
1771 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001772 if (invertedType)
1773 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001774 }
1775
1776 if (noReturnValue)
1777 return false;
1778
1779 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001780 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001781 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001782 } else {
1783 builder.clearAccessChain();
1784 builder.setAccessChainRValue(result);
1785 return false;
1786 }
1787}
1788
John Kessenich433e9ff2017-01-26 20:31:11 -07001789// This path handles both if-then-else and ?:
1790// The if-then-else has a node type of void, while
1791// ?: has either a void or a non-void node type
1792//
1793// Leaving the result, when not void:
1794// GLSL only has r-values as the result of a :?, but
1795// if we have an l-value, that can be more efficient if it will
1796// become the base of a complex r-value expression, because the
1797// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001798bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1799{
John Kessenich433e9ff2017-01-26 20:31:11 -07001800 // See if it simple and safe to generate OpSelect instead of using control flow.
1801 // Crucially, side effects must be avoided, and there are performance trade-offs.
1802 // Return true if good idea (and safe) for OpSelect, false otherwise.
1803 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001804 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1805 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001806 return false;
1807
1808 if (node->getTrueBlock() == nullptr ||
1809 node->getFalseBlock() == nullptr)
1810 return false;
1811
1812 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1813 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1814
1815 // return true if a single operand to ? : is okay for OpSelect
1816 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001817 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001818 };
1819
1820 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1821 operandOkay(node->getFalseBlock()->getAsTyped());
1822 };
1823
1824 // Emit OpSelect for this selection.
1825 const auto handleAsOpSelect = [&]() {
1826 node->getCondition()->traverse(this);
1827 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1828 node->getTrueBlock()->traverse(this);
1829 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1830 node->getFalseBlock()->traverse(this);
1831 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1832
John Kesseniche434ad92017-03-30 10:09:28 -06001833 // smear condition to vector, if necessary (AST is always scalar)
1834 if (builder.isVector(trueValue))
1835 condition = builder.smearScalar(spv::NoPrecision, condition,
1836 builder.makeVectorType(builder.makeBoolType(),
1837 builder.getNumComponents(trueValue)));
1838
1839 spv::Id select = builder.createTriOp(spv::OpSelect,
1840 convertGlslangToSpvType(node->getType()), condition,
1841 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001842 builder.clearAccessChain();
1843 builder.setAccessChainRValue(select);
1844 };
1845
1846 // Try for OpSelect
1847
1848 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001849 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1850 if (node->getType().getQualifier().isSpecConstant())
1851 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1852
John Kessenich433e9ff2017-01-26 20:31:11 -07001853 handleAsOpSelect();
1854 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001855 }
1856
John Kessenich433e9ff2017-01-26 20:31:11 -07001857 // Instead, emit control flow...
1858
1859 // Don't handle results as temporaries, because there will be two names
1860 // and better to leave SSA to later passes.
1861 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1862 ? spv::NoResult
1863 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1864
John Kessenich140f3df2015-06-26 16:58:36 -06001865 // emit the condition before doing anything with selection
1866 node->getCondition()->traverse(this);
1867
1868 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001869 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001870
John Kessenich433e9ff2017-01-26 20:31:11 -07001871 // emit the "then" statement
1872 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001873 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001874 if (result != spv::NoResult)
1875 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001876 }
1877
John Kessenich433e9ff2017-01-26 20:31:11 -07001878 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001879 ifBuilder.makeBeginElse();
1880 // emit the "else" statement
1881 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001882 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001883 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001884 }
1885
John Kessenich433e9ff2017-01-26 20:31:11 -07001886 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001887 ifBuilder.makeEndIf();
1888
John Kessenich433e9ff2017-01-26 20:31:11 -07001889 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001890 // GLSL only has r-values as the result of a :?, but
1891 // if we have an l-value, that can be more efficient if it will
1892 // become the base of a complex r-value expression, because the
1893 // next layer copies r-values into memory to use the access-chain mechanism
1894 builder.clearAccessChain();
1895 builder.setAccessChainLValue(result);
1896 }
1897
1898 return false;
1899}
1900
1901bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1902{
1903 // emit and get the condition before doing anything with switch
1904 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001905 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001906
1907 // browse the children to sort out code segments
1908 int defaultSegment = -1;
1909 std::vector<TIntermNode*> codeSegments;
1910 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1911 std::vector<int> caseValues;
1912 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1913 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1914 TIntermNode* child = *c;
1915 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001916 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001917 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001918 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001919 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1920 } else
1921 codeSegments.push_back(child);
1922 }
1923
qining25262b32016-05-06 17:25:16 -04001924 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001925 // statements between the last case and the end of the switch statement
1926 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1927 (int)codeSegments.size() == defaultSegment)
1928 codeSegments.push_back(nullptr);
1929
1930 // make the switch statement
1931 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001932 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001933
1934 // emit all the code in the segments
1935 breakForLoop.push(false);
1936 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1937 builder.nextSwitchSegment(segmentBlocks, s);
1938 if (codeSegments[s])
1939 codeSegments[s]->traverse(this);
1940 else
1941 builder.addSwitchBreak();
1942 }
1943 breakForLoop.pop();
1944
1945 builder.endSwitch(segmentBlocks);
1946
1947 return false;
1948}
1949
1950void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1951{
1952 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001953 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001954
1955 builder.clearAccessChain();
1956 builder.setAccessChainRValue(constant);
1957}
1958
1959bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1960{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001961 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001962 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001963 // Spec requires back edges to target header blocks, and every header block
1964 // must dominate its merge block. Make a header block first to ensure these
1965 // conditions are met. By definition, it will contain OpLoopMerge, followed
1966 // by a block-ending branch. But we don't want to put any other body/test
1967 // instructions in it, since the body/test may have arbitrary instructions,
1968 // including merges of its own.
1969 builder.setBuildPoint(&blocks.head);
1970 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001971 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001972 spv::Block& test = builder.makeNewBlock();
1973 builder.createBranch(&test);
1974
1975 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001976 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001977 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001978 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001979 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1980
1981 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001982 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001983 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001984 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001985 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001986 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001987
1988 builder.setBuildPoint(&blocks.continue_target);
1989 if (node->getTerminal())
1990 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001991 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001992 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001993 builder.createBranch(&blocks.body);
1994
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001995 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001996 builder.setBuildPoint(&blocks.body);
1997 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001998 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001999 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002000 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002001
2002 builder.setBuildPoint(&blocks.continue_target);
2003 if (node->getTerminal())
2004 node->getTerminal()->traverse(this);
2005 if (node->getTest()) {
2006 node->getTest()->traverse(this);
2007 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002008 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002009 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002010 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002011 // TODO: unless there was a break/return/discard instruction
2012 // somewhere in the body, this is an infinite loop, so we should
2013 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002014 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002015 }
John Kessenich140f3df2015-06-26 16:58:36 -06002016 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002017 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002018 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002019 return false;
2020}
2021
2022bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2023{
2024 if (node->getExpression())
2025 node->getExpression()->traverse(this);
2026
2027 switch (node->getFlowOp()) {
2028 case glslang::EOpKill:
2029 builder.makeDiscard();
2030 break;
2031 case glslang::EOpBreak:
2032 if (breakForLoop.top())
2033 builder.createLoopExit();
2034 else
2035 builder.addSwitchBreak();
2036 break;
2037 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002038 builder.createLoopContinue();
2039 break;
2040 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002041 if (node->getExpression()) {
2042 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2043 spv::Id returnId = accessChainLoad(glslangReturnType);
2044 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2045 builder.clearAccessChain();
2046 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2047 builder.setAccessChainLValue(copyId);
2048 multiTypeStore(glslangReturnType, returnId);
2049 returnId = builder.createLoad(copyId);
2050 }
2051 builder.makeReturn(false, returnId);
2052 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002053 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002054
2055 builder.clearAccessChain();
2056 break;
2057
2058 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002059 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002060 break;
2061 }
2062
2063 return false;
2064}
2065
2066spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2067{
qining25262b32016-05-06 17:25:16 -04002068 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002069 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002070 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002071 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002072 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002073 }
2074
2075 // Now, handle actual variables
John Kessenich67027182017-04-19 18:34:49 -06002076 spv::StorageClass storageClass = TranslateStorageClass(node->getType(), glslangIntermediate->usingStorageBuffer());
John Kessenich140f3df2015-06-26 16:58:36 -06002077 spv::Id spvType = convertGlslangToSpvType(node->getType());
2078
Rex Xuf89ad982017-04-07 23:22:33 +08002079#ifdef AMD_EXTENSIONS
2080 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16);
2081 if (contains16BitType) {
2082 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2083 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2084 builder.addCapability(spv::CapabilityStorageInputOutput16);
2085 } else if (storageClass == spv::StorageClassPushConstant) {
2086 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2087 builder.addCapability(spv::CapabilityStoragePushConstant16);
2088 } else if (storageClass == spv::StorageClassUniform) {
2089 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2090 builder.addCapability(spv::CapabilityStorageUniform16);
2091 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2092 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2093 }
2094 }
2095#endif
2096
John Kessenich140f3df2015-06-26 16:58:36 -06002097 const char* name = node->getName().c_str();
2098 if (glslang::IsAnonymous(name))
2099 name = "";
2100
2101 return builder.createVariable(storageClass, spvType, name);
2102}
2103
2104// Return type Id of the sampled type.
2105spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2106{
2107 switch (sampler.type) {
2108 case glslang::EbtFloat: return builder.makeFloatType(32);
2109 case glslang::EbtInt: return builder.makeIntType(32);
2110 case glslang::EbtUint: return builder.makeUintType(32);
2111 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002112 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002113 return builder.makeFloatType(32);
2114 }
2115}
2116
John Kessenich8c8505c2016-07-26 12:50:38 -06002117// If node is a swizzle operation, return the type that should be used if
2118// the swizzle base is first consumed by another operation, before the swizzle
2119// is applied.
2120spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2121{
John Kessenichecba76f2017-01-06 00:34:48 -07002122 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002123 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2124 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2125 else
2126 return spv::NoType;
2127}
2128
2129// When inverting a swizzle with a parent op, this function
2130// will apply the swizzle operation to a completed parent operation.
2131spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2132{
2133 std::vector<unsigned> swizzle;
2134 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2135 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2136}
2137
John Kessenich8c8505c2016-07-26 12:50:38 -06002138// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2139void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2140{
2141 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2142 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2143 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2144}
2145
John Kessenich3ac051e2015-12-20 11:29:16 -07002146// Convert from a glslang type to an SPV type, by calling into a
2147// recursive version of this function. This establishes the inherited
2148// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002149spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2150{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002151 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002152}
2153
2154// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002155// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002156// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002157spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002158{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002159 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002160
2161 switch (type.getBasicType()) {
2162 case glslang::EbtVoid:
2163 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002164 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002165 break;
2166 case glslang::EbtFloat:
2167 spvType = builder.makeFloatType(32);
2168 break;
2169 case glslang::EbtDouble:
2170 spvType = builder.makeFloatType(64);
2171 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002172#ifdef AMD_EXTENSIONS
2173 case glslang::EbtFloat16:
2174 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002175 spvType = builder.makeFloatType(16);
2176 break;
2177#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002178 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002179 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2180 // a 32-bit int where non-0 means true.
2181 if (explicitLayout != glslang::ElpNone)
2182 spvType = builder.makeUintType(32);
2183 else
2184 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002185 break;
2186 case glslang::EbtInt:
2187 spvType = builder.makeIntType(32);
2188 break;
2189 case glslang::EbtUint:
2190 spvType = builder.makeUintType(32);
2191 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002192 case glslang::EbtInt64:
2193 builder.addCapability(spv::CapabilityInt64);
2194 spvType = builder.makeIntType(64);
2195 break;
2196 case glslang::EbtUint64:
2197 builder.addCapability(spv::CapabilityInt64);
2198 spvType = builder.makeUintType(64);
2199 break;
John Kessenich426394d2015-07-23 10:22:48 -06002200 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002201 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002202 spvType = builder.makeUintType(32);
2203 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002204 case glslang::EbtSampler:
2205 {
2206 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002207 if (sampler.sampler) {
2208 // pure sampler
2209 spvType = builder.makeSamplerType();
2210 } else {
2211 // an image is present, make its type
2212 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2213 sampler.image ? 2 : 1, TranslateImageFormat(type));
2214 if (sampler.combined) {
2215 // already has both image and sampler, make the combined type
2216 spvType = builder.makeSampledImageType(spvType);
2217 }
John Kessenich55e7d112015-11-15 21:33:39 -07002218 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002219 }
John Kessenich140f3df2015-06-26 16:58:36 -06002220 break;
2221 case glslang::EbtStruct:
2222 case glslang::EbtBlock:
2223 {
2224 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002225 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002226
2227 // Try to share structs for different layouts, but not yet for other
2228 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002229 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002230 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002231 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002232 break;
2233
2234 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002235 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002236 memberRemapper[glslangMembers].resize(glslangMembers->size());
2237 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002238 }
2239 break;
2240 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002241 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002242 break;
2243 }
2244
2245 if (type.isMatrix())
2246 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2247 else {
2248 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2249 if (type.getVectorSize() > 1)
2250 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2251 }
2252
2253 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002254 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2255
John Kessenichc9a80832015-09-12 12:17:44 -06002256 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002257 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002258 // We need to decorate array strides for types needing explicit layout, except blocks.
2259 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002260 // Use a dummy glslang type for querying internal strides of
2261 // arrays of arrays, but using just a one-dimensional array.
2262 glslang::TType simpleArrayType(type, 0); // deference type of the array
2263 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2264 simpleArrayType.getArraySizes().dereference();
2265
2266 // Will compute the higher-order strides here, rather than making a whole
2267 // pile of types and doing repetitive recursion on their contents.
2268 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2269 }
John Kessenichf8842e52016-01-04 19:22:56 -07002270
2271 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002272 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002273 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002274 if (stride > 0)
2275 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002276 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002277 }
2278 } else {
2279 // single-dimensional array, and don't yet have stride
2280
John Kessenichf8842e52016-01-04 19:22:56 -07002281 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002282 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2283 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002284 }
John Kessenich31ed4832015-09-09 17:51:38 -06002285
John Kessenichc9a80832015-09-12 12:17:44 -06002286 // Do the outer dimension, which might not be known for a runtime-sized array
2287 if (type.isRuntimeSizedArray()) {
2288 spvType = builder.makeRuntimeArray(spvType);
2289 } else {
2290 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002291 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002292 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002293 if (stride > 0)
2294 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002295 }
2296
2297 return spvType;
2298}
2299
John Kessenich0e737842017-03-24 18:38:16 -06002300// TODO: this functionality should exist at a higher level, in creating the AST
2301//
2302// Identify interface members that don't have their required extension turned on.
2303//
2304bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2305{
2306 auto& extensions = glslangIntermediate->getRequestedExtensions();
2307
Rex Xubcf291a2017-03-29 23:01:36 +08002308 if (member.getFieldName() == "gl_ViewportMask" &&
2309 extensions.find("GL_NV_viewport_array2") == extensions.end())
2310 return true;
2311 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2312 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2313 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002314 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2315 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2316 return true;
2317 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2318 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2319 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002320 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2321 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2322 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002323
2324 return false;
2325};
2326
John Kessenich6090df02016-06-30 21:18:02 -06002327// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2328// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2329// Mutually recursive with convertGlslangToSpvType().
2330spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2331 const glslang::TTypeList* glslangMembers,
2332 glslang::TLayoutPacking explicitLayout,
2333 const glslang::TQualifier& qualifier)
2334{
2335 // Create a vector of struct types for SPIR-V to consume
2336 std::vector<spv::Id> spvMembers;
2337 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2338 int locationOffset = 0; // for use across struct members, when they are called recursively
2339 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2340 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2341 if (glslangMember.hiddenMember()) {
2342 ++memberDelta;
2343 if (type.getBasicType() == glslang::EbtBlock)
2344 memberRemapper[glslangMembers][i] = -1;
2345 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002346 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002347 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002348 if (filterMember(glslangMember))
2349 continue;
2350 }
John Kessenich6090df02016-06-30 21:18:02 -06002351 // modify just this child's view of the qualifier
2352 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2353 InheritQualifiers(memberQualifier, qualifier);
2354
2355 // manually inherit location; it's more complex
2356 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2357 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2358 if (qualifier.hasLocation())
2359 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2360
2361 // recurse
2362 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2363 }
2364 }
2365
2366 // Make the SPIR-V type
2367 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002368 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002369 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2370
2371 // Decorate it
2372 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2373
2374 return spvType;
2375}
2376
2377void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2378 const glslang::TTypeList* glslangMembers,
2379 glslang::TLayoutPacking explicitLayout,
2380 const glslang::TQualifier& qualifier,
2381 spv::Id spvType)
2382{
2383 // Name and decorate the non-hidden members
2384 int offset = -1;
2385 int locationOffset = 0; // for use within the members of this struct
2386 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2387 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2388 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002389 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002390 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002391 if (filterMember(glslangMember))
2392 continue;
2393 }
John Kessenich6090df02016-06-30 21:18:02 -06002394
2395 // modify just this child's view of the qualifier
2396 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2397 InheritQualifiers(memberQualifier, qualifier);
2398
2399 // using -1 above to indicate a hidden member
2400 if (member >= 0) {
2401 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2402 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2403 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2404 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002405 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2406 type.getQualifier().storage == glslang::EvqVaryingOut) {
2407 if (type.getBasicType() == glslang::EbtBlock ||
2408 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002409 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2410 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2411 }
2412 }
2413 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2414
2415 if (qualifier.storage == glslang::EvqBuffer) {
2416 std::vector<spv::Decoration> memory;
2417 TranslateMemoryDecoration(memberQualifier, memory);
2418 for (unsigned int i = 0; i < memory.size(); ++i)
2419 addMemberDecoration(spvType, member, memory[i]);
2420 }
2421
John Kessenich2f47bc92016-06-30 21:47:35 -06002422 // Compute location decoration; tricky based on whether inheritance is at play and
2423 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002424 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2425 // probably move to the linker stage of the front end proper, and just have the
2426 // answer sitting already distributed throughout the individual member locations.
2427 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002428 // Ignore member locations if the container is an array, as that's
2429 // ill-specified and decisions have been made to not allow this anyway.
2430 // The object itself must have a location, and that comes out from decorating the object,
2431 // not the type (this code decorates types).
2432 if (! type.isArray()) {
2433 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2434 // struct members should not have explicit locations
2435 assert(type.getBasicType() != glslang::EbtStruct);
2436 location = memberQualifier.layoutLocation;
2437 } else if (type.getBasicType() != glslang::EbtBlock) {
2438 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2439 // The members, and their nested types, must not themselves have Location decorations.
2440 } else if (qualifier.hasLocation()) // inheritance
2441 location = qualifier.layoutLocation + locationOffset;
2442 }
John Kessenich6090df02016-06-30 21:18:02 -06002443 if (location >= 0)
2444 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2445
John Kessenich2f47bc92016-06-30 21:47:35 -06002446 if (qualifier.hasLocation()) // track for upcoming inheritance
2447 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2448
John Kessenich6090df02016-06-30 21:18:02 -06002449 // component, XFB, others
2450 if (glslangMember.getQualifier().hasComponent())
2451 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2452 if (glslangMember.getQualifier().hasXfbOffset())
2453 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2454 else if (explicitLayout != glslang::ElpNone) {
2455 // figure out what to do with offset, which is accumulating
2456 int nextOffset;
2457 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2458 if (offset >= 0)
2459 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2460 offset = nextOffset;
2461 }
2462
2463 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2464 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2465
2466 // built-in variable decorations
2467 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002468 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002469 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002470
2471#ifdef NV_EXTENSIONS
2472 if (builtIn == spv::BuiltInLayer) {
2473 // SPV_NV_viewport_array2 extension
2474 if (glslangMember.getQualifier().layoutViewportRelative){
2475 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2476 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2477 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2478 }
2479 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2480 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2481 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2482 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2483 }
2484 }
chaocdf3956c2017-02-14 14:52:34 -08002485 if (glslangMember.getQualifier().layoutPassthrough) {
2486 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2487 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2488 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2489 }
chaoc771d89f2017-01-13 01:10:53 -08002490#endif
John Kessenich6090df02016-06-30 21:18:02 -06002491 }
2492 }
2493
2494 // Decorate the structure
2495 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002496 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002497 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2498 builder.addCapability(spv::CapabilityGeometryStreams);
2499 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2500 }
2501 if (glslangIntermediate->getXfbMode()) {
2502 builder.addCapability(spv::CapabilityTransformFeedback);
2503 if (type.getQualifier().hasXfbStride())
2504 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2505 if (type.getQualifier().hasXfbBuffer())
2506 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2507 }
2508}
2509
John Kessenich6c292d32016-02-15 20:58:50 -07002510// Turn the expression forming the array size into an id.
2511// This is not quite trivial, because of specialization constants.
2512// Sometimes, a raw constant is turned into an Id, and sometimes
2513// a specialization constant expression is.
2514spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2515{
2516 // First, see if this is sized with a node, meaning a specialization constant:
2517 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2518 if (specNode != nullptr) {
2519 builder.clearAccessChain();
2520 specNode->traverse(this);
2521 return accessChainLoad(specNode->getAsTyped()->getType());
2522 }
qining25262b32016-05-06 17:25:16 -04002523
John Kessenich6c292d32016-02-15 20:58:50 -07002524 // Otherwise, need a compile-time (front end) size, get it:
2525 int size = arraySizes.getDimSize(dim);
2526 assert(size > 0);
2527 return builder.makeUintConstant(size);
2528}
2529
John Kessenich103bef92016-02-08 21:38:15 -07002530// Wrap the builder's accessChainLoad to:
2531// - localize handling of RelaxedPrecision
2532// - use the SPIR-V inferred type instead of another conversion of the glslang type
2533// (avoids unnecessary work and possible type punning for structures)
2534// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002535spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2536{
John Kessenich103bef92016-02-08 21:38:15 -07002537 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2538 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2539
2540 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002541 if (type.getBasicType() == glslang::EbtBool) {
2542 if (builder.isScalarType(nominalTypeId)) {
2543 // Conversion for bool
2544 spv::Id boolType = builder.makeBoolType();
2545 if (nominalTypeId != boolType)
2546 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2547 } else if (builder.isVectorType(nominalTypeId)) {
2548 // Conversion for bvec
2549 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2550 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2551 if (nominalTypeId != bvecType)
2552 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2553 }
2554 }
John Kessenich103bef92016-02-08 21:38:15 -07002555
2556 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002557}
2558
Rex Xu27253232016-02-23 17:51:09 +08002559// Wrap the builder's accessChainStore to:
2560// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002561//
2562// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002563void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2564{
2565 // Need to convert to abstract types when necessary
2566 if (type.getBasicType() == glslang::EbtBool) {
2567 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2568
2569 if (builder.isScalarType(nominalTypeId)) {
2570 // Conversion for bool
2571 spv::Id boolType = builder.makeBoolType();
2572 if (nominalTypeId != boolType) {
2573 spv::Id zero = builder.makeUintConstant(0);
2574 spv::Id one = builder.makeUintConstant(1);
2575 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2576 }
2577 } else if (builder.isVectorType(nominalTypeId)) {
2578 // Conversion for bvec
2579 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2580 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2581 if (nominalTypeId != bvecType) {
2582 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2583 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2584 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2585 }
2586 }
2587 }
2588
2589 builder.accessChainStore(rvalue);
2590}
2591
John Kessenich4bf71552016-09-02 11:20:21 -06002592// For storing when types match at the glslang level, but not might match at the
2593// SPIR-V level.
2594//
2595// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002596// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002597// as in a member-decorated way.
2598//
2599// NOTE: This function can handle any store request; if it's not special it
2600// simplifies to a simple OpStore.
2601//
2602// Implicitly uses the existing builder.accessChain as the storage target.
2603void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2604{
John Kessenichb3e24e42016-09-11 12:33:43 -06002605 // we only do the complex path here if it's an aggregate
2606 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002607 accessChainStore(type, rValue);
2608 return;
2609 }
2610
John Kessenichb3e24e42016-09-11 12:33:43 -06002611 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002612 spv::Id rType = builder.getTypeId(rValue);
2613 spv::Id lValue = builder.accessChainGetLValue();
2614 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2615 if (lType == rType) {
2616 accessChainStore(type, rValue);
2617 return;
2618 }
2619
John Kessenichb3e24e42016-09-11 12:33:43 -06002620 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002621 // where the two types were the same type in GLSL. This requires member
2622 // by member copy, recursively.
2623
John Kessenichb3e24e42016-09-11 12:33:43 -06002624 // If an array, copy element by element.
2625 if (type.isArray()) {
2626 glslang::TType glslangElementType(type, 0);
2627 spv::Id elementRType = builder.getContainedTypeId(rType);
2628 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2629 // get the source member
2630 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002631
John Kessenichb3e24e42016-09-11 12:33:43 -06002632 // set up the target storage
2633 builder.clearAccessChain();
2634 builder.setAccessChainLValue(lValue);
2635 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002636
John Kessenichb3e24e42016-09-11 12:33:43 -06002637 // store the member
2638 multiTypeStore(glslangElementType, elementRValue);
2639 }
2640 } else {
2641 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002642
John Kessenichb3e24e42016-09-11 12:33:43 -06002643 // loop over structure members
2644 const glslang::TTypeList& members = *type.getStruct();
2645 for (int m = 0; m < (int)members.size(); ++m) {
2646 const glslang::TType& glslangMemberType = *members[m].type;
2647
2648 // get the source member
2649 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2650 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2651
2652 // set up the target storage
2653 builder.clearAccessChain();
2654 builder.setAccessChainLValue(lValue);
2655 builder.accessChainPush(builder.makeIntConstant(m));
2656
2657 // store the member
2658 multiTypeStore(glslangMemberType, memberRValue);
2659 }
John Kessenich4bf71552016-09-02 11:20:21 -06002660 }
2661}
2662
John Kessenichf85e8062015-12-19 13:57:10 -07002663// Decide whether or not this type should be
2664// decorated with offsets and strides, and if so
2665// whether std140 or std430 rules should be applied.
2666glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002667{
John Kessenichf85e8062015-12-19 13:57:10 -07002668 // has to be a block
2669 if (type.getBasicType() != glslang::EbtBlock)
2670 return glslang::ElpNone;
2671
2672 // has to be a uniform or buffer block
2673 if (type.getQualifier().storage != glslang::EvqUniform &&
2674 type.getQualifier().storage != glslang::EvqBuffer)
2675 return glslang::ElpNone;
2676
2677 // return the layout to use
2678 switch (type.getQualifier().layoutPacking) {
2679 case glslang::ElpStd140:
2680 case glslang::ElpStd430:
2681 return type.getQualifier().layoutPacking;
2682 default:
2683 return glslang::ElpNone;
2684 }
John Kessenich31ed4832015-09-09 17:51:38 -06002685}
2686
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002687// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002688int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002689{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002690 int size;
John Kessenich49987892015-12-29 17:11:44 -07002691 int stride;
2692 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002693
2694 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002695}
2696
John Kessenich49987892015-12-29 17:11:44 -07002697// 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 -07002698// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002699int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002700{
John Kessenich49987892015-12-29 17:11:44 -07002701 glslang::TType elementType;
2702 elementType.shallowCopy(matrixType);
2703 elementType.clearArraySizes();
2704
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002705 int size;
John Kessenich49987892015-12-29 17:11:44 -07002706 int stride;
2707 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2708
2709 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002710}
2711
John Kessenich5e4b1242015-08-06 22:53:06 -06002712// Given a member type of a struct, realign the current offset for it, and compute
2713// the next (not yet aligned) offset for the next member, which will get aligned
2714// on the next call.
2715// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2716// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2717// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002718void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002719 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002720{
2721 // this will get a positive value when deemed necessary
2722 nextOffset = -1;
2723
John Kessenich5e4b1242015-08-06 22:53:06 -06002724 // override anything in currentOffset with user-set offset
2725 if (memberType.getQualifier().hasOffset())
2726 currentOffset = memberType.getQualifier().layoutOffset;
2727
2728 // It could be that current linker usage in glslang updated all the layoutOffset,
2729 // in which case the following code does not matter. But, that's not quite right
2730 // once cross-compilation unit GLSL validation is done, as the original user
2731 // settings are needed in layoutOffset, and then the following will come into play.
2732
John Kessenichf85e8062015-12-19 13:57:10 -07002733 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002734 if (! memberType.getQualifier().hasOffset())
2735 currentOffset = -1;
2736
2737 return;
2738 }
2739
John Kessenichf85e8062015-12-19 13:57:10 -07002740 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002741 if (currentOffset < 0)
2742 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002743
John Kessenich5e4b1242015-08-06 22:53:06 -06002744 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2745 // but possibly not yet correctly aligned.
2746
2747 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002748 int dummyStride;
2749 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002750
2751 // Adjust alignment for HLSL rules
2752 if (glslangIntermediate->usingHlslOFfsets() &&
2753 ! memberType.isArray() && memberType.isVector()) {
2754 int dummySize;
2755 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2756 if (componentAlignment <= 4)
2757 memberAlignment = componentAlignment;
2758 }
2759
2760 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002761 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002762
2763 // Bump up to vec4 if there is a bad straddle
2764 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2765 glslang::RoundToPow2(currentOffset, 16);
2766
John Kessenich5e4b1242015-08-06 22:53:06 -06002767 nextOffset = currentOffset + memberSize;
2768}
2769
David Netoa901ffe2016-06-08 14:11:40 +01002770void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002771{
David Netoa901ffe2016-06-08 14:11:40 +01002772 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2773 switch (glslangBuiltIn)
2774 {
2775 case glslang::EbvClipDistance:
2776 case glslang::EbvCullDistance:
2777 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002778#ifdef NV_EXTENSIONS
2779 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002780 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002781 case glslang::EbvViewportMaskNV:
2782 case glslang::EbvSecondaryPositionNV:
2783 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002784 case glslang::EbvPositionPerViewNV:
2785 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002786#endif
David Netoa901ffe2016-06-08 14:11:40 +01002787 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2788 // Alternately, we could just call this for any glslang built-in, since the
2789 // capability already guards against duplicates.
2790 TranslateBuiltInDecoration(glslangBuiltIn, false);
2791 break;
2792 default:
2793 // Capabilities were already generated when the struct was declared.
2794 break;
2795 }
John Kessenichebb50532016-05-16 19:22:05 -06002796}
2797
John Kessenich6fccb3c2016-09-19 16:01:41 -06002798bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002799{
John Kessenicheee9d532016-09-19 18:09:30 -06002800 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002801}
2802
2803// Make all the functions, skeletally, without actually visiting their bodies.
2804void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2805{
2806 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2807 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002808 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002809 continue;
2810
2811 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002812 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002813 //
qining25262b32016-05-06 17:25:16 -04002814 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002815 // function. What it is an address of varies:
2816 //
John Kessenich4bf71552016-09-02 11:20:21 -06002817 // - "in" parameters not marked as "const" can be written to without modifying the calling
2818 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002819 //
2820 // - "const in" parameters can just be the r-value, as no writes need occur.
2821 //
John Kessenich4bf71552016-09-02 11:20:21 -06002822 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2823 // 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 -06002824
2825 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002826 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002827 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2828
John Kessenich37789792017-03-21 23:56:40 -06002829 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() == glslangIntermediate->implicitThisName;
2830
John Kessenich140f3df2015-06-26 16:58:36 -06002831 for (int p = 0; p < (int)parameters.size(); ++p) {
2832 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2833 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002834 // can we pass by reference?
2835 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002836 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002837 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002838 (p == 0 && implicitThis)) // implicit 'this'
John Kessenich67027182017-04-19 18:34:49 -06002839 typeId = builder.makePointer(TranslateStorageClass(paramType, glslangIntermediate->usingStorageBuffer()), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002840 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002841 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2842 else
John Kessenich4bf71552016-09-02 11:20:21 -06002843 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002844 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002845 paramTypes.push_back(typeId);
2846 }
2847
2848 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002849 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2850 convertGlslangToSpvType(glslFunction->getType()),
2851 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06002852 if (implicitThis)
2853 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06002854
2855 // Track function to emit/call later
2856 functionMap[glslFunction->getName().c_str()] = function;
2857
2858 // Set the parameter id's
2859 for (int p = 0; p < (int)parameters.size(); ++p) {
2860 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2861 // give a name too
2862 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2863 }
2864 }
2865}
2866
2867// Process all the initializers, while skipping the functions and link objects
2868void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2869{
2870 builder.setBuildPoint(shaderEntry->getLastBlock());
2871 for (int i = 0; i < (int)initializers.size(); ++i) {
2872 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2873 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2874
2875 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002876 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002877 initializer->traverse(this);
2878 }
2879 }
2880}
2881
2882// Process all the functions, while skipping initializers.
2883void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2884{
2885 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2886 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002887 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002888 node->traverse(this);
2889 }
2890}
2891
2892void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2893{
qining25262b32016-05-06 17:25:16 -04002894 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002895 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002896 currentFunction = functionMap[node->getName().c_str()];
2897 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002898 builder.setBuildPoint(functionBlock);
2899}
2900
Rex Xu04db3f52015-09-16 11:44:02 +08002901void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002902{
Rex Xufc618912015-09-09 16:42:49 +08002903 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002904
2905 glslang::TSampler sampler = {};
2906 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002907 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002908 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2909 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2910 }
2911
John Kessenich140f3df2015-06-26 16:58:36 -06002912 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2913 builder.clearAccessChain();
2914 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002915
2916 // Special case l-value operands
2917 bool lvalue = false;
2918 switch (node.getOp()) {
2919 case glslang::EOpImageAtomicAdd:
2920 case glslang::EOpImageAtomicMin:
2921 case glslang::EOpImageAtomicMax:
2922 case glslang::EOpImageAtomicAnd:
2923 case glslang::EOpImageAtomicOr:
2924 case glslang::EOpImageAtomicXor:
2925 case glslang::EOpImageAtomicExchange:
2926 case glslang::EOpImageAtomicCompSwap:
2927 if (i == 0)
2928 lvalue = true;
2929 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002930 case glslang::EOpSparseImageLoad:
2931 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2932 lvalue = true;
2933 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002934 case glslang::EOpSparseTexture:
2935 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2936 lvalue = true;
2937 break;
2938 case glslang::EOpSparseTextureClamp:
2939 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2940 lvalue = true;
2941 break;
2942 case glslang::EOpSparseTextureLod:
2943 case glslang::EOpSparseTextureOffset:
2944 if (i == 3)
2945 lvalue = true;
2946 break;
2947 case glslang::EOpSparseTextureFetch:
2948 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2949 lvalue = true;
2950 break;
2951 case glslang::EOpSparseTextureFetchOffset:
2952 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2953 lvalue = true;
2954 break;
2955 case glslang::EOpSparseTextureLodOffset:
2956 case glslang::EOpSparseTextureGrad:
2957 case glslang::EOpSparseTextureOffsetClamp:
2958 if (i == 4)
2959 lvalue = true;
2960 break;
2961 case glslang::EOpSparseTextureGradOffset:
2962 case glslang::EOpSparseTextureGradClamp:
2963 if (i == 5)
2964 lvalue = true;
2965 break;
2966 case glslang::EOpSparseTextureGradOffsetClamp:
2967 if (i == 6)
2968 lvalue = true;
2969 break;
2970 case glslang::EOpSparseTextureGather:
2971 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2972 lvalue = true;
2973 break;
2974 case glslang::EOpSparseTextureGatherOffset:
2975 case glslang::EOpSparseTextureGatherOffsets:
2976 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2977 lvalue = true;
2978 break;
Rex Xufc618912015-09-09 16:42:49 +08002979 default:
2980 break;
2981 }
2982
Rex Xu6b86d492015-09-16 17:48:22 +08002983 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002984 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002985 else
John Kessenich32cfd492016-02-02 12:37:46 -07002986 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002987 }
2988}
2989
John Kessenichfc51d282015-08-19 13:34:18 -06002990void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002991{
John Kessenichfc51d282015-08-19 13:34:18 -06002992 builder.clearAccessChain();
2993 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002994 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002995}
John Kessenich140f3df2015-06-26 16:58:36 -06002996
John Kessenichfc51d282015-08-19 13:34:18 -06002997spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2998{
Rex Xufc618912015-09-09 16:42:49 +08002999 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06003000 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003001 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003002 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003003
John Kessenichfc51d282015-08-19 13:34:18 -06003004 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003005 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3006 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3007 std::vector<spv::Id> arguments;
3008 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003009 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003010 else
3011 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003012 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003013
3014 spv::Builder::TextureParameters params = { };
3015 params.sampler = arguments[0];
3016
Rex Xu04db3f52015-09-16 11:44:02 +08003017 glslang::TCrackedTextureOp cracked;
3018 node->crackTexture(sampler, cracked);
3019
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003020 const bool isUnsignedResult =
3021 node->getType().getBasicType() == glslang::EbtUint64 ||
3022 node->getType().getBasicType() == glslang::EbtUint;
3023
John Kessenichfc51d282015-08-19 13:34:18 -06003024 // Check for queries
3025 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003026 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3027 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003028 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003029
John Kessenichfc51d282015-08-19 13:34:18 -06003030 switch (node->getOp()) {
3031 case glslang::EOpImageQuerySize:
3032 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003033 if (arguments.size() > 1) {
3034 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003035 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003036 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003037 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003038 case glslang::EOpImageQuerySamples:
3039 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003040 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003041 case glslang::EOpTextureQueryLod:
3042 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003043 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003044 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003045 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003046 case glslang::EOpSparseTexelsResident:
3047 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003048 default:
3049 assert(0);
3050 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003051 }
John Kessenich140f3df2015-06-26 16:58:36 -06003052 }
3053
Rex Xufc618912015-09-09 16:42:49 +08003054 // Check for image functions other than queries
3055 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003056 std::vector<spv::Id> operands;
3057 auto opIt = arguments.begin();
3058 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003059
3060 // Handle subpass operations
3061 // TODO: GLSL should change to have the "MS" only on the type rather than the
3062 // built-in function.
3063 if (cracked.subpass) {
3064 // add on the (0,0) coordinate
3065 spv::Id zero = builder.makeIntConstant(0);
3066 std::vector<spv::Id> comps;
3067 comps.push_back(zero);
3068 comps.push_back(zero);
3069 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3070 if (sampler.ms) {
3071 operands.push_back(spv::ImageOperandsSampleMask);
3072 operands.push_back(*(opIt++));
3073 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003074 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003075 }
3076
John Kessenich56bab042015-09-16 10:54:31 -06003077 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003078 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003079 if (sampler.ms) {
3080 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003081 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003082 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003083 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3084 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003085 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003086 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003087 if (sampler.ms) {
3088 operands.push_back(*(opIt + 1));
3089 operands.push_back(spv::ImageOperandsSampleMask);
3090 operands.push_back(*opIt);
3091 } else
3092 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003093 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003094 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3095 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003096 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003097 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3098 builder.addCapability(spv::CapabilitySparseResidency);
3099 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3100 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3101
3102 if (sampler.ms) {
3103 operands.push_back(spv::ImageOperandsSampleMask);
3104 operands.push_back(*opIt++);
3105 }
3106
3107 // Create the return type that was a special structure
3108 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003109 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003110 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3111 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3112
3113 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3114
3115 // Decode the return type
3116 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3117 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003118 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003119 // Process image atomic operations
3120
3121 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3122 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003123 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003124
John Kessenich8c8505c2016-07-26 12:50:38 -06003125 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003126 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003127
3128 std::vector<spv::Id> operands;
3129 operands.push_back(pointer);
3130 for (; opIt != arguments.end(); ++opIt)
3131 operands.push_back(*opIt);
3132
John Kessenich8c8505c2016-07-26 12:50:38 -06003133 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003134 }
3135 }
3136
3137 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003138 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003139 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3140
John Kessenichfc51d282015-08-19 13:34:18 -06003141 // check for bias argument
3142 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003143 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003144 int nonBiasArgCount = 2;
3145 if (cracked.offset)
3146 ++nonBiasArgCount;
3147 if (cracked.grad)
3148 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003149 if (cracked.lodClamp)
3150 ++nonBiasArgCount;
3151 if (sparse)
3152 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003153
3154 if ((int)arguments.size() > nonBiasArgCount)
3155 bias = true;
3156 }
3157
John Kessenicha5c33d62016-06-02 23:45:21 -06003158 // See if the sampler param should really be just the SPV image part
3159 if (cracked.fetch) {
3160 // a fetch needs to have the image extracted first
3161 if (builder.isSampledImage(params.sampler))
3162 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3163 }
3164
John Kessenichfc51d282015-08-19 13:34:18 -06003165 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003166
John Kessenichfc51d282015-08-19 13:34:18 -06003167 params.coords = arguments[1];
3168 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003169 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003170
3171 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003172 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003173 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003174 ++extraArgs;
3175 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003176 params.Dref = arguments[2];
3177 ++extraArgs;
3178 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003179 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003180 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003181 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003182 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003183 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003184 dRefComp = builder.getNumComponents(params.coords) - 1;
3185 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003186 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3187 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003188
3189 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003190 if (cracked.lod) {
3191 params.lod = arguments[2];
3192 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003193 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3194 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3195 noImplicitLod = true;
3196 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003197
3198 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003199 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003200 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003201 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003202 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003203
3204 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003205 if (cracked.grad) {
3206 params.gradX = arguments[2 + extraArgs];
3207 params.gradY = arguments[3 + extraArgs];
3208 extraArgs += 2;
3209 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003210
3211 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003212 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003213 params.offset = arguments[2 + extraArgs];
3214 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003215 } else if (cracked.offsets) {
3216 params.offsets = arguments[2 + extraArgs];
3217 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003218 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003219
3220 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003221 if (cracked.lodClamp) {
3222 params.lodClamp = arguments[2 + extraArgs];
3223 ++extraArgs;
3224 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003225
3226 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003227 if (sparse) {
3228 params.texelOut = arguments[2 + extraArgs];
3229 ++extraArgs;
3230 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003231
3232 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003233 if (bias) {
3234 params.bias = arguments[2 + extraArgs];
3235 ++extraArgs;
3236 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003237
3238 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003239 if (cracked.gather && ! sampler.shadow) {
3240 // default component is 0, if missing, otherwise an argument
3241 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003242 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003243 ++extraArgs;
3244 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003245 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003246 }
3247 }
John Kessenichfc51d282015-08-19 13:34:18 -06003248
John Kessenich65336482016-06-16 14:06:26 -06003249 // projective component (might not to move)
3250 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3251 // are divided by the last component of P."
3252 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3253 // unused components will appear after all used components."
3254 if (cracked.proj) {
3255 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3256 int projTargetComp;
3257 switch (sampler.dim) {
3258 case glslang::Esd1D: projTargetComp = 1; break;
3259 case glslang::Esd2D: projTargetComp = 2; break;
3260 case glslang::EsdRect: projTargetComp = 2; break;
3261 default: projTargetComp = projSourceComp; break;
3262 }
3263 // copy the projective coordinate if we have to
3264 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003265 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003266 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3267 projSourceComp);
3268 params.coords = builder.createCompositeInsert(projComp, params.coords,
3269 builder.getTypeId(params.coords), projTargetComp);
3270 }
3271 }
3272
John Kessenich8c8505c2016-07-26 12:50:38 -06003273 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003274}
3275
3276spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3277{
3278 // Grab the function's pointer from the previously created function
3279 spv::Function* function = functionMap[node->getName().c_str()];
3280 if (! function)
3281 return 0;
3282
3283 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3284 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3285
3286 // See comments in makeFunctions() for details about the semantics for parameter passing.
3287 //
3288 // These imply we need a four step process:
3289 // 1. Evaluate the arguments
3290 // 2. Allocate and make copies of in, out, and inout arguments
3291 // 3. Make the call
3292 // 4. Copy back the results
3293
3294 // 1. Evaluate the arguments
3295 std::vector<spv::Builder::AccessChain> lValues;
3296 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003297 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003298 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003299 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003300 // build l-value
3301 builder.clearAccessChain();
3302 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003303 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003304 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003305 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003306 // save l-value
3307 lValues.push_back(builder.getAccessChain());
3308 } else {
3309 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003310 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003311 }
3312 }
3313
3314 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3315 // copy the original into that space.
3316 //
3317 // Also, build up the list of actual arguments to pass in for the call
3318 int lValueCount = 0;
3319 int rValueCount = 0;
3320 std::vector<spv::Id> spvArgs;
3321 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003322 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003323 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003324 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003325 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3326 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003327 builder.setAccessChain(lValues[lValueCount]);
3328 arg = builder.accessChainGetLValue();
3329 ++lValueCount;
3330 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003331 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003332 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3333 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3334 // need to copy the input into output space
3335 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003336 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003337 builder.clearAccessChain();
3338 builder.setAccessChainLValue(arg);
3339 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003340 }
3341 ++lValueCount;
3342 } else {
3343 arg = rValues[rValueCount];
3344 ++rValueCount;
3345 }
3346 spvArgs.push_back(arg);
3347 }
3348
3349 // 3. Make the call.
3350 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003351 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003352
3353 // 4. Copy back out an "out" arguments.
3354 lValueCount = 0;
3355 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003356 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003357 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3358 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3359 spv::Id copy = builder.createLoad(spvArgs[a]);
3360 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003361 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003362 }
3363 ++lValueCount;
3364 }
3365 }
3366
3367 return result;
3368}
3369
3370// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003371spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3372 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003373 spv::Id typeId, spv::Id left, spv::Id right,
3374 glslang::TBasicType typeProxy, bool reduceComparison)
3375{
Rex Xu8ff43de2016-04-22 16:51:45 +08003376 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003377#ifdef AMD_EXTENSIONS
3378 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3379#else
John Kessenich140f3df2015-06-26 16:58:36 -06003380 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003381#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003382 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003383
3384 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003385 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003386 bool comparison = false;
3387
3388 switch (op) {
3389 case glslang::EOpAdd:
3390 case glslang::EOpAddAssign:
3391 if (isFloat)
3392 binOp = spv::OpFAdd;
3393 else
3394 binOp = spv::OpIAdd;
3395 break;
3396 case glslang::EOpSub:
3397 case glslang::EOpSubAssign:
3398 if (isFloat)
3399 binOp = spv::OpFSub;
3400 else
3401 binOp = spv::OpISub;
3402 break;
3403 case glslang::EOpMul:
3404 case glslang::EOpMulAssign:
3405 if (isFloat)
3406 binOp = spv::OpFMul;
3407 else
3408 binOp = spv::OpIMul;
3409 break;
3410 case glslang::EOpVectorTimesScalar:
3411 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003412 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003413 if (builder.isVector(right))
3414 std::swap(left, right);
3415 assert(builder.isScalar(right));
3416 needMatchingVectors = false;
3417 binOp = spv::OpVectorTimesScalar;
3418 } else
3419 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003420 break;
3421 case glslang::EOpVectorTimesMatrix:
3422 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003423 binOp = spv::OpVectorTimesMatrix;
3424 break;
3425 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003426 binOp = spv::OpMatrixTimesVector;
3427 break;
3428 case glslang::EOpMatrixTimesScalar:
3429 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003430 binOp = spv::OpMatrixTimesScalar;
3431 break;
3432 case glslang::EOpMatrixTimesMatrix:
3433 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003434 binOp = spv::OpMatrixTimesMatrix;
3435 break;
3436 case glslang::EOpOuterProduct:
3437 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003438 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003439 break;
3440
3441 case glslang::EOpDiv:
3442 case glslang::EOpDivAssign:
3443 if (isFloat)
3444 binOp = spv::OpFDiv;
3445 else if (isUnsigned)
3446 binOp = spv::OpUDiv;
3447 else
3448 binOp = spv::OpSDiv;
3449 break;
3450 case glslang::EOpMod:
3451 case glslang::EOpModAssign:
3452 if (isFloat)
3453 binOp = spv::OpFMod;
3454 else if (isUnsigned)
3455 binOp = spv::OpUMod;
3456 else
3457 binOp = spv::OpSMod;
3458 break;
3459 case glslang::EOpRightShift:
3460 case glslang::EOpRightShiftAssign:
3461 if (isUnsigned)
3462 binOp = spv::OpShiftRightLogical;
3463 else
3464 binOp = spv::OpShiftRightArithmetic;
3465 break;
3466 case glslang::EOpLeftShift:
3467 case glslang::EOpLeftShiftAssign:
3468 binOp = spv::OpShiftLeftLogical;
3469 break;
3470 case glslang::EOpAnd:
3471 case glslang::EOpAndAssign:
3472 binOp = spv::OpBitwiseAnd;
3473 break;
3474 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003475 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003476 binOp = spv::OpLogicalAnd;
3477 break;
3478 case glslang::EOpInclusiveOr:
3479 case glslang::EOpInclusiveOrAssign:
3480 binOp = spv::OpBitwiseOr;
3481 break;
3482 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003483 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003484 binOp = spv::OpLogicalOr;
3485 break;
3486 case glslang::EOpExclusiveOr:
3487 case glslang::EOpExclusiveOrAssign:
3488 binOp = spv::OpBitwiseXor;
3489 break;
3490 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003491 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003492 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003493 break;
3494
3495 case glslang::EOpLessThan:
3496 case glslang::EOpGreaterThan:
3497 case glslang::EOpLessThanEqual:
3498 case glslang::EOpGreaterThanEqual:
3499 case glslang::EOpEqual:
3500 case glslang::EOpNotEqual:
3501 case glslang::EOpVectorEqual:
3502 case glslang::EOpVectorNotEqual:
3503 comparison = true;
3504 break;
3505 default:
3506 break;
3507 }
3508
John Kessenich7c1aa102015-10-15 13:29:11 -06003509 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003510 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003511 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003512 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003513 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003514
3515 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003516 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003517 builder.promoteScalar(precision, left, right);
3518
qining25262b32016-05-06 17:25:16 -04003519 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3520 addDecoration(result, noContraction);
3521 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003522 }
3523
3524 if (! comparison)
3525 return 0;
3526
John Kessenich7c1aa102015-10-15 13:29:11 -06003527 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003528
John Kessenich4583b612016-08-07 19:14:22 -06003529 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3530 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003531 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003532
3533 switch (op) {
3534 case glslang::EOpLessThan:
3535 if (isFloat)
3536 binOp = spv::OpFOrdLessThan;
3537 else if (isUnsigned)
3538 binOp = spv::OpULessThan;
3539 else
3540 binOp = spv::OpSLessThan;
3541 break;
3542 case glslang::EOpGreaterThan:
3543 if (isFloat)
3544 binOp = spv::OpFOrdGreaterThan;
3545 else if (isUnsigned)
3546 binOp = spv::OpUGreaterThan;
3547 else
3548 binOp = spv::OpSGreaterThan;
3549 break;
3550 case glslang::EOpLessThanEqual:
3551 if (isFloat)
3552 binOp = spv::OpFOrdLessThanEqual;
3553 else if (isUnsigned)
3554 binOp = spv::OpULessThanEqual;
3555 else
3556 binOp = spv::OpSLessThanEqual;
3557 break;
3558 case glslang::EOpGreaterThanEqual:
3559 if (isFloat)
3560 binOp = spv::OpFOrdGreaterThanEqual;
3561 else if (isUnsigned)
3562 binOp = spv::OpUGreaterThanEqual;
3563 else
3564 binOp = spv::OpSGreaterThanEqual;
3565 break;
3566 case glslang::EOpEqual:
3567 case glslang::EOpVectorEqual:
3568 if (isFloat)
3569 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003570 else if (isBool)
3571 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003572 else
3573 binOp = spv::OpIEqual;
3574 break;
3575 case glslang::EOpNotEqual:
3576 case glslang::EOpVectorNotEqual:
3577 if (isFloat)
3578 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003579 else if (isBool)
3580 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003581 else
3582 binOp = spv::OpINotEqual;
3583 break;
3584 default:
3585 break;
3586 }
3587
qining25262b32016-05-06 17:25:16 -04003588 if (binOp != spv::OpNop) {
3589 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3590 addDecoration(result, noContraction);
3591 return builder.setPrecision(result, precision);
3592 }
John Kessenich140f3df2015-06-26 16:58:36 -06003593
3594 return 0;
3595}
3596
John Kessenich04bb8a02015-12-12 12:28:14 -07003597//
3598// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3599// These can be any of:
3600//
3601// matrix * scalar
3602// scalar * matrix
3603// matrix * matrix linear algebraic
3604// matrix * vector
3605// vector * matrix
3606// matrix * matrix componentwise
3607// matrix op matrix op in {+, -, /}
3608// matrix op scalar op in {+, -, /}
3609// scalar op matrix op in {+, -, /}
3610//
qining25262b32016-05-06 17:25:16 -04003611spv::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 -07003612{
3613 bool firstClass = true;
3614
3615 // First, handle first-class matrix operations (* and matrix/scalar)
3616 switch (op) {
3617 case spv::OpFDiv:
3618 if (builder.isMatrix(left) && builder.isScalar(right)) {
3619 // turn matrix / scalar into a multiply...
3620 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3621 op = spv::OpMatrixTimesScalar;
3622 } else
3623 firstClass = false;
3624 break;
3625 case spv::OpMatrixTimesScalar:
3626 if (builder.isMatrix(right))
3627 std::swap(left, right);
3628 assert(builder.isScalar(right));
3629 break;
3630 case spv::OpVectorTimesMatrix:
3631 assert(builder.isVector(left));
3632 assert(builder.isMatrix(right));
3633 break;
3634 case spv::OpMatrixTimesVector:
3635 assert(builder.isMatrix(left));
3636 assert(builder.isVector(right));
3637 break;
3638 case spv::OpMatrixTimesMatrix:
3639 assert(builder.isMatrix(left));
3640 assert(builder.isMatrix(right));
3641 break;
3642 default:
3643 firstClass = false;
3644 break;
3645 }
3646
qining25262b32016-05-06 17:25:16 -04003647 if (firstClass) {
3648 spv::Id result = builder.createBinOp(op, typeId, left, right);
3649 addDecoration(result, noContraction);
3650 return builder.setPrecision(result, precision);
3651 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003652
LoopDawg592860c2016-06-09 08:57:35 -06003653 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003654 // The result type of all of them is the same type as the (a) matrix operand.
3655 // The algorithm is to:
3656 // - break the matrix(es) into vectors
3657 // - smear any scalar to a vector
3658 // - do vector operations
3659 // - make a matrix out the vector results
3660 switch (op) {
3661 case spv::OpFAdd:
3662 case spv::OpFSub:
3663 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003664 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003665 case spv::OpFMul:
3666 {
3667 // one time set up...
3668 bool leftMat = builder.isMatrix(left);
3669 bool rightMat = builder.isMatrix(right);
3670 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3671 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3672 spv::Id scalarType = builder.getScalarTypeId(typeId);
3673 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3674 std::vector<spv::Id> results;
3675 spv::Id smearVec = spv::NoResult;
3676 if (builder.isScalar(left))
3677 smearVec = builder.smearScalar(precision, left, vecType);
3678 else if (builder.isScalar(right))
3679 smearVec = builder.smearScalar(precision, right, vecType);
3680
3681 // do each vector op
3682 for (unsigned int c = 0; c < numCols; ++c) {
3683 std::vector<unsigned int> indexes;
3684 indexes.push_back(c);
3685 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3686 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003687 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3688 addDecoration(result, noContraction);
3689 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003690 }
3691
3692 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003693 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003694 }
3695 default:
3696 assert(0);
3697 return spv::NoResult;
3698 }
3699}
3700
qining25262b32016-05-06 17:25:16 -04003701spv::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 -06003702{
3703 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003704 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003705 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003706 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003707#ifdef AMD_EXTENSIONS
3708 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3709#else
Rex Xu04db3f52015-09-16 11:44:02 +08003710 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003711#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003712
3713 switch (op) {
3714 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003715 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003716 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003717 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003718 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003719 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003720 unaryOp = spv::OpSNegate;
3721 break;
3722
3723 case glslang::EOpLogicalNot:
3724 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003725 unaryOp = spv::OpLogicalNot;
3726 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003727 case glslang::EOpBitwiseNot:
3728 unaryOp = spv::OpNot;
3729 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003730
John Kessenich140f3df2015-06-26 16:58:36 -06003731 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003732 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003733 break;
3734 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003735 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003736 break;
3737 case glslang::EOpTranspose:
3738 unaryOp = spv::OpTranspose;
3739 break;
3740
3741 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003742 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003743 break;
3744 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003745 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003746 break;
3747 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003748 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003749 break;
3750 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003751 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003752 break;
3753 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003754 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003755 break;
3756 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003757 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003758 break;
3759 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003760 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003761 break;
3762 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003763 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003764 break;
3765
3766 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003767 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003768 break;
3769 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003770 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003771 break;
3772 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003773 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003774 break;
3775 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003776 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003777 break;
3778 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003779 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003780 break;
3781 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003782 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003783 break;
3784
3785 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003786 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003787 break;
3788 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003789 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003790 break;
3791
3792 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003793 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003794 break;
3795 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003796 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003797 break;
3798 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003799 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003800 break;
3801 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003802 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003803 break;
3804 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003805 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003806 break;
3807 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003808 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003809 break;
3810
3811 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003812 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003813 break;
3814 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003815 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003816 break;
3817 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003818 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003819 break;
3820 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003821 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003822 break;
3823 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003824 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003825 break;
3826 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003827 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003828 break;
3829
3830 case glslang::EOpIsNan:
3831 unaryOp = spv::OpIsNan;
3832 break;
3833 case glslang::EOpIsInf:
3834 unaryOp = spv::OpIsInf;
3835 break;
LoopDawg592860c2016-06-09 08:57:35 -06003836 case glslang::EOpIsFinite:
3837 unaryOp = spv::OpIsFinite;
3838 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003839
Rex Xucbc426e2015-12-15 16:03:10 +08003840 case glslang::EOpFloatBitsToInt:
3841 case glslang::EOpFloatBitsToUint:
3842 case glslang::EOpIntBitsToFloat:
3843 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003844 case glslang::EOpDoubleBitsToInt64:
3845 case glslang::EOpDoubleBitsToUint64:
3846 case glslang::EOpInt64BitsToDouble:
3847 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003848 unaryOp = spv::OpBitcast;
3849 break;
3850
John Kessenich140f3df2015-06-26 16:58:36 -06003851 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003852 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003853 break;
3854 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003855 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003856 break;
3857 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003858 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003859 break;
3860 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003861 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003862 break;
3863 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003864 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003865 break;
3866 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003867 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003868 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003869 case glslang::EOpPackSnorm4x8:
3870 libCall = spv::GLSLstd450PackSnorm4x8;
3871 break;
3872 case glslang::EOpUnpackSnorm4x8:
3873 libCall = spv::GLSLstd450UnpackSnorm4x8;
3874 break;
3875 case glslang::EOpPackUnorm4x8:
3876 libCall = spv::GLSLstd450PackUnorm4x8;
3877 break;
3878 case glslang::EOpUnpackUnorm4x8:
3879 libCall = spv::GLSLstd450UnpackUnorm4x8;
3880 break;
3881 case glslang::EOpPackDouble2x32:
3882 libCall = spv::GLSLstd450PackDouble2x32;
3883 break;
3884 case glslang::EOpUnpackDouble2x32:
3885 libCall = spv::GLSLstd450UnpackDouble2x32;
3886 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003887
Rex Xu8ff43de2016-04-22 16:51:45 +08003888 case glslang::EOpPackInt2x32:
3889 case glslang::EOpUnpackInt2x32:
3890 case glslang::EOpPackUint2x32:
3891 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003892 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003893 break;
3894
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003895#ifdef AMD_EXTENSIONS
3896 case glslang::EOpPackFloat2x16:
3897 case glslang::EOpUnpackFloat2x16:
3898 unaryOp = spv::OpBitcast;
3899 break;
3900#endif
3901
John Kessenich140f3df2015-06-26 16:58:36 -06003902 case glslang::EOpDPdx:
3903 unaryOp = spv::OpDPdx;
3904 break;
3905 case glslang::EOpDPdy:
3906 unaryOp = spv::OpDPdy;
3907 break;
3908 case glslang::EOpFwidth:
3909 unaryOp = spv::OpFwidth;
3910 break;
3911 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003912 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003913 unaryOp = spv::OpDPdxFine;
3914 break;
3915 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003916 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003917 unaryOp = spv::OpDPdyFine;
3918 break;
3919 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003920 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003921 unaryOp = spv::OpFwidthFine;
3922 break;
3923 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003924 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003925 unaryOp = spv::OpDPdxCoarse;
3926 break;
3927 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003928 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003929 unaryOp = spv::OpDPdyCoarse;
3930 break;
3931 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003932 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003933 unaryOp = spv::OpFwidthCoarse;
3934 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003935 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003936 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003937 libCall = spv::GLSLstd450InterpolateAtCentroid;
3938 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003939 case glslang::EOpAny:
3940 unaryOp = spv::OpAny;
3941 break;
3942 case glslang::EOpAll:
3943 unaryOp = spv::OpAll;
3944 break;
3945
3946 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003947 if (isFloat)
3948 libCall = spv::GLSLstd450FAbs;
3949 else
3950 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003951 break;
3952 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003953 if (isFloat)
3954 libCall = spv::GLSLstd450FSign;
3955 else
3956 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003957 break;
3958
John Kessenichfc51d282015-08-19 13:34:18 -06003959 case glslang::EOpAtomicCounterIncrement:
3960 case glslang::EOpAtomicCounterDecrement:
3961 case glslang::EOpAtomicCounter:
3962 {
3963 // Handle all of the atomics in one place, in createAtomicOperation()
3964 std::vector<spv::Id> operands;
3965 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003966 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003967 }
3968
John Kessenichfc51d282015-08-19 13:34:18 -06003969 case glslang::EOpBitFieldReverse:
3970 unaryOp = spv::OpBitReverse;
3971 break;
3972 case glslang::EOpBitCount:
3973 unaryOp = spv::OpBitCount;
3974 break;
3975 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003976 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003977 break;
3978 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003979 if (isUnsigned)
3980 libCall = spv::GLSLstd450FindUMsb;
3981 else
3982 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003983 break;
3984
Rex Xu574ab042016-04-14 16:53:07 +08003985 case glslang::EOpBallot:
3986 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003987 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08003988 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08003989 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08003990#ifdef AMD_EXTENSIONS
3991 case glslang::EOpMinInvocations:
3992 case glslang::EOpMaxInvocations:
3993 case glslang::EOpAddInvocations:
3994 case glslang::EOpMinInvocationsNonUniform:
3995 case glslang::EOpMaxInvocationsNonUniform:
3996 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08003997 case glslang::EOpMinInvocationsInclusiveScan:
3998 case glslang::EOpMaxInvocationsInclusiveScan:
3999 case glslang::EOpAddInvocationsInclusiveScan:
4000 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4001 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4002 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4003 case glslang::EOpMinInvocationsExclusiveScan:
4004 case glslang::EOpMaxInvocationsExclusiveScan:
4005 case glslang::EOpAddInvocationsExclusiveScan:
4006 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4007 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4008 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004009#endif
Rex Xu51596642016-09-21 18:56:12 +08004010 {
4011 std::vector<spv::Id> operands;
4012 operands.push_back(operand);
4013 return createInvocationsOperation(op, typeId, operands, typeProxy);
4014 }
Rex Xu9d93a232016-05-05 12:30:44 +08004015
4016#ifdef AMD_EXTENSIONS
4017 case glslang::EOpMbcnt:
4018 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4019 libCall = spv::MbcntAMD;
4020 break;
4021
4022 case glslang::EOpCubeFaceIndex:
4023 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4024 libCall = spv::CubeFaceIndexAMD;
4025 break;
4026
4027 case glslang::EOpCubeFaceCoord:
4028 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4029 libCall = spv::CubeFaceCoordAMD;
4030 break;
4031#endif
Rex Xu338b1852016-05-05 20:38:33 +08004032
John Kessenich140f3df2015-06-26 16:58:36 -06004033 default:
4034 return 0;
4035 }
4036
4037 spv::Id id;
4038 if (libCall >= 0) {
4039 std::vector<spv::Id> args;
4040 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004041 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004042 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004043 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004044 }
John Kessenich140f3df2015-06-26 16:58:36 -06004045
qining25262b32016-05-06 17:25:16 -04004046 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004047 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004048}
4049
John Kessenich7a53f762016-01-20 11:19:27 -07004050// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004051spv::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 -07004052{
4053 // Handle unary operations vector by vector.
4054 // The result type is the same type as the original type.
4055 // The algorithm is to:
4056 // - break the matrix into vectors
4057 // - apply the operation to each vector
4058 // - make a matrix out the vector results
4059
4060 // get the types sorted out
4061 int numCols = builder.getNumColumns(operand);
4062 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004063 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4064 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004065 std::vector<spv::Id> results;
4066
4067 // do each vector op
4068 for (int c = 0; c < numCols; ++c) {
4069 std::vector<unsigned int> indexes;
4070 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004071 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4072 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4073 addDecoration(destVec, noContraction);
4074 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004075 }
4076
4077 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004078 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004079}
4080
Rex Xu73e3ce72016-04-27 18:48:17 +08004081spv::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 -06004082{
4083 spv::Op convOp = spv::OpNop;
4084 spv::Id zero = 0;
4085 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004086 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004087
4088 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4089
4090 switch (op) {
4091 case glslang::EOpConvIntToBool:
4092 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004093 case glslang::EOpConvInt64ToBool:
4094 case glslang::EOpConvUint64ToBool:
4095 zero = (op == glslang::EOpConvInt64ToBool ||
4096 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004097 zero = makeSmearedConstant(zero, vectorSize);
4098 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4099
4100 case glslang::EOpConvFloatToBool:
4101 zero = builder.makeFloatConstant(0.0F);
4102 zero = makeSmearedConstant(zero, vectorSize);
4103 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4104
4105 case glslang::EOpConvDoubleToBool:
4106 zero = builder.makeDoubleConstant(0.0);
4107 zero = makeSmearedConstant(zero, vectorSize);
4108 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4109
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004110#ifdef AMD_EXTENSIONS
4111 case glslang::EOpConvFloat16ToBool:
4112 zero = builder.makeFloat16Constant(0.0F);
4113 zero = makeSmearedConstant(zero, vectorSize);
4114 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4115#endif
4116
John Kessenich140f3df2015-06-26 16:58:36 -06004117 case glslang::EOpConvBoolToFloat:
4118 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004119 zero = builder.makeFloatConstant(0.0F);
4120 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004121 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004122
John Kessenich140f3df2015-06-26 16:58:36 -06004123 case glslang::EOpConvBoolToDouble:
4124 convOp = spv::OpSelect;
4125 zero = builder.makeDoubleConstant(0.0);
4126 one = builder.makeDoubleConstant(1.0);
4127 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004128
4129#ifdef AMD_EXTENSIONS
4130 case glslang::EOpConvBoolToFloat16:
4131 convOp = spv::OpSelect;
4132 zero = builder.makeFloat16Constant(0.0F);
4133 one = builder.makeFloat16Constant(1.0F);
4134 break;
4135#endif
4136
John Kessenich140f3df2015-06-26 16:58:36 -06004137 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004138 case glslang::EOpConvBoolToInt64:
4139 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4140 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004141 convOp = spv::OpSelect;
4142 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004143
John Kessenich140f3df2015-06-26 16:58:36 -06004144 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004145 case glslang::EOpConvBoolToUint64:
4146 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4147 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004148 convOp = spv::OpSelect;
4149 break;
4150
4151 case glslang::EOpConvIntToFloat:
4152 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004153 case glslang::EOpConvInt64ToFloat:
4154 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004155#ifdef AMD_EXTENSIONS
4156 case glslang::EOpConvIntToFloat16:
4157 case glslang::EOpConvInt64ToFloat16:
4158#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004159 convOp = spv::OpConvertSToF;
4160 break;
4161
4162 case glslang::EOpConvUintToFloat:
4163 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004164 case glslang::EOpConvUint64ToFloat:
4165 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004166#ifdef AMD_EXTENSIONS
4167 case glslang::EOpConvUintToFloat16:
4168 case glslang::EOpConvUint64ToFloat16:
4169#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004170 convOp = spv::OpConvertUToF;
4171 break;
4172
4173 case glslang::EOpConvDoubleToFloat:
4174 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004175#ifdef AMD_EXTENSIONS
4176 case glslang::EOpConvDoubleToFloat16:
4177 case glslang::EOpConvFloat16ToDouble:
4178 case glslang::EOpConvFloatToFloat16:
4179 case glslang::EOpConvFloat16ToFloat:
4180#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004181 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004182 if (builder.isMatrixType(destType))
4183 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004184 break;
4185
4186 case glslang::EOpConvFloatToInt:
4187 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004188 case glslang::EOpConvFloatToInt64:
4189 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004190#ifdef AMD_EXTENSIONS
4191 case glslang::EOpConvFloat16ToInt:
4192 case glslang::EOpConvFloat16ToInt64:
4193#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004194 convOp = spv::OpConvertFToS;
4195 break;
4196
4197 case glslang::EOpConvUintToInt:
4198 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004199 case glslang::EOpConvUint64ToInt64:
4200 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004201 if (builder.isInSpecConstCodeGenMode()) {
4202 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004203 zero = (op == glslang::EOpConvUint64ToInt64 ||
4204 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004205 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004206 // Use OpIAdd, instead of OpBitcast to do the conversion when
4207 // generating for OpSpecConstantOp instruction.
4208 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4209 }
4210 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004211 convOp = spv::OpBitcast;
4212 break;
4213
4214 case glslang::EOpConvFloatToUint:
4215 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004216 case glslang::EOpConvFloatToUint64:
4217 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004218#ifdef AMD_EXTENSIONS
4219 case glslang::EOpConvFloat16ToUint:
4220 case glslang::EOpConvFloat16ToUint64:
4221#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004222 convOp = spv::OpConvertFToU;
4223 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004224
4225 case glslang::EOpConvIntToInt64:
4226 case glslang::EOpConvInt64ToInt:
4227 convOp = spv::OpSConvert;
4228 break;
4229
4230 case glslang::EOpConvUintToUint64:
4231 case glslang::EOpConvUint64ToUint:
4232 convOp = spv::OpUConvert;
4233 break;
4234
4235 case glslang::EOpConvIntToUint64:
4236 case glslang::EOpConvInt64ToUint:
4237 case glslang::EOpConvUint64ToInt:
4238 case glslang::EOpConvUintToInt64:
4239 // OpSConvert/OpUConvert + OpBitCast
4240 switch (op) {
4241 case glslang::EOpConvIntToUint64:
4242 convOp = spv::OpSConvert;
4243 type = builder.makeIntType(64);
4244 break;
4245 case glslang::EOpConvInt64ToUint:
4246 convOp = spv::OpSConvert;
4247 type = builder.makeIntType(32);
4248 break;
4249 case glslang::EOpConvUint64ToInt:
4250 convOp = spv::OpUConvert;
4251 type = builder.makeUintType(32);
4252 break;
4253 case glslang::EOpConvUintToInt64:
4254 convOp = spv::OpUConvert;
4255 type = builder.makeUintType(64);
4256 break;
4257 default:
4258 assert(0);
4259 break;
4260 }
4261
4262 if (vectorSize > 0)
4263 type = builder.makeVectorType(type, vectorSize);
4264
4265 operand = builder.createUnaryOp(convOp, type, operand);
4266
4267 if (builder.isInSpecConstCodeGenMode()) {
4268 // Build zero scalar or vector for OpIAdd.
4269 zero = (op == glslang::EOpConvIntToUint64 ||
4270 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4271 zero = makeSmearedConstant(zero, vectorSize);
4272 // Use OpIAdd, instead of OpBitcast to do the conversion when
4273 // generating for OpSpecConstantOp instruction.
4274 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4275 }
4276 // For normal run-time conversion instruction, use OpBitcast.
4277 convOp = spv::OpBitcast;
4278 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004279 default:
4280 break;
4281 }
4282
4283 spv::Id result = 0;
4284 if (convOp == spv::OpNop)
4285 return result;
4286
4287 if (convOp == spv::OpSelect) {
4288 zero = makeSmearedConstant(zero, vectorSize);
4289 one = makeSmearedConstant(one, vectorSize);
4290 result = builder.createTriOp(convOp, destType, operand, one, zero);
4291 } else
4292 result = builder.createUnaryOp(convOp, destType, operand);
4293
John Kessenich32cfd492016-02-02 12:37:46 -07004294 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004295}
4296
4297spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4298{
4299 if (vectorSize == 0)
4300 return constant;
4301
4302 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4303 std::vector<spv::Id> components;
4304 for (int c = 0; c < vectorSize; ++c)
4305 components.push_back(constant);
4306 return builder.makeCompositeConstant(vectorTypeId, components);
4307}
4308
John Kessenich426394d2015-07-23 10:22:48 -06004309// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004310spv::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 -06004311{
4312 spv::Op opCode = spv::OpNop;
4313
4314 switch (op) {
4315 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004316 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004317 opCode = spv::OpAtomicIAdd;
4318 break;
4319 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004320 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004321 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004322 break;
4323 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004324 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004325 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004326 break;
4327 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004328 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004329 opCode = spv::OpAtomicAnd;
4330 break;
4331 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004332 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004333 opCode = spv::OpAtomicOr;
4334 break;
4335 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004336 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004337 opCode = spv::OpAtomicXor;
4338 break;
4339 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004340 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004341 opCode = spv::OpAtomicExchange;
4342 break;
4343 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004344 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004345 opCode = spv::OpAtomicCompareExchange;
4346 break;
4347 case glslang::EOpAtomicCounterIncrement:
4348 opCode = spv::OpAtomicIIncrement;
4349 break;
4350 case glslang::EOpAtomicCounterDecrement:
4351 opCode = spv::OpAtomicIDecrement;
4352 break;
4353 case glslang::EOpAtomicCounter:
4354 opCode = spv::OpAtomicLoad;
4355 break;
4356 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004357 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004358 break;
4359 }
4360
4361 // Sort out the operands
4362 // - mapping from glslang -> SPV
4363 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004364 // - compare-exchange swaps the value and comparator
4365 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004366 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4367 auto opIt = operands.begin(); // walk the glslang operands
4368 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004369 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4370 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4371 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004372 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4373 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004374 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004375 spvAtomicOperands.push_back(*(opIt + 1));
4376 spvAtomicOperands.push_back(*opIt);
4377 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004378 }
John Kessenich426394d2015-07-23 10:22:48 -06004379
John Kessenich3e60a6f2015-09-14 22:45:16 -06004380 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004381 for (; opIt != operands.end(); ++opIt)
4382 spvAtomicOperands.push_back(*opIt);
4383
4384 return builder.createOp(opCode, typeId, spvAtomicOperands);
4385}
4386
John Kessenich91cef522016-05-05 16:45:40 -06004387// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004388spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004389{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004390#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004391 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004392 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004393#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004394
Rex Xu51596642016-09-21 18:56:12 +08004395 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004396 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004397 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4398
chaocf200da82016-12-20 12:44:35 -08004399 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4400 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004401 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4402 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004403 } else if (op == glslang::EOpAnyInvocation ||
4404 op == glslang::EOpAllInvocations ||
4405 op == glslang::EOpAllInvocationsEqual) {
4406 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4407 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004408 } else {
4409 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004410#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004411 if (op == glslang::EOpMinInvocationsNonUniform ||
4412 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004413 op == glslang::EOpAddInvocationsNonUniform ||
4414 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4415 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4416 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4417 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4418 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4419 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004420 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004421#endif
Rex Xu51596642016-09-21 18:56:12 +08004422
4423 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004424#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004425 switch (op) {
4426 case glslang::EOpMinInvocations:
4427 case glslang::EOpMaxInvocations:
4428 case glslang::EOpAddInvocations:
4429 case glslang::EOpMinInvocationsNonUniform:
4430 case glslang::EOpMaxInvocationsNonUniform:
4431 case glslang::EOpAddInvocationsNonUniform:
4432 groupOperation = spv::GroupOperationReduce;
4433 spvGroupOperands.push_back(groupOperation);
4434 break;
4435 case glslang::EOpMinInvocationsInclusiveScan:
4436 case glslang::EOpMaxInvocationsInclusiveScan:
4437 case glslang::EOpAddInvocationsInclusiveScan:
4438 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4439 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4440 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4441 groupOperation = spv::GroupOperationInclusiveScan;
4442 spvGroupOperands.push_back(groupOperation);
4443 break;
4444 case glslang::EOpMinInvocationsExclusiveScan:
4445 case glslang::EOpMaxInvocationsExclusiveScan:
4446 case glslang::EOpAddInvocationsExclusiveScan:
4447 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4448 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4449 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4450 groupOperation = spv::GroupOperationExclusiveScan;
4451 spvGroupOperands.push_back(groupOperation);
4452 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004453 default:
4454 break;
Rex Xu430ef402016-10-14 17:22:23 +08004455 }
Rex Xu9d93a232016-05-05 12:30:44 +08004456#endif
Rex Xu51596642016-09-21 18:56:12 +08004457 }
4458
4459 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4460 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004461
4462 switch (op) {
4463 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004464 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004465 break;
John Kessenich91cef522016-05-05 16:45:40 -06004466 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004467 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004468 break;
John Kessenich91cef522016-05-05 16:45:40 -06004469 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004470 opCode = spv::OpSubgroupAllEqualKHR;
4471 break;
Rex Xu51596642016-09-21 18:56:12 +08004472 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004473 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004474 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004475 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004476 break;
4477 case glslang::EOpReadFirstInvocation:
4478 opCode = spv::OpSubgroupFirstInvocationKHR;
4479 break;
4480 case glslang::EOpBallot:
4481 {
4482 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4483 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4484 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4485 //
4486 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4487 //
4488 spv::Id uintType = builder.makeUintType(32);
4489 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4490 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4491
4492 std::vector<spv::Id> components;
4493 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4494 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4495
4496 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4497 return builder.createUnaryOp(spv::OpBitcast, typeId,
4498 builder.createCompositeConstruct(uvec2Type, components));
4499 }
4500
Rex Xu9d93a232016-05-05 12:30:44 +08004501#ifdef AMD_EXTENSIONS
4502 case glslang::EOpMinInvocations:
4503 case glslang::EOpMaxInvocations:
4504 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004505 case glslang::EOpMinInvocationsInclusiveScan:
4506 case glslang::EOpMaxInvocationsInclusiveScan:
4507 case glslang::EOpAddInvocationsInclusiveScan:
4508 case glslang::EOpMinInvocationsExclusiveScan:
4509 case glslang::EOpMaxInvocationsExclusiveScan:
4510 case glslang::EOpAddInvocationsExclusiveScan:
4511 if (op == glslang::EOpMinInvocations ||
4512 op == glslang::EOpMinInvocationsInclusiveScan ||
4513 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004514 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004515 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004516 else {
4517 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004518 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004519 else
Rex Xu51596642016-09-21 18:56:12 +08004520 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004521 }
Rex Xu430ef402016-10-14 17:22:23 +08004522 } else if (op == glslang::EOpMaxInvocations ||
4523 op == glslang::EOpMaxInvocationsInclusiveScan ||
4524 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004525 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004526 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004527 else {
4528 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004529 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004530 else
Rex Xu51596642016-09-21 18:56:12 +08004531 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004532 }
4533 } else {
4534 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004535 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004536 else
Rex Xu51596642016-09-21 18:56:12 +08004537 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004538 }
4539
Rex Xu2bbbe062016-08-23 15:41:05 +08004540 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004541 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004542
4543 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004544 case glslang::EOpMinInvocationsNonUniform:
4545 case glslang::EOpMaxInvocationsNonUniform:
4546 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004547 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4548 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4549 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4550 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4551 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4552 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4553 if (op == glslang::EOpMinInvocationsNonUniform ||
4554 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4555 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004556 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004557 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004558 else {
4559 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004560 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004561 else
Rex Xu51596642016-09-21 18:56:12 +08004562 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004563 }
4564 }
Rex Xu430ef402016-10-14 17:22:23 +08004565 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4566 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4567 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004568 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004569 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004570 else {
4571 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004572 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004573 else
Rex Xu51596642016-09-21 18:56:12 +08004574 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004575 }
4576 }
4577 else {
4578 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004579 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004580 else
Rex Xu51596642016-09-21 18:56:12 +08004581 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004582 }
4583
Rex Xu2bbbe062016-08-23 15:41:05 +08004584 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004585 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004586
4587 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004588#endif
John Kessenich91cef522016-05-05 16:45:40 -06004589 default:
4590 logger->missingFunctionality("invocation operation");
4591 return spv::NoResult;
4592 }
Rex Xu51596642016-09-21 18:56:12 +08004593
4594 assert(opCode != spv::OpNop);
4595 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004596}
4597
Rex Xu2bbbe062016-08-23 15:41:05 +08004598// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004599spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004600{
Rex Xub7072052016-09-26 15:53:40 +08004601#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004602 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4603 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004604 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004605 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004606 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4607 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4608 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004609#else
4610 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4611 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004612 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4613 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004614#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004615
4616 // Handle group invocation operations scalar by scalar.
4617 // The result type is the same type as the original type.
4618 // The algorithm is to:
4619 // - break the vector into scalars
4620 // - apply the operation to each scalar
4621 // - make a vector out the scalar results
4622
4623 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004624 int numComponents = builder.getNumComponents(operands[0]);
4625 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004626 std::vector<spv::Id> results;
4627
4628 // do each scalar op
4629 for (int comp = 0; comp < numComponents; ++comp) {
4630 std::vector<unsigned int> indexes;
4631 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004632 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004633 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004634 if (op == spv::OpSubgroupReadInvocationKHR) {
4635 spvGroupOperands.push_back(scalar);
4636 spvGroupOperands.push_back(operands[1]);
4637 } else if (op == spv::OpGroupBroadcast) {
4638 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004639 spvGroupOperands.push_back(scalar);
4640 spvGroupOperands.push_back(operands[1]);
4641 } else {
chaocf200da82016-12-20 12:44:35 -08004642 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004643 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004644 spvGroupOperands.push_back(scalar);
4645 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004646
Rex Xub7072052016-09-26 15:53:40 +08004647 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004648 }
4649
4650 // put the pieces together
4651 return builder.createCompositeConstruct(typeId, results);
4652}
Rex Xu2bbbe062016-08-23 15:41:05 +08004653
John Kessenich5e4b1242015-08-06 22:53:06 -06004654spv::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 -06004655{
Rex Xu8ff43de2016-04-22 16:51:45 +08004656 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004657#ifdef AMD_EXTENSIONS
4658 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4659#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004660 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004661#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004662
John Kessenich140f3df2015-06-26 16:58:36 -06004663 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004664 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004665 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004666 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004667 spv::Id typeId0 = 0;
4668 if (consumedOperands > 0)
4669 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08004670 spv::Id typeId1 = 0;
4671 if (consumedOperands > 1)
4672 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07004673 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004674
4675 switch (op) {
4676 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004677 if (isFloat)
4678 libCall = spv::GLSLstd450FMin;
4679 else if (isUnsigned)
4680 libCall = spv::GLSLstd450UMin;
4681 else
4682 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004683 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004684 break;
4685 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004686 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004687 break;
4688 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004689 if (isFloat)
4690 libCall = spv::GLSLstd450FMax;
4691 else if (isUnsigned)
4692 libCall = spv::GLSLstd450UMax;
4693 else
4694 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004695 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004696 break;
4697 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004698 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004699 break;
4700 case glslang::EOpDot:
4701 opCode = spv::OpDot;
4702 break;
4703 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004704 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004705 break;
4706
4707 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004708 if (isFloat)
4709 libCall = spv::GLSLstd450FClamp;
4710 else if (isUnsigned)
4711 libCall = spv::GLSLstd450UClamp;
4712 else
4713 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004714 builder.promoteScalar(precision, operands.front(), operands[1]);
4715 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004716 break;
4717 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004718 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4719 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004720 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004721 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004722 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004723 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004724 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004725 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004726 break;
4727 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004728 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004729 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004730 break;
4731 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004732 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004733 builder.promoteScalar(precision, operands[0], operands[2]);
4734 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004735 break;
4736
4737 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004738 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004739 break;
4740 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004741 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004742 break;
4743 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004744 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004745 break;
4746 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004747 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004748 break;
4749 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004750 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004751 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004752 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004753 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004754 libCall = spv::GLSLstd450InterpolateAtSample;
4755 break;
4756 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004757 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004758 libCall = spv::GLSLstd450InterpolateAtOffset;
4759 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004760 case glslang::EOpAddCarry:
4761 opCode = spv::OpIAddCarry;
4762 typeId = builder.makeStructResultType(typeId0, typeId0);
4763 consumedOperands = 2;
4764 break;
4765 case glslang::EOpSubBorrow:
4766 opCode = spv::OpISubBorrow;
4767 typeId = builder.makeStructResultType(typeId0, typeId0);
4768 consumedOperands = 2;
4769 break;
4770 case glslang::EOpUMulExtended:
4771 opCode = spv::OpUMulExtended;
4772 typeId = builder.makeStructResultType(typeId0, typeId0);
4773 consumedOperands = 2;
4774 break;
4775 case glslang::EOpIMulExtended:
4776 opCode = spv::OpSMulExtended;
4777 typeId = builder.makeStructResultType(typeId0, typeId0);
4778 consumedOperands = 2;
4779 break;
4780 case glslang::EOpBitfieldExtract:
4781 if (isUnsigned)
4782 opCode = spv::OpBitFieldUExtract;
4783 else
4784 opCode = spv::OpBitFieldSExtract;
4785 break;
4786 case glslang::EOpBitfieldInsert:
4787 opCode = spv::OpBitFieldInsert;
4788 break;
4789
4790 case glslang::EOpFma:
4791 libCall = spv::GLSLstd450Fma;
4792 break;
4793 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004794 {
4795 libCall = spv::GLSLstd450FrexpStruct;
4796 assert(builder.isPointerType(typeId1));
4797 typeId1 = builder.getContainedTypeId(typeId1);
4798#ifdef AMD_EXTENSIONS
4799 int width = builder.getScalarTypeWidth(typeId1);
4800#else
4801 int width = 32;
4802#endif
4803 if (builder.getNumComponents(operands[0]) == 1)
4804 frexpIntType = builder.makeIntegerType(width, true);
4805 else
4806 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
4807 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4808 consumedOperands = 1;
4809 }
John Kessenich55e7d112015-11-15 21:33:39 -07004810 break;
4811 case glslang::EOpLdexp:
4812 libCall = spv::GLSLstd450Ldexp;
4813 break;
4814
Rex Xu574ab042016-04-14 16:53:07 +08004815 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004816 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004817
Rex Xu9d93a232016-05-05 12:30:44 +08004818#ifdef AMD_EXTENSIONS
4819 case glslang::EOpSwizzleInvocations:
4820 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4821 libCall = spv::SwizzleInvocationsAMD;
4822 break;
4823 case glslang::EOpSwizzleInvocationsMasked:
4824 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4825 libCall = spv::SwizzleInvocationsMaskedAMD;
4826 break;
4827 case glslang::EOpWriteInvocation:
4828 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4829 libCall = spv::WriteInvocationAMD;
4830 break;
4831
4832 case glslang::EOpMin3:
4833 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4834 if (isFloat)
4835 libCall = spv::FMin3AMD;
4836 else {
4837 if (isUnsigned)
4838 libCall = spv::UMin3AMD;
4839 else
4840 libCall = spv::SMin3AMD;
4841 }
4842 break;
4843 case glslang::EOpMax3:
4844 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4845 if (isFloat)
4846 libCall = spv::FMax3AMD;
4847 else {
4848 if (isUnsigned)
4849 libCall = spv::UMax3AMD;
4850 else
4851 libCall = spv::SMax3AMD;
4852 }
4853 break;
4854 case glslang::EOpMid3:
4855 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4856 if (isFloat)
4857 libCall = spv::FMid3AMD;
4858 else {
4859 if (isUnsigned)
4860 libCall = spv::UMid3AMD;
4861 else
4862 libCall = spv::SMid3AMD;
4863 }
4864 break;
4865
4866 case glslang::EOpInterpolateAtVertex:
4867 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4868 libCall = spv::InterpolateAtVertexAMD;
4869 break;
4870#endif
4871
John Kessenich140f3df2015-06-26 16:58:36 -06004872 default:
4873 return 0;
4874 }
4875
4876 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004877 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004878 // Use an extended instruction from the standard library.
4879 // Construct the call arguments, without modifying the original operands vector.
4880 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4881 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004882 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004883 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004884 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004885 case 0:
4886 // should all be handled by visitAggregate and createNoArgOperation
4887 assert(0);
4888 return 0;
4889 case 1:
4890 // should all be handled by createUnaryOperation
4891 assert(0);
4892 return 0;
4893 case 2:
4894 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4895 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004896 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004897 // anything 3 or over doesn't have l-value operands, so all should be consumed
4898 assert(consumedOperands == operands.size());
4899 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004900 break;
4901 }
4902 }
4903
John Kessenich55e7d112015-11-15 21:33:39 -07004904 // Decode the return types that were structures
4905 switch (op) {
4906 case glslang::EOpAddCarry:
4907 case glslang::EOpSubBorrow:
4908 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4909 id = builder.createCompositeExtract(id, typeId0, 0);
4910 break;
4911 case glslang::EOpUMulExtended:
4912 case glslang::EOpIMulExtended:
4913 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4914 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4915 break;
4916 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004917 {
4918 assert(operands.size() == 2);
4919 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
4920 // "exp" is floating-point type (from HLSL intrinsic)
4921 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
4922 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
4923 builder.createStore(member1, operands[1]);
4924 } else
4925 // "exp" is integer type (from GLSL built-in function)
4926 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4927 id = builder.createCompositeExtract(id, typeId0, 0);
4928 }
John Kessenich55e7d112015-11-15 21:33:39 -07004929 break;
4930 default:
4931 break;
4932 }
4933
John Kessenich32cfd492016-02-02 12:37:46 -07004934 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004935}
4936
Rex Xu9d93a232016-05-05 12:30:44 +08004937// Intrinsics with no arguments (or no return value, and no precision).
4938spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004939{
4940 // TODO: get the barrier operands correct
4941
4942 switch (op) {
4943 case glslang::EOpEmitVertex:
4944 builder.createNoResultOp(spv::OpEmitVertex);
4945 return 0;
4946 case glslang::EOpEndPrimitive:
4947 builder.createNoResultOp(spv::OpEndPrimitive);
4948 return 0;
4949 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004950 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004951 return 0;
4952 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004953 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004954 return 0;
4955 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004956 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004957 return 0;
4958 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004959 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004960 return 0;
4961 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004962 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004963 return 0;
4964 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004965 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004966 return 0;
4967 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004968 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004969 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004970 case glslang::EOpAllMemoryBarrierWithGroupSync:
4971 // Control barrier with non-"None" semantic is also a memory barrier.
4972 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4973 return 0;
4974 case glslang::EOpGroupMemoryBarrierWithGroupSync:
4975 // Control barrier with non-"None" semantic is also a memory barrier.
4976 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
4977 return 0;
4978 case glslang::EOpWorkgroupMemoryBarrier:
4979 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4980 return 0;
4981 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
4982 // Control barrier with non-"None" semantic is also a memory barrier.
4983 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
4984 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08004985#ifdef AMD_EXTENSIONS
4986 case glslang::EOpTime:
4987 {
4988 std::vector<spv::Id> args; // Dummy arguments
4989 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
4990 return builder.setPrecision(id, precision);
4991 }
4992#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004993 default:
Lei Zhang17535f72016-05-04 15:55:59 -04004994 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06004995 return 0;
4996 }
4997}
4998
4999spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5000{
John Kessenich2f273362015-07-18 22:34:27 -06005001 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005002 spv::Id id;
5003 if (symbolValues.end() != iter) {
5004 id = iter->second;
5005 return id;
5006 }
5007
5008 // it was not found, create it
5009 id = createSpvVariable(symbol);
5010 symbolValues[symbol->getId()] = id;
5011
Rex Xuc884b4a2016-06-29 15:03:44 +08005012 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005013 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005014 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005015 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005016 if (symbol->getType().getQualifier().hasSpecConstantId())
5017 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005018 if (symbol->getQualifier().hasIndex())
5019 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5020 if (symbol->getQualifier().hasComponent())
5021 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5022 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005023 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005024 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005025 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005026 if (symbol->getQualifier().hasXfbBuffer())
5027 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5028 if (symbol->getQualifier().hasXfbOffset())
5029 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5030 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005031 // atomic counters use this:
5032 if (symbol->getQualifier().hasOffset())
5033 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005034 }
5035
scygan2c864272016-05-18 18:09:17 +02005036 if (symbol->getQualifier().hasLocation())
5037 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005038 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005039 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005040 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005041 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005042 }
John Kessenich140f3df2015-06-26 16:58:36 -06005043 if (symbol->getQualifier().hasSet())
5044 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005045 else if (IsDescriptorResource(symbol->getType())) {
5046 // default to 0
5047 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5048 }
John Kessenich140f3df2015-06-26 16:58:36 -06005049 if (symbol->getQualifier().hasBinding())
5050 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005051 if (symbol->getQualifier().hasAttachment())
5052 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005053 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005054 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005055 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005056 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005057 if (symbol->getQualifier().hasXfbBuffer())
5058 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5059 }
5060
Rex Xu1da878f2016-02-21 20:59:01 +08005061 if (symbol->getType().isImage()) {
5062 std::vector<spv::Decoration> memory;
5063 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5064 for (unsigned int i = 0; i < memory.size(); ++i)
5065 addDecoration(id, memory[i]);
5066 }
5067
John Kessenich140f3df2015-06-26 16:58:36 -06005068 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005069 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005070 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005071 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005072
John Kessenichecba76f2017-01-06 00:34:48 -07005073#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005074 if (builtIn == spv::BuiltInSampleMask) {
5075 spv::Decoration decoration;
5076 // GL_NV_sample_mask_override_coverage extension
5077 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005078 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005079 else
5080 decoration = (spv::Decoration)spv::DecorationMax;
5081 addDecoration(id, decoration);
5082 if (decoration != spv::DecorationMax) {
5083 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5084 }
5085 }
chaoc771d89f2017-01-13 01:10:53 -08005086 else if (builtIn == spv::BuiltInLayer) {
5087 // SPV_NV_viewport_array2 extension
5088 if (symbol->getQualifier().layoutViewportRelative)
5089 {
5090 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5091 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5092 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5093 }
5094 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5095 {
5096 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5097 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5098 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5099 }
5100 }
5101
chaoc6e5acae2016-12-20 13:28:52 -08005102 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005103 addDecoration(id, spv::DecorationPassthroughNV);
5104 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005105 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5106 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005107#endif
5108
John Kessenich140f3df2015-06-26 16:58:36 -06005109 return id;
5110}
5111
John Kessenich55e7d112015-11-15 21:33:39 -07005112// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005113void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5114{
John Kessenich4016e382016-07-15 11:53:56 -06005115 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005116 builder.addDecoration(id, dec);
5117}
5118
John Kessenich55e7d112015-11-15 21:33:39 -07005119// If 'dec' is valid, add a one-operand decoration to an object
5120void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5121{
John Kessenich4016e382016-07-15 11:53:56 -06005122 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005123 builder.addDecoration(id, dec, value);
5124}
5125
5126// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005127void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5128{
John Kessenich4016e382016-07-15 11:53:56 -06005129 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005130 builder.addMemberDecoration(id, (unsigned)member, dec);
5131}
5132
John Kessenich92187592016-02-01 13:45:25 -07005133// If 'dec' is valid, add a one-operand decoration to a struct member
5134void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5135{
John Kessenich4016e382016-07-15 11:53:56 -06005136 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005137 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5138}
5139
John Kessenich55e7d112015-11-15 21:33:39 -07005140// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005141// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005142//
5143// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5144//
5145// Recursively walk the nodes. The nodes form a tree whose leaves are
5146// regular constants, which themselves are trees that createSpvConstant()
5147// recursively walks. So, this function walks the "top" of the tree:
5148// - emit specialization constant-building instructions for specConstant
5149// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005150spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005151{
John Kessenich7cc0e282016-03-20 00:46:02 -06005152 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005153
qining4f4bb812016-04-03 23:55:17 -04005154 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005155 if (! node.getQualifier().specConstant) {
5156 // hand off to the non-spec-constant path
5157 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5158 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005159 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005160 nextConst, false);
5161 }
5162
5163 // We now know we have a specialization constant to build
5164
John Kessenichd94c0032016-05-30 19:29:40 -06005165 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005166 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5167 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5168 std::vector<spv::Id> dimConstId;
5169 for (int dim = 0; dim < 3; ++dim) {
5170 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5171 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5172 if (specConst)
5173 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5174 }
5175 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5176 }
5177
5178 // An AST node labelled as specialization constant should be a symbol node.
5179 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5180 if (auto* sn = node.getAsSymbolNode()) {
5181 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005182 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5183 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5184 // will set the builder into spec constant op instruction generating mode.
5185 sub_tree->traverse(this);
5186 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005187 } else if (auto* const_union_array = &sn->getConstArray()){
5188 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005189 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5190 builder.addName(id, sn->getName().c_str());
5191 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005192 }
5193 }
qining4f4bb812016-04-03 23:55:17 -04005194
5195 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5196 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005197 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005198 exit(1);
5199 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005200}
5201
John Kessenich140f3df2015-06-26 16:58:36 -06005202// Use 'consts' as the flattened glslang source of scalar constants to recursively
5203// build the aggregate SPIR-V constant.
5204//
5205// If there are not enough elements present in 'consts', 0 will be substituted;
5206// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5207//
qining08408382016-03-21 09:51:37 -04005208spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005209{
5210 // vector of constants for SPIR-V
5211 std::vector<spv::Id> spvConsts;
5212
5213 // Type is used for struct and array constants
5214 spv::Id typeId = convertGlslangToSpvType(glslangType);
5215
5216 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005217 glslang::TType elementType(glslangType, 0);
5218 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005219 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005220 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005221 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005222 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005223 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005224 } else if (glslangType.getStruct()) {
5225 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5226 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005227 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005228 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005229 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5230 bool zero = nextConst >= consts.size();
5231 switch (glslangType.getBasicType()) {
5232 case glslang::EbtInt:
5233 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5234 break;
5235 case glslang::EbtUint:
5236 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5237 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005238 case glslang::EbtInt64:
5239 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5240 break;
5241 case glslang::EbtUint64:
5242 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5243 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005244 case glslang::EbtFloat:
5245 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5246 break;
5247 case glslang::EbtDouble:
5248 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5249 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005250#ifdef AMD_EXTENSIONS
5251 case glslang::EbtFloat16:
5252 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5253 break;
5254#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005255 case glslang::EbtBool:
5256 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5257 break;
5258 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005259 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005260 break;
5261 }
5262 ++nextConst;
5263 }
5264 } else {
5265 // we have a non-aggregate (scalar) constant
5266 bool zero = nextConst >= consts.size();
5267 spv::Id scalar = 0;
5268 switch (glslangType.getBasicType()) {
5269 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005270 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005271 break;
5272 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005273 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005274 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005275 case glslang::EbtInt64:
5276 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5277 break;
5278 case glslang::EbtUint64:
5279 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5280 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005281 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005282 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005283 break;
5284 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005285 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005286 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005287#ifdef AMD_EXTENSIONS
5288 case glslang::EbtFloat16:
5289 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5290 break;
5291#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005292 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005293 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005294 break;
5295 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005296 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005297 break;
5298 }
5299 ++nextConst;
5300 return scalar;
5301 }
5302
5303 return builder.makeCompositeConstant(typeId, spvConsts);
5304}
5305
John Kessenich7c1aa102015-10-15 13:29:11 -06005306// Return true if the node is a constant or symbol whose reading has no
5307// non-trivial observable cost or effect.
5308bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5309{
5310 // don't know what this is
5311 if (node == nullptr)
5312 return false;
5313
5314 // a constant is safe
5315 if (node->getAsConstantUnion() != nullptr)
5316 return true;
5317
5318 // not a symbol means non-trivial
5319 if (node->getAsSymbolNode() == nullptr)
5320 return false;
5321
5322 // a symbol, depends on what's being read
5323 switch (node->getType().getQualifier().storage) {
5324 case glslang::EvqTemporary:
5325 case glslang::EvqGlobal:
5326 case glslang::EvqIn:
5327 case glslang::EvqInOut:
5328 case glslang::EvqConst:
5329 case glslang::EvqConstReadOnly:
5330 case glslang::EvqUniform:
5331 return true;
5332 default:
5333 return false;
5334 }
qining25262b32016-05-06 17:25:16 -04005335}
John Kessenich7c1aa102015-10-15 13:29:11 -06005336
5337// A node is trivial if it is a single operation with no side effects.
5338// Error on the side of saying non-trivial.
5339// Return true if trivial.
5340bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5341{
5342 if (node == nullptr)
5343 return false;
5344
5345 // symbols and constants are trivial
5346 if (isTrivialLeaf(node))
5347 return true;
5348
5349 // otherwise, it needs to be a simple operation or one or two leaf nodes
5350
5351 // not a simple operation
5352 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5353 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5354 if (binaryNode == nullptr && unaryNode == nullptr)
5355 return false;
5356
5357 // not on leaf nodes
5358 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5359 return false;
5360
5361 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5362 return false;
5363 }
5364
5365 switch (node->getAsOperator()->getOp()) {
5366 case glslang::EOpLogicalNot:
5367 case glslang::EOpConvIntToBool:
5368 case glslang::EOpConvUintToBool:
5369 case glslang::EOpConvFloatToBool:
5370 case glslang::EOpConvDoubleToBool:
5371 case glslang::EOpEqual:
5372 case glslang::EOpNotEqual:
5373 case glslang::EOpLessThan:
5374 case glslang::EOpGreaterThan:
5375 case glslang::EOpLessThanEqual:
5376 case glslang::EOpGreaterThanEqual:
5377 case glslang::EOpIndexDirect:
5378 case glslang::EOpIndexDirectStruct:
5379 case glslang::EOpLogicalXor:
5380 case glslang::EOpAny:
5381 case glslang::EOpAll:
5382 return true;
5383 default:
5384 return false;
5385 }
5386}
5387
5388// Emit short-circuiting code, where 'right' is never evaluated unless
5389// the left side is true (for &&) or false (for ||).
5390spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5391{
5392 spv::Id boolTypeId = builder.makeBoolType();
5393
5394 // emit left operand
5395 builder.clearAccessChain();
5396 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005397 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005398
5399 // Operands to accumulate OpPhi operands
5400 std::vector<spv::Id> phiOperands;
5401 // accumulate left operand's phi information
5402 phiOperands.push_back(leftId);
5403 phiOperands.push_back(builder.getBuildPoint()->getId());
5404
5405 // Make the two kinds of operation symmetric with a "!"
5406 // || => emit "if (! left) result = right"
5407 // && => emit "if ( left) result = right"
5408 //
5409 // TODO: this runtime "not" for || could be avoided by adding functionality
5410 // to 'builder' to have an "else" without an "then"
5411 if (op == glslang::EOpLogicalOr)
5412 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5413
5414 // make an "if" based on the left value
5415 spv::Builder::If ifBuilder(leftId, builder);
5416
5417 // emit right operand as the "then" part of the "if"
5418 builder.clearAccessChain();
5419 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005420 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005421
5422 // accumulate left operand's phi information
5423 phiOperands.push_back(rightId);
5424 phiOperands.push_back(builder.getBuildPoint()->getId());
5425
5426 // finish the "if"
5427 ifBuilder.makeEndIf();
5428
5429 // phi together the two results
5430 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5431}
5432
Rex Xu9d93a232016-05-05 12:30:44 +08005433// Return type Id of the imported set of extended instructions corresponds to the name.
5434// Import this set if it has not been imported yet.
5435spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5436{
5437 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5438 return extBuiltinMap[name];
5439 else {
Rex Xu51596642016-09-21 18:56:12 +08005440 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005441 spv::Id extBuiltins = builder.import(name);
5442 extBuiltinMap[name] = extBuiltins;
5443 return extBuiltins;
5444 }
5445}
5446
John Kessenich140f3df2015-06-26 16:58:36 -06005447}; // end anonymous namespace
5448
5449namespace glslang {
5450
John Kessenich68d78fd2015-07-12 19:28:10 -06005451void GetSpirvVersion(std::string& version)
5452{
John Kessenich9e55f632015-07-15 10:03:39 -06005453 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005454 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005455 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005456 version = buf;
5457}
5458
John Kessenich140f3df2015-06-26 16:58:36 -06005459// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005460void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005461{
5462 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005463 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005464 if (out.fail())
5465 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005466 for (int i = 0; i < (int)spirv.size(); ++i) {
5467 unsigned int word = spirv[i];
5468 out.write((const char*)&word, 4);
5469 }
5470 out.close();
5471}
5472
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005473// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005474void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005475{
5476 std::ofstream out;
5477 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005478 if (out.fail())
5479 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005480 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005481 if (varName != nullptr) {
5482 out << "\t #pragma once" << std::endl;
5483 out << "const uint32_t " << varName << "[] = {" << std::endl;
5484 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005485 const int WORDS_PER_LINE = 8;
5486 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5487 out << "\t";
5488 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5489 const unsigned int word = spirv[i + j];
5490 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5491 if (i + j + 1 < (int)spirv.size()) {
5492 out << ",";
5493 }
5494 }
5495 out << std::endl;
5496 }
Flavio15017db2017-02-15 14:29:33 -08005497 if (varName != nullptr) {
5498 out << "};";
5499 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005500 out.close();
5501}
5502
John Kessenich140f3df2015-06-26 16:58:36 -06005503//
5504// Set up the glslang traversal
5505//
5506void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5507{
Lei Zhang17535f72016-05-04 15:55:59 -04005508 spv::SpvBuildLogger logger;
5509 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005510}
5511
Lei Zhang17535f72016-05-04 15:55:59 -04005512void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005513{
John Kessenich140f3df2015-06-26 16:58:36 -06005514 TIntermNode* root = intermediate.getTreeRoot();
5515
5516 if (root == 0)
5517 return;
5518
5519 glslang::GetThreadPoolAllocator().push();
5520
Lei Zhang17535f72016-05-04 15:55:59 -04005521 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005522 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005523 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005524 it.dumpSpv(spirv);
5525
5526 glslang::GetThreadPoolAllocator().pop();
5527}
5528
5529}; // end namespace glslang